1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::convert::TryInto;
use crate::dns::DnsPacketContent;
use crate::Name;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct SRV<'a> {
pub priority: u16,
pub weight: u16,
pub port: u16,
pub target: Name<'a>,
}
impl<'a> SRV<'a> {
pub fn into_owned<'b>(self) -> SRV<'b> {
SRV {
priority: self.priority,
weight: self.weight,
port: self.port,
target: self.target.into_owned(),
}
}
}
impl<'a> DnsPacketContent<'a> for SRV<'a> {
fn parse(data: &'a [u8], position: usize) -> crate::Result<Self>
where
Self: Sized,
{
let priority = u16::from_be_bytes(data[position..position + 2].try_into()?);
let weight = u16::from_be_bytes(data[position + 2..position + 4].try_into()?);
let port = u16::from_be_bytes(data[position + 4..position + 6].try_into()?);
let target = Name::parse(data, position + 6)?;
Ok(Self {
priority,
weight,
port,
target,
})
}
fn append_to_vec(&self, out: &mut Vec<u8>) -> crate::Result<()> {
out.extend(self.priority.to_be_bytes());
out.extend(self.weight.to_be_bytes());
out.extend(self.port.to_be_bytes());
self.target.append_to_vec(out)
}
fn len(&self) -> usize {
self.target.len() + 6
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_and_write_srv() {
let srv = SRV {
priority: 1,
weight: 2,
port: 3,
target: Name::new("_srv._tcp.example.com").unwrap(),
};
let mut bytes = Vec::new();
assert!(srv.append_to_vec(&mut bytes).is_ok());
let srv = SRV::parse(&bytes, 0);
assert!(srv.is_ok());
let srv = srv.unwrap();
assert_eq!(1, srv.priority);
assert_eq!(2, srv.weight);
assert_eq!(3, srv.port);
assert_eq!(bytes.len(), srv.len());
}
}