hickory_proto/xfer/serial_message.rs
1// Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use std::net::SocketAddr;
9
10use crate::error::ProtoResult;
11use crate::op::Message;
12
13/// A DNS message in serialized form, with either the target address or source address
14pub struct SerialMessage {
15 // TODO: change to Bytes? this would be more compatible with some underlying libraries
16 message: Vec<u8>,
17 addr: SocketAddr,
18}
19
20impl SerialMessage {
21 /// Construct a new SerialMessage and the source or destination address
22 pub fn new(message: Vec<u8>, addr: SocketAddr) -> Self {
23 Self { message, addr }
24 }
25
26 /// Get a reference to the bytes
27 pub fn bytes(&self) -> &[u8] {
28 &self.message
29 }
30
31 /// Get the source or destination address (context dependent)
32 pub fn addr(&self) -> SocketAddr {
33 self.addr
34 }
35
36 /// Unwrap the Bytes and address
37 pub fn into_parts(self) -> (Vec<u8>, SocketAddr) {
38 self.into()
39 }
40
41 /// Build a `SerialMessage` from some bytes and an address
42 pub fn from_parts(message: Vec<u8>, addr: SocketAddr) -> Self {
43 (message, addr).into()
44 }
45
46 /// Deserializes the inner data into a Message
47 pub fn to_message(&self) -> ProtoResult<Message> {
48 Message::from_vec(&self.message)
49 }
50}
51
52impl From<(Vec<u8>, SocketAddr)> for SerialMessage {
53 fn from((message, addr): (Vec<u8>, SocketAddr)) -> Self {
54 Self { message, addr }
55 }
56}
57
58impl From<SerialMessage> for (Vec<u8>, SocketAddr) {
59 fn from(msg: SerialMessage) -> Self {
60 let SerialMessage { message, addr } = msg;
61 (message, addr)
62 }
63}