1use crate::utils::init;
19
20use super::{
21 EitherIter, TLVElement, TLVSequenceIter, TLVSequenceTLVIter, TLVTag, TLVValue, TLVValueType,
22 TLVWrite, TlvError, TLV,
23};
24
25pub use builder::*;
26pub use container::*;
27pub use maybe::*;
28pub use octets::*;
29pub use skippable::*;
30pub use slice::*;
31pub use str::*;
32
33mod array;
34mod bitflags;
35mod builder;
36mod container;
37mod maybe;
38mod octets;
39mod primitive;
40mod skippable;
41mod slice;
42mod str;
43mod vec;
44
45pub trait FromTLV<'a>: Sized + 'a {
48 fn from_tlv(element: &TLVElement<'a>) -> Result<Self, TlvError>;
50
51 fn init_from_tlv(element: TLVElement<'a>) -> impl init::Init<Self, TlvError> {
54 unsafe {
55 init::init_from_closure(move |slot| {
56 core::ptr::write(slot, Self::from_tlv(&element)?);
57
58 Ok(())
59 })
60 }
61 }
62
63 fn nullable_from_tlv(element: &TLVElement<'a>) -> Result<Self, TlvError> {
69 Self::from_tlv(element)
70 }
71
72 fn init_nullable_from_tlv(element: TLVElement<'a>) -> impl init::Init<Self, TlvError> {
79 unsafe {
80 init::init_from_closure(move |slot| {
81 core::ptr::write(slot, Self::nullable_from_tlv(&element)?);
82
83 Ok(())
84 })
85 }
86 }
87}
88
89pub trait ToTLV {
92 fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, tw: W) -> Result<(), TlvError>;
94
95 fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>>;
98
99 fn nullable_to_tlv<W: TLVWrite>(&self, tag: &TLVTag, tw: W) -> Result<(), TlvError> {
105 self.to_tlv(tag, tw)
106 }
107
108 fn nullable_tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
115 self.tlv_iter(tag)
116 }
117}
118
119impl<T> ToTLV for &T
120where
121 T: ToTLV,
122{
123 fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, tw: W) -> Result<(), TlvError> {
124 (*self).to_tlv(tag, tw)
125 }
126
127 fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
128 (*self).tlv_iter(tag)
129 }
130
131 fn nullable_to_tlv<W: TLVWrite>(&self, tag: &TLVTag, tw: W) -> Result<(), TlvError> {
132 (*self).nullable_to_tlv(tag, tw)
133 }
134
135 fn nullable_tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
136 (*self).nullable_tlv_iter(tag)
137 }
138}
139
140impl<'a> FromTLV<'a> for TLVElement<'a> {
141 fn from_tlv(element: &TLVElement<'a>) -> Result<Self, TlvError> {
142 Ok(element.clone())
143 }
144}
145
146impl ToTLV for TLVElement<'_> {
147 fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, mut tw: W) -> Result<(), TlvError> {
148 if self.is_empty() {
149 Ok(())
152 } else {
153 let value_type = self.control()?.value_type;
154 let payload = self.raw_value()?;
155
156 let size_len = value_type.variable_size_len();
162 if size_len > 0 {
163 let len_bytes = (payload.len() as u64).to_le_bytes();
164 tw.raw_value(tag, value_type, &len_bytes[..size_len])?;
165 Ok(tw.write_raw_data(payload.iter().copied())?)
166 } else {
167 Ok(tw.raw_value(tag, value_type, payload)?)
168 }
169 }
170 }
171
172 fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
173 TLVElementTLVIter::Start(tag, self.clone())
174 }
175}
176
177enum TLVElementTLVIter<'a> {
178 Start(TLVTag, TLVElement<'a>),
179 Seq(TLVSequenceTLVIter<'a>),
180 Finished,
181}
182
183impl<'a> Iterator for TLVElementTLVIter<'a> {
184 type Item = Result<TLV<'a>, TlvError>;
185
186 fn next(&mut self) -> Option<Self::Item> {
187 match core::mem::replace(self, Self::Finished) {
188 TLVElementTLVIter::Start(tag, elem) => {
189 if elem.is_empty() {
190 None
193 } else {
194 let value = elem.value().map(|value| TLV::new(tag, value));
195
196 if let Ok(seq) = elem.container() {
197 *self = Self::Seq(seq.tlv_iter());
198 } else {
199 *self = TLVElementTLVIter::Finished;
200 }
201
202 Some(value)
203 }
204 }
205 TLVElementTLVIter::Seq(mut iter) => {
206 if let Some(value) = iter.next() {
207 *self = TLVElementTLVIter::Seq(iter);
208 Some(value)
209 } else {
210 Some(Ok(TLV::end_container()))
211 }
212 }
213 TLVElementTLVIter::Finished => None,
214 }
215 }
216}
217
218impl<'a> FromTLV<'a> for TLVValue<'a> {
219 fn from_tlv(element: &TLVElement<'a>) -> Result<Self, TlvError> {
220 element.value()
221 }
222}
223
224impl ToTLV for TLVValue<'_> {
225 fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, mut tw: W) -> Result<(), TlvError> {
226 tw.tlv(tag, self)
227 }
228
229 fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
230 TLV::new(tag, self.clone()).into_tlv_iter()
231 }
232}
233
234#[cfg(test)]
235#[cfg_attr(coverage_nightly, coverage(off))]
236mod tests {
237 use core::fmt::Debug;
238 use core::mem::MaybeUninit;
239
240 use rs_matter_macros::{FromTLV, ToTLV};
241
242 use crate::utils::init::InitMaybeUninit;
243 use crate::utils::storage::WriteBuf;
244 use crate::{Octets, TLVElement, TLV};
245
246 use super::{FromTLV, OctetStr, TLVTag, ToTLV};
247
248 fn test_from_tlv<'a, T: FromTLV<'a> + PartialEq + Debug>(data: &'a [u8], expected: T) {
249 let root = TLVElement::new(data);
250 let test = T::from_tlv(&root).unwrap();
251 ::core::assert_eq!(test, expected);
252
253 let test_init = T::init_from_tlv(root);
254
255 let mut test = MaybeUninit::<T>::uninit();
256
257 let test = test.try_init_with(test_init).unwrap();
258
259 ::core::assert_eq!(*test, expected);
260 }
261
262 fn test_to_tlv<T: ToTLV>(t: T, expected: &[u8]) {
263 let mut buf = [0; 20];
264 let mut tw = WriteBuf::new(&mut buf);
265
266 t.to_tlv(&TLVTag::Anonymous, &mut tw).unwrap();
267
268 assert_eq!(tw.as_slice(), expected);
269
270 tw.reset();
271
272 let mut iter = t
273 .tlv_iter(TLVTag::Anonymous)
274 .flat_map(TLV::result_into_bytes_iter);
275 loop {
276 match iter.next() {
277 Some(Ok(byte)) => tw.append(&[byte]).unwrap(),
278 None => break,
279 _ => panic!("Error in iterator"),
280 }
281 }
282
283 ::core::assert_eq!(tw.as_slice(), expected);
284 }
285
286 #[derive(ToTLV, Debug)]
287 struct TestDerive {
288 a: u16,
289 b: u32,
290 }
291
292 #[test]
293 fn test_derive_totlv() {
294 test_to_tlv(
295 TestDerive {
296 a: 0x1010,
297 b: 0x20202020,
298 },
299 &[21, 37, 0, 0x10, 0x10, 38, 1, 0x20, 0x20, 0x20, 0x20, 24],
300 );
301 }
302
303 #[derive(FromTLV, Debug, PartialEq)]
304 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
305 struct TestDeriveSimple {
306 a: u16,
307 b: u32,
308 }
309
310 #[test]
311 fn test_derive_fromtlv() {
312 test_from_tlv(
313 &[21, 37, 0, 10, 0, 38, 1, 20, 0, 0, 0, 24],
314 TestDeriveSimple { a: 10, b: 20 },
315 );
316 }
317
318 #[derive(FromTLV, Debug, PartialEq)]
319 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
320 #[tlvargs(lifetime = "'a")]
321 struct TestDeriveStr<'a> {
322 a: u16,
323 b: OctetStr<'a>,
324 }
325
326 #[test]
327 fn test_derive_fromtlv_str() {
328 test_from_tlv(
329 &[21, 37, 0, 10, 0, 0x30, 0x01, 0x03, 10, 11, 12, 0],
330 TestDeriveStr {
331 a: 10,
332 b: Octets(&[10, 11, 12]),
333 },
334 );
335 }
336
337 #[derive(FromTLV, Debug, PartialEq)]
338 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
339 struct TestDeriveOption {
340 a: u16,
341 b: Option<u16>,
342 c: Option<u16>,
343 }
344
345 #[test]
346 fn test_derive_fromtlv_option() {
347 test_from_tlv(
348 &[21, 37, 0, 10, 0, 37, 2, 11, 0],
349 TestDeriveOption {
350 a: 10,
351 b: None,
352 c: Some(11),
353 },
354 );
355 }
356
357 #[derive(FromTLV, ToTLV, Debug, PartialEq)]
358 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
359 struct TestDeriveFabScoped {
360 a: u16,
361 #[tagval(0xFE)]
362 fab_idx: u16,
363 }
364
365 #[test]
366 fn test_derive_fromtlv_fab_scoped() {
367 test_from_tlv(
368 &[21, 37, 0, 10, 0, 37, 0xFE, 11, 0],
369 TestDeriveFabScoped { a: 10, fab_idx: 11 },
370 );
371 }
372
373 #[test]
374 fn test_derive_totlv_fab_scoped() {
375 test_to_tlv(
376 TestDeriveFabScoped { a: 20, fab_idx: 3 },
377 &[21, 36, 0, 20, 36, 0xFE, 3, 24],
378 );
379 }
380
381 #[derive(ToTLV, FromTLV, PartialEq, Debug)]
382 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
383 enum TestDeriveEnum {
384 ValueA(u32),
385 ValueB(u32),
386 }
387
388 #[test]
389 fn test_derive_from_to_tlv_enum() {
390 test_from_tlv(&[21, 36, 0, 100, 24, 0], TestDeriveEnum::ValueA(100));
392
393 test_to_tlv(TestDeriveEnum::ValueB(10), &[21, 36, 1, 10, 24]);
395 }
396}