Skip to main content

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
48impl From<AAAA> for Ipv6Addr {
49    fn from(aaaa: AAAA) -> Self {
50        aaaa.address.into()
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use crate::lib::FromStr;
57    use crate::lib::Vec;
58
59    use super::*;
60
61    #[test]
62    fn parse_and_write_a() {
63        let address = Ipv6Addr::from_str("FF02::FB").unwrap();
64        let aaaa = AAAA {
65            address: address.into(),
66        };
67
68        let mut bytes = Vec::new();
69        assert!(aaaa.write_to(&mut bytes).is_ok());
70
71        let aaaa = AAAA::parse(&mut BytesBuffer::new(&bytes));
72        assert!(aaaa.is_ok());
73        let aaaa = aaaa.unwrap();
74
75        assert_eq!(address, Ipv6Addr::from(aaaa.address));
76        assert_eq!(bytes.len(), aaaa.len());
77    }
78
79    #[test]
80    #[cfg(feature = "std")]
81    fn parse_sample() -> Result<(), Box<dyn std::error::Error>> {
82        use crate::{rdata::RData, ResourceRecord};
83
84        let sample_file = std::fs::read("samples/zonefile/AAAA.sample")?;
85        let sample_ip: u128 = "fd92:7065:b8e:ffff::5".parse::<Ipv6Addr>()?.into();
86
87        let sample_rdata = match ResourceRecord::parse(&mut BytesBuffer::new(&sample_file))?.rdata {
88            RData::AAAA(rdata) => rdata,
89            _ => unreachable!(),
90        };
91
92        assert_eq!(sample_rdata.address, sample_ip);
93        Ok(())
94    }
95
96    #[test]
97    fn test_from_conversions() {
98        let ip = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
99        let aaaa = AAAA::from(ip);
100        assert_eq!(ip, Ipv6Addr::from(aaaa));
101    }
102}