simple_dns/dns/rdata/
a.rs

1use crate::dns::WireFormat;
2use std::{convert::TryInto, net::Ipv4Addr};
3
4use super::RR;
5
6/// Represents a Resource Address (IPv4)
7#[derive(Debug, PartialEq, Eq, Hash, Clone)]
8pub struct A {
9    /// a 32 bit ip address
10    pub address: u32,
11}
12
13impl RR for A {
14    const TYPE_CODE: u16 = 1;
15}
16
17impl<'a> WireFormat<'a> for A {
18    fn parse(data: &'a [u8], position: &mut usize) -> crate::Result<Self>
19    where
20        Self: Sized,
21    {
22        let address = u32::from_be_bytes(data[*position..*position + 4].try_into()?);
23        *position += 4;
24        Ok(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    fn len(&self) -> usize {
33        4
34    }
35}
36
37impl A {
38    /// Transforms the inner data into its owned type
39    pub fn into_owned(self) -> Self {
40        self
41    }
42}
43
44impl From<Ipv4Addr> for A {
45    fn from(addr: Ipv4Addr) -> Self {
46        Self {
47            address: addr.into(),
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use crate::{rdata::RData, ResourceRecord};
55
56    use super::*;
57
58    #[test]
59    fn parse_and_write_a() {
60        let a = A {
61            address: 2130706433,
62        };
63
64        let mut bytes = Vec::new();
65        assert!(a.write_to(&mut bytes).is_ok());
66
67        let a = A::parse(&bytes, &mut 0);
68        assert!(a.is_ok());
69        let a = a.unwrap();
70
71        assert_eq!(2130706433, a.address);
72        assert_eq!(bytes.len(), a.len());
73    }
74
75    #[test]
76    fn parse_sample() -> Result<(), Box<dyn std::error::Error>> {
77        let sample_a = std::fs::read("samples/zonefile/A.sample.A")?;
78        let sample_ip: u32 = "26.3.0.103".parse::<Ipv4Addr>()?.into();
79
80        let sample_a_rdata = match ResourceRecord::parse(&sample_a, &mut 0)?.rdata {
81            RData::A(a) => a,
82            _ => unreachable!(),
83        };
84
85        assert_eq!(sample_a_rdata.address, sample_ip);
86        Ok(())
87    }
88}