simple_dns/dns/rdata/
aaaa.rs

1use crate::{
2    bytes_buffer::BytesBuffer,
3    dns::WireFormat,
4    lib::{Ipv6Addr, Write},
5};
6
7use super::RR;
8
9/// Represents a Resource Address (IPv6) [rfc3596](https://tools.ietf.org/html/rfc3596)
10#[derive(Debug, PartialEq, Eq, Hash, Clone)]
11pub struct AAAA {
12    /// a 128 bit ip address
13    pub address: u128,
14}
15
16impl RR for AAAA {
17    const TYPE_CODE: u16 = 28;
18}
19
20impl WireFormat<'_> for AAAA {
21    const MINIMUM_LEN: usize = 16;
22
23    fn parse(data: &mut BytesBuffer) -> crate::Result<Self>
24    where
25        Self: Sized,
26    {
27        data.get_u128().map(|address| Self { address })
28    }
29
30    fn write_to<T: Write>(&self, out: &mut T) -> crate::Result<()> {
31        out.write_all(&self.address.to_be_bytes())
32    }
33}
34
35impl AAAA {
36    /// Transforms the inner data into its owned type
37    pub fn into_owned(self) -> Self {
38        self
39    }
40}
41
42impl From<Ipv6Addr> for AAAA {
43    fn from(ip: Ipv6Addr) -> Self {
44        Self { address: ip.into() }
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use crate::lib::FromStr;
51    use crate::lib::Vec;
52
53    use super::*;
54
55    #[test]
56    fn parse_and_write_a() {
57        let address = Ipv6Addr::from_str("FF02::FB").unwrap();
58        let aaaa = AAAA {
59            address: address.into(),
60        };
61
62        let mut bytes = Vec::new();
63        assert!(aaaa.write_to(&mut bytes).is_ok());
64
65        let aaaa = AAAA::parse(&mut BytesBuffer::new(&bytes));
66        assert!(aaaa.is_ok());
67        let aaaa = aaaa.unwrap();
68
69        assert_eq!(address, Ipv6Addr::from(aaaa.address));
70        assert_eq!(bytes.len(), aaaa.len());
71    }
72
73    #[test]
74    #[cfg(feature = "std")]
75    fn parse_sample() -> Result<(), Box<dyn std::error::Error>> {
76        use crate::{rdata::RData, ResourceRecord};
77
78        let sample_file = std::fs::read("samples/zonefile/AAAA.sample")?;
79        let sample_ip: u128 = "fd92:7065:b8e:ffff::5".parse::<Ipv6Addr>()?.into();
80
81        let sample_rdata = match ResourceRecord::parse(&mut BytesBuffer::new(&sample_file))?.rdata {
82            RData::AAAA(rdata) => rdata,
83            _ => unreachable!(),
84        };
85
86        assert_eq!(sample_rdata.address, sample_ip);
87        Ok(())
88    }
89}