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
50#[cfg(test)]
51mod tests {
52    use crate::lib::Vec;
53
54    use super::*;
55
56    #[test]
57    fn parse_and_write_a() {
58        let a = A {
59            address: 2130706433,
60        };
61
62        let mut bytes = Vec::new();
63        assert!(a.write_to(&mut bytes).is_ok());
64
65        let a = A::parse(&mut BytesBuffer::new(&bytes));
66        assert!(a.is_ok());
67        let a = a.unwrap();
68
69        assert_eq!(2130706433, a.address);
70        assert_eq!(bytes.len(), a.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        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(&mut BytesBuffer::new(&sample_a))?.rdata {
81            RData::A(a) => a,
82            _ => unreachable!(),
83        };
84
85        assert_eq!(sample_a_rdata.address, sample_ip);
86        Ok(())
87    }
88}