webrtc_mdns/message/resource/
opt.rs1use super::*;
2use crate::error::{Result, *};
3use crate::message::packer::*;
4
5#[derive(Default, Debug, Clone, PartialEq, Eq)]
10pub struct OptResource {
11 pub options: Vec<DnsOption>,
12}
13
14#[derive(Default, Debug, Clone, PartialEq, Eq)]
19pub struct DnsOption {
20 pub code: u16, pub data: Vec<u8>,
22}
23
24impl fmt::Display for DnsOption {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 write!(
27 f,
28 "dnsmessage.Option{{Code: {}, Data: {:?}}}",
29 self.code, self.data
30 )
31 }
32}
33
34impl fmt::Display for OptResource {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 let s: Vec<String> = self.options.iter().map(|o| o.to_string()).collect();
37 write!(f, "dnsmessage.OPTResource{{options: {}}}", s.join(","))
38 }
39}
40
41impl ResourceBody for OptResource {
42 fn real_type(&self) -> DnsType {
43 DnsType::Opt
44 }
45
46 fn pack(
47 &self,
48 mut msg: Vec<u8>,
49 _compression: &mut Option<HashMap<String, usize>>,
50 _compression_off: usize,
51 ) -> Result<Vec<u8>> {
52 for opt in &self.options {
53 msg = pack_uint16(msg, opt.code);
54 msg = pack_uint16(msg, opt.data.len() as u16);
55 msg = pack_bytes(msg, &opt.data);
56 }
57 Ok(msg)
58 }
59
60 fn unpack(&mut self, msg: &[u8], mut off: usize, length: usize) -> Result<usize> {
61 let mut opts = vec![];
62 let old_off = off;
63 while off < old_off + length {
64 let (code, new_off) = unpack_uint16(msg, off)?;
65 off = new_off;
66
67 let (l, new_off) = unpack_uint16(msg, off)?;
68 off = new_off;
69
70 let mut opt = DnsOption {
71 code,
72 data: vec![0; l as usize],
73 };
74 if off + l as usize > msg.len() {
75 return Err(Error::ErrCalcLen);
76 }
77 opt.data.copy_from_slice(&msg[off..off + l as usize]);
78 off += l as usize;
79 opts.push(opt);
80 }
81 self.options = opts;
82 Ok(off)
83 }
84}