Skip to main content

simple_dns/dns/rdata/
a.rs

1use crate::{
2    bytes_buffer::BytesBuffer,
3    dns::WireFormat,
4    lib::{Ipv4Addr, Write},
5};
6
7use super::RR;
8
9/// Represents a Resource Address (IPv4)
10#[derive(Debug, PartialEq, Eq, Hash, Clone)]
11pub struct A {
12    /// a 32 bit ip address
13    pub address: u32,
14}
15
16impl RR for A {
17    const TYPE_CODE: u16 = 1;
18}
19
20impl<'a> WireFormat<'a> for A {
21    const MINIMUM_LEN: usize = 4;
22
23    fn parse(data: &mut BytesBuffer<'a>) -> crate::Result<Self>
24    where
25        Self: Sized,
26    {
27        data.get_u32().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 A {
36    /// Transforms the inner data into its owned type
37    pub fn into_owned(self) -> Self {
38        self
39    }
40}
41
42impl From<Ipv4Addr> for A {
43    fn from(addr: Ipv4Addr) -> Self {
44        Self {
45            address: addr.into(),
46        }
47    }
48}
49
50impl From<A> for Ipv4Addr {
51    fn from(a: A) -> Self {
52        a.address.into()
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use crate::lib::Vec;
59
60    use super::*;
61
62    #[test]
63    fn parse_and_write_a() {
64        let a = A {
65            address: 2130706433,
66        };
67
68        let mut bytes = Vec::new();
69        assert!(a.write_to(&mut bytes).is_ok());
70
71        let a = A::parse(&mut BytesBuffer::new(&bytes));
72        assert!(a.is_ok());
73        let a = a.unwrap();
74
75        assert_eq!(2130706433, a.address);
76        assert_eq!(bytes.len(), a.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        let sample_a = std::fs::read("samples/zonefile/A.sample.A")?;
84        let sample_ip: u32 = "26.3.0.103".parse::<Ipv4Addr>()?.into();
85
86        let sample_a_rdata = match ResourceRecord::parse(&mut BytesBuffer::new(&sample_a))?.rdata {
87            RData::A(a) => a,
88            _ => unreachable!(),
89        };
90
91        assert_eq!(sample_a_rdata.address, sample_ip);
92        Ok(())
93    }
94
95    #[test]
96    fn test_from_conversions() {
97        let ip = Ipv4Addr::new(127, 0, 0, 1);
98        let a = A::from(ip);
99        assert_eq!(ip, Ipv4Addr::from(a));
100    }
101}