simple_dns/dns/rdata/
rp.rs

1use std::collections::HashMap;
2
3use crate::{
4    bytes_buffer::BytesBuffer,
5    dns::{name::Label, Name, WireFormat},
6};
7
8use super::RR;
9
10/// RP Responsible Person, [RFC 1183](https://datatracker.ietf.org/doc/html/rfc1183#section-2.2)
11#[derive(Debug, PartialEq, Eq, Hash, Clone)]
12pub struct RP<'a> {
13    /// A [Name](`Name`) which specifies a mailbox for the responsble person.
14    pub mbox: Name<'a>,
15    /// A [Name](`Name`) which specifies a domain name the TXT records.
16    pub txt: Name<'a>,
17}
18
19impl RR for RP<'_> {
20    const TYPE_CODE: u16 = 17;
21}
22
23impl RP<'_> {
24    /// Transforms the inner data into its owned type
25    pub fn into_owned<'b>(self) -> RP<'b> {
26        RP {
27            mbox: self.mbox.into_owned(),
28            txt: self.txt.into_owned(),
29        }
30    }
31}
32
33impl<'a> WireFormat<'a> for RP<'a> {
34    const MINIMUM_LEN: usize = 0;
35    fn parse(data: &mut BytesBuffer<'a>) -> crate::Result<Self>
36    where
37        Self: Sized,
38    {
39        let mbox = Name::parse(data)?;
40        let txt = Name::parse(data)?;
41
42        Ok(RP { mbox, txt })
43    }
44
45    fn write_to<T: std::io::Write>(&self, out: &mut T) -> crate::Result<()> {
46        self.mbox.write_to(out)?;
47        self.txt.write_to(out)
48    }
49
50    fn write_compressed_to<T: std::io::Write + std::io::Seek>(
51        &'a self,
52        out: &mut T,
53        name_refs: &mut HashMap<&'a [Label<'a>], usize>,
54    ) -> crate::Result<()> {
55        self.mbox.write_compressed_to(out, name_refs)?;
56        self.txt.write_compressed_to(out, name_refs)
57    }
58
59    fn len(&self) -> usize {
60        self.txt.len() + self.mbox.len()
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use crate::{rdata::RData, ResourceRecord};
67
68    use super::*;
69
70    #[test]
71    fn parse_and_write_rp() {
72        let rp = RP {
73            mbox: Name::new("mbox.rp.com").unwrap(),
74            txt: Name::new("txt.rp.com").unwrap(),
75        };
76
77        let mut data = Vec::new();
78        assert!(rp.write_to(&mut data).is_ok());
79
80        let rp = RP::parse(&mut data[..].into());
81        assert!(rp.is_ok());
82        let rp = rp.unwrap();
83
84        assert_eq!(data.len(), rp.len());
85        assert_eq!("mbox.rp.com", rp.mbox.to_string());
86        assert_eq!("txt.rp.com", rp.txt.to_string());
87    }
88
89    #[test]
90    fn parse_sample() -> Result<(), Box<dyn std::error::Error>> {
91        let sample_file = std::fs::read("samples/zonefile/RP.sample")?;
92
93        let sample_rdata = match ResourceRecord::parse(&mut sample_file[..].into())?.rdata {
94            RData::RP(rdata) => rdata,
95            _ => unreachable!(),
96        };
97
98        assert_eq!(sample_rdata.mbox, "mbox-dname.sample".try_into()?);
99        assert_eq!(sample_rdata.txt, "txt-dname.sample".try_into()?);
100        Ok(())
101    }
102}