rlibdns/messages/
rr_query.rs1use std::collections::HashMap;
2use std::fmt;
3use std::fmt::Formatter;
4use crate::messages::inter::rr_classes::RRClasses;
5use crate::messages::inter::rr_types::RRTypes;
6use crate::messages::message::MessageError;
7use crate::utils::fqdn_utils::{pack_fqdn, pack_fqdn_compressed, unpack_fqdn};
8
9#[derive(Debug, Clone)]
10pub struct RRQuery {
11 fqdn: String,
12 _type: RRTypes,
13 class: RRClasses
14}
15
16impl RRQuery {
17
18 pub fn new(fqdn: &str, _type: RRTypes, class: RRClasses) -> Self {
19 Self {
20 fqdn: fqdn.to_string(),
21 _type,
22 class
23 }
24 }
25
26 pub fn from_bytes(buf: &[u8], off: &mut usize) -> Result<Self, MessageError> {
27 let (fqdn, len) = unpack_fqdn(buf, *off);
28 *off += len;
29
30 let _type = RRTypes::try_from(u16::from_be_bytes([buf[*off], buf[*off+1]])).map_err(|e| MessageError::RecordError(e.to_string()))?;
31 let class = RRClasses::try_from(u16::from_be_bytes([buf[*off+2], buf[*off+3]])).map_err(|e| MessageError::RecordError(e.to_string()))?;
32 *off += 4;
33
34 Ok(Self {
35 fqdn,
36 _type,
37 class
38 })
39 }
40
41 pub fn to_bytes_compressed(&self, compression_data: &mut HashMap<String, usize>, off: usize) -> Vec<u8> {
42 let mut buf = pack_fqdn_compressed(&self.fqdn, compression_data, off);
43
44 buf.extend_from_slice(&self._type.get_code().to_be_bytes());
45 buf.extend_from_slice(&self.class.get_code().to_be_bytes());
46
47 buf
48 }
49
50 pub fn to_bytes(&self) -> Vec<u8> {
51 let mut buf = pack_fqdn(&self.fqdn);
52
53 buf.extend_from_slice(&self._type.get_code().to_be_bytes());
54 buf.extend_from_slice(&self.class.get_code().to_be_bytes());
55
56 buf
57 }
58
59 pub fn set_fqdn(&mut self, fqdn: &str) {
60 self.fqdn = fqdn.to_string();
61 }
62
63 pub fn get_fqdn(&self) -> &str {
64 &self.fqdn
65 }
66
67 pub fn set_type(&mut self, _type: RRTypes) {
68 self._type = _type;
69 }
70
71 pub fn get_type(&self) -> RRTypes {
72 self._type
73 }
74
75 pub fn set_class(&mut self, class: RRClasses) {
76 self.class = class;
77 }
78
79 pub fn get_class(&self) -> RRClasses {
80 self.class
81 }
82
83 pub fn as_ref(&self) -> &Self {
84 self
85 }
86
87 pub fn as_mut(&mut self) -> &mut Self {
88 self
89 }
90}
91
92impl fmt::Display for RRQuery {
93
94 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
95 write!(f, "{:<31}{:<8}{}", format!("{}.", self.fqdn), self.class.to_string(), self._type)
96 }
97}