hickory_proto/rr/rdata/
txt.rs1use alloc::{boxed::Box, string::String, vec::Vec};
10use core::fmt;
11
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 error::ProtoResult,
17 rr::{RData, RecordData, RecordDataDecodable, RecordType},
18 serialize::{binary::*, txt::ParseError},
19};
20
21#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
35#[derive(Debug, PartialEq, Eq, Hash, Clone)]
36#[non_exhaustive]
37pub struct TXT {
38 pub txt_data: Box<[Box<[u8]>]>,
42}
43
44impl TXT {
45 pub fn try_new(
50 txt_data: impl Iterator<Item = impl Into<Box<[u8]>>>,
51 ) -> Result<Self, ParseError> {
52 Self::new_inner(txt_data.map(Into::into).collect::<Box<[_]>>())
53 }
54
55 #[deprecated(since = "0.26.4", note = "use `try_new()` or `try_from()` instead")]
57 pub fn new(txt_data: Vec<String>) -> Self {
58 Self {
59 txt_data: txt_data
60 .into_iter()
61 .map(|s| s.into_bytes().into_boxed_slice())
62 .collect::<Vec<_>>()
63 .into_boxed_slice(),
64 }
65 }
66
67 #[deprecated(since = "0.26.4", note = "use `try_new()` or `try_from()` instead")]
69 pub fn from_bytes(txt_data: Vec<&[u8]>) -> Self {
70 Self {
71 txt_data: txt_data
72 .into_iter()
73 .map(|s| s.to_vec().into_boxed_slice())
74 .collect::<Vec<_>>()
75 .into_boxed_slice(),
76 }
77 }
78
79 #[allow(clippy::unnecessary_wraps)]
81 pub(crate) fn from_tokens<'i, I: Iterator<Item = &'i str>>(
82 tokens: I,
83 ) -> Result<Self, ParseError> {
84 let txt_data = tokens
85 .map(|s| Box::from(s.as_bytes()))
86 .collect::<Box<[_]>>();
87
88 if txt_data.is_empty() {
89 return Err(ParseError::Message(
90 "TXT record must contain at least one character-string",
91 ));
92 }
93
94 Self::new_inner(txt_data)
95 }
96
97 fn new_inner(txt_data: Box<[Box<[u8]>]>) -> Result<Self, ParseError> {
98 let mut total = 0;
99 for part in txt_data.iter() {
100 total += 1 + part.len();
102 if part.len() > 255 {
103 return Err(ParseError::Message(
104 "character-string in TXT record must not exceed 255 octets",
105 ));
106 }
107 }
108
109 if total > 65535 {
110 return Err(ParseError::Message(
111 "TXT record data must not exceed 65535 octets",
112 ));
113 }
114
115 Ok(Self { txt_data })
116 }
117}
118
119impl BinEncodable for TXT {
120 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
121 for s in &self.txt_data {
122 encoder.emit_character_data(s)?;
123 }
124
125 Ok(())
126 }
127}
128
129impl RecordDataDecodable<'_> for TXT {
130 fn read_data(
131 decoder: &mut BinDecoder<'_>,
132 rdata_length: Restrict<u16>,
133 ) -> Result<Self, DecodeError> {
134 let data_len = decoder.len();
135 let mut strings = Vec::with_capacity(1);
136
137 let rdata_length =
139 rdata_length.map(|u| u as usize).unverified();
140 while data_len - decoder.len() < rdata_length {
141 let string = decoder.read_character_data()?.unverified();
142 strings.push(string.to_vec().into_boxed_slice());
143 }
144 Ok(Self {
145 txt_data: strings.into_boxed_slice(),
146 })
147 }
148}
149
150impl RecordData for TXT {
151 fn try_borrow(data: &RData) -> Option<&Self> {
152 match data {
153 RData::TXT(data) => Some(data),
154 _ => None,
155 }
156 }
157
158 fn record_type(&self) -> RecordType {
159 RecordType::TXT
160 }
161
162 fn into_rdata(self) -> RData {
163 RData::TXT(self)
164 }
165}
166
167impl TryFrom<String> for TXT {
168 type Error = ParseError;
169
170 fn try_from(value: String) -> Result<Self, Self::Error> {
171 Self::new_inner(Box::new([value.into_boxed_str().into()]))
172 }
173}
174
175impl fmt::Display for TXT {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
198 for txt in self.txt_data.iter() {
199 f.write_str(&String::from_utf8_lossy(txt))?;
200 }
201
202 Ok(())
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 #![allow(clippy::dbg_macro, clippy::print_stdout)]
209
210 #[cfg(feature = "std")]
211 use std::println;
212
213 use super::*;
214
215 #[test]
216 fn test() {
217 let rdata =
218 TXT::try_new([b"Test me some".to_vec(), b"more please".to_vec()].into_iter()).unwrap();
219
220 let mut bytes = Vec::new();
221 let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
222 assert!(rdata.emit(&mut encoder).is_ok());
223 let bytes = encoder.into_bytes();
224
225 #[cfg(feature = "std")]
226 println!("bytes: {bytes:?}");
227
228 let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
229 let restrict = Restrict::new(bytes.len() as u16);
230 let read_rdata = TXT::read_data(&mut decoder, restrict).expect("Decoding error");
231 assert_eq!(rdata, read_rdata);
232 }
233
234 #[test]
235 fn publish_binary_txt_record() {
236 let bin_data = vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
237 let rdata = TXT::try_new([b"Test me some".to_vec(), bin_data].into_iter()).unwrap();
238
239 let mut bytes = Vec::new();
240 let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
241 assert!(rdata.emit(&mut encoder).is_ok());
242 let bytes = encoder.into_bytes();
243
244 #[cfg(feature = "std")]
245 println!("bytes: {bytes:?}");
246
247 let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
248 let restrict = Restrict::new(bytes.len() as u16);
249 let read_rdata = TXT::read_data(&mut decoder, restrict).expect("Decoding error");
250 assert_eq!(rdata, read_rdata);
251 }
252
253 #[test]
254 fn empty_txt_is_rejected() {
255 assert!(TXT::from_tokens([].into_iter()).is_err());
256 }
257
258 #[test]
259 fn empty_character_string_is_allowed() {
260 let txt = TXT::try_new([Vec::new()].into_iter()).unwrap();
261
262 assert_eq!(txt.txt_data.len(), 1);
263 assert!(txt.txt_data[0].is_empty());
264 }
265
266 #[test]
267 fn from_tokens_string_at_limit() {
268 let token = "a".repeat(255);
270 let rdata = TXT::from_tokens([token.as_str()].into_iter())
271 .expect("a 255-octet character-string should be allowed");
272 assert_eq!(rdata.txt_data.len(), 1);
273 assert_eq!(rdata.txt_data[0].len(), 255);
274 }
275
276 #[test]
277 fn from_tokens_string_over_limit() {
278 let token = "a".repeat(256);
280 assert!(
281 TXT::from_tokens([token.as_str()].into_iter()).is_err(),
282 "a character-string longer than 255 octets should be rejected"
283 );
284 }
285
286 #[test]
287 fn from_tokens_many_strings_allowed() {
288 let tokens = vec!["a"; 256];
291 let rdata = TXT::from_tokens(tokens.iter().copied())
292 .expect("many short character-strings should be allowed");
293 assert_eq!(rdata.txt_data.len(), 256);
294 }
295
296 #[test]
297 fn from_tokens_total_data_at_limit() {
298 let token = "a".repeat(255);
300 let tokens = vec![token.as_str(); 255];
301 let rdata = TXT::from_tokens(tokens.into_iter())
302 .expect("total TXT data within 65535 octets should be allowed");
303 assert_eq!(rdata.txt_data.len(), 255);
304 }
305
306 #[test]
307 fn from_tokens_total_data_over_limit() {
308 let token = "a".repeat(255);
313 let tokens = vec![token.as_str(); 256];
314 assert!(
315 TXT::from_tokens(tokens.into_iter()).is_err(),
316 "total TXT data exceeding 65535 octets should be rejected"
317 );
318 }
319}