Skip to main content

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