1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::borrow::Cow;

use crate::dns::{WireFormat, MAX_NULL_LENGTH};

use super::RR;

/// NULL resources are used to represent any kind of information.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct NULL<'a> {
    length: u16,
    data: Cow<'a, [u8]>,
}

impl<'a> RR for NULL<'a> {
    const TYPE_CODE: u16 = 10;
}

impl<'a> NULL<'a> {
    /// Creates a new NULL rdata
    pub fn new(data: &'a [u8]) -> crate::Result<Self> {
        if data.len() > MAX_NULL_LENGTH {
            return Err(crate::SimpleDnsError::InvalidDnsPacket);
        }

        Ok(Self {
            length: data.len() as u16,
            data: Cow::Borrowed(data),
        })
    }

    /// get a read only reference to internal data
    pub fn get_data(&'_ self) -> &'_ [u8] {
        &self.data
    }

    /// Transforms the inner data into its owned type
    pub fn into_owned<'b>(self) -> NULL<'b> {
        NULL {
            length: self.length,
            data: self.data.into_owned().into(),
        }
    }
}

impl<'a> WireFormat<'a> for NULL<'a> {
    fn parse(data: &'a [u8], position: &mut usize) -> crate::Result<Self>
    where
        Self: Sized,
    {
        let data = &data[*position..];
        *position += data.len();
        Self::new(data)
    }

    fn write_to<T: std::io::Write>(&self, out: &mut T) -> crate::Result<()> {
        out.write_all(&self.data)
            .map_err(crate::SimpleDnsError::from)
    }

    fn len(&self) -> usize {
        self.length as usize
    }
}