webrtc_mdns/message/resource/
txt.rs

1use super::*;
2use crate::error::*;
3use crate::message::packer::*;
4
5// A TXTResource is a txt Resource record.
6#[derive(Default, Debug, Clone, PartialEq, Eq)]
7pub struct TxtResource {
8    pub txt: Vec<String>,
9}
10
11impl fmt::Display for TxtResource {
12    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13        if self.txt.is_empty() {
14            write!(f, "dnsmessage.TXTResource{{txt: {{}}}}",)
15        } else {
16            write!(f, "dnsmessage.TXTResource{{txt: {{{}}}", self.txt.join(","))
17        }
18    }
19}
20
21impl ResourceBody for TxtResource {
22    fn real_type(&self) -> DnsType {
23        DnsType::Txt
24    }
25
26    // pack appends the wire format of the TXTResource to msg.
27    fn pack(
28        &self,
29        mut msg: Vec<u8>,
30        _compression: &mut Option<HashMap<String, usize>>,
31        _compression_off: usize,
32    ) -> Result<Vec<u8>> {
33        for s in &self.txt {
34            msg = pack_str(msg, s)?
35        }
36        Ok(msg)
37    }
38
39    fn unpack(&mut self, msg: &[u8], mut off: usize, length: usize) -> Result<usize> {
40        let mut txts = vec![];
41        let mut n = 0;
42        while n < length {
43            let (t, new_off) = unpack_str(msg, off)?;
44            off = new_off;
45            // Check if we got too many bytes.
46            if length < n + t.as_bytes().len() + 1 {
47                return Err(Error::ErrCalcLen);
48            }
49            n += t.len() + 1;
50            txts.push(t);
51        }
52        self.txt = txts;
53
54        Ok(off)
55    }
56}