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 alloc::vec::Vec;
9#[cfg(not(feature = "std"))]
10use core::net::SocketAddr;
11#[cfg(feature = "std")]
12use std::net::SocketAddr;
13
14use crate::error::ProtoResult;
15use crate::op::Message;
16
17/// A DNS message in serialized form, with either the target address or source address
18pub struct SerialMessage {
19    // TODO: change to Bytes? this would be more compatible with some underlying libraries
20    message: Vec<u8>,
21    addr: SocketAddr,
22}
23
24impl SerialMessage {
25    /// Construct a new SerialMessage and the source or destination address
26    pub fn new(message: Vec<u8>, addr: SocketAddr) -> Self {
27        Self { message, addr }
28    }
29
30    /// Get a reference to the bytes
31    pub fn bytes(&self) -> &[u8] {
32        &self.message
33    }
34
35    /// Get the source or destination address (context dependent)
36    pub fn addr(&self) -> SocketAddr {
37        self.addr
38    }
39
40    /// Unwrap the Bytes and address
41    pub fn into_parts(self) -> (Vec<u8>, SocketAddr) {
42        self.into()
43    }
44
45    /// Build a `SerialMessage` from some bytes and an address
46    pub fn from_parts(message: Vec<u8>, addr: SocketAddr) -> Self {
47        (message, addr).into()
48    }
49
50    /// Deserializes the inner data into a Message
51    pub fn to_message(&self) -> ProtoResult<Message> {
52        Message::from_vec(&self.message)
53    }
54}
55
56impl From<(Vec<u8>, SocketAddr)> for SerialMessage {
57    fn from((message, addr): (Vec<u8>, SocketAddr)) -> Self {
58        Self { message, addr }
59    }
60}
61
62impl From<SerialMessage> for (Vec<u8>, SocketAddr) {
63    fn from(msg: SerialMessage) -> Self {
64        let SerialMessage { message, addr } = msg;
65        (message, addr)
66    }
67}