simple_dns/dns/rdata/
aaaa.rs

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