rs-matter 0.2.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
Documentation
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/*
 *
 *    Copyright (c) 2024-2026 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

use num_traits::ToBytes;

use crate::error::{Error, ErrorCode};
use crate::utils::storage::WriteBuf;

use super::{TLVControl, TLVTag, TLVTagType, TLVValue, TLVValueType};

/// A trait representing a storage where data can be serialized as a TLV stream.
/// by synchronously emitting bytes to the storage.
///
/// The one method that needs to be implemented by user code is `write`.
///
/// The trait operates in an append-only manner without requiring access to the serialized
/// TLV data, so it can be implemented with an in-memory storage, or a file storage, or anything
/// that can output a byte to somewhere (like the `Write` Rust traits).
///
/// With that said, the trait has two additional methods that (optionally) allow for "rewinding"
/// the storage. Implementing these is optional, and they currently exist only for backwards
/// compatibility with code implemented prior to the introduction of this trait.
///
/// For iterator-style TLV serialization look at the `ToTLVIter` trait.
pub trait TLVWrite {
    type Position: PartialEq + Copy;

    /// Write a TLV tag and value to the TLV stream.
    fn tlv(&mut self, tag: &TLVTag, value: &TLVValue) -> Result<(), Error> {
        self.raw_value(tag, value.value_type(), &[])?;

        match value {
            TLVValue::Str8l(a) => self.write_raw_data((a.len() as u8).to_le_bytes()),
            TLVValue::Str16l(a) => self.write_raw_data((a.len() as u16).to_le_bytes()),
            TLVValue::Str32l(a) => self.write_raw_data((a.len() as u32).to_le_bytes()),
            TLVValue::Str64l(a) => self.write_raw_data((a.len() as u64).to_le_bytes()),
            TLVValue::Utf8l(a) => self.write_raw_data((a.len() as u8).to_le_bytes()),
            TLVValue::Utf16l(a) => self.write_raw_data((a.len() as u16).to_le_bytes()),
            TLVValue::Utf32l(a) => self.write_raw_data((a.len() as u32).to_le_bytes()),
            TLVValue::Utf64l(a) => self.write_raw_data((a.len() as u64).to_le_bytes()),
            _ => Ok(()),
        }?;

        match value {
            TLVValue::S8(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::S16(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::S32(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::S64(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::U8(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::U16(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::U32(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::U64(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::False => Ok(()),
            TLVValue::True => Ok(()),
            TLVValue::F32(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::F64(a) => self.write_raw_data(a.to_le_bytes()),
            TLVValue::Utf8l(a)
            | TLVValue::Utf16l(a)
            | TLVValue::Utf32l(a)
            | TLVValue::Utf64l(a) => self.write_raw_data(a.as_bytes().iter().copied()),
            TLVValue::Str8l(a)
            | TLVValue::Str16l(a)
            | TLVValue::Str32l(a)
            | TLVValue::Str64l(a) => self.write_raw_data(a.iter().copied()),
            TLVValue::Null
            | TLVValue::Struct
            | TLVValue::Array
            | TLVValue::List
            | TLVValue::EndCnt => Ok(()),
        }
    }

    /// Write a tag and a TLV S8 value to the TLV stream.
    fn i8(&mut self, tag: &TLVTag, data: i8) -> Result<(), Error> {
        self.raw_value(tag, TLVValueType::S8, &data.to_le_bytes())
    }

    /// Write a tag and a TLV U8 value to the TLV stream.
    fn u8(&mut self, tag: &TLVTag, data: u8) -> Result<(), Error> {
        self.raw_value(tag, TLVValueType::U8, &data.to_le_bytes())
    }

    /// Write a tag and a TLV S16 or (if the data is small enough) S8 value to the TLV stream.
    fn i16(&mut self, tag: &TLVTag, data: i16) -> Result<(), Error> {
        if data >= i8::MIN as i16 && data <= i8::MAX as i16 {
            self.i8(tag, data as i8)
        } else {
            self.raw_value(tag, TLVValueType::S16, &data.to_le_bytes())
        }
    }

    /// Write a tag and a TLV U16 or (if the data is small enough) U8 value to the TLV stream.
    fn u16(&mut self, tag: &TLVTag, data: u16) -> Result<(), Error> {
        if data <= u8::MAX as u16 {
            self.u8(tag, data as u8)
        } else {
            self.raw_value(tag, TLVValueType::U16, &data.to_le_bytes())
        }
    }

    /// Write a tag and a TLV S32 or (if the data is small enough) S16 or S8 value to the TLV stream.
    fn i32(&mut self, tag: &TLVTag, data: i32) -> Result<(), Error> {
        if data >= i16::MIN as i32 && data <= i16::MAX as i32 {
            self.i16(tag, data as i16)
        } else {
            self.raw_value(tag, TLVValueType::S32, &data.to_le_bytes())
        }
    }

    /// Write a tag and a TLV U32 or (if the data is small enough) U16 or U8 value to the TLV stream.
    fn u32(&mut self, tag: &TLVTag, data: u32) -> Result<(), Error> {
        if data <= u16::MAX as u32 {
            self.u16(tag, data as u16)
        } else {
            self.raw_value(tag, TLVValueType::U32, &data.to_le_bytes())
        }
    }

    /// Write a tag and a TLV S64 or (if the data is small enough) S32, S16, or S8 value to the TLV stream.
    fn i64(&mut self, tag: &TLVTag, data: i64) -> Result<(), Error> {
        if data >= i32::MIN as i64 && data <= i32::MAX as i64 {
            self.i32(tag, data as i32)
        } else {
            self.raw_value(tag, TLVValueType::S64, &data.to_le_bytes())
        }
    }

    /// Write a tag and a TLV U64 or (if the data is small enough) U32, U16, or U8 value to the TLV stream.
    fn u64(&mut self, tag: &TLVTag, data: u64) -> Result<(), Error> {
        if data <= u32::MAX as u64 {
            self.u32(tag, data as u32)
        } else {
            self.raw_value(tag, TLVValueType::U64, &data.to_le_bytes())
        }
    }

    /// Write a tag and a TLV F32 to the TLV stream.
    fn f32(&mut self, tag: &TLVTag, data: f32) -> Result<(), Error> {
        self.raw_value(tag, TLVValueType::F32, &data.to_le_bytes())
    }

    /// Write a tag and a TLV F64 to the TLV stream.
    fn f64(&mut self, tag: &TLVTag, data: f64) -> Result<(), Error> {
        self.raw_value(tag, TLVValueType::F64, &data.to_le_bytes())
    }

    /// Write a tag and a TLV Octet String to the TLV stream, where the Octet String is a slice of u8 bytes.
    ///
    /// The exact octet string type (Str8l, Str16l, Str32l, or Str64l) is chosen based on the length of the data,
    /// whereas the smallest type filling the provided data length is chosen.
    fn str(&mut self, tag: &TLVTag, data: &[u8]) -> Result<(), Error> {
        self.stri(tag, data.len(), data.iter().copied())
    }

    /// Write a tag and a TLV Octet String to the TLV stream, where the Octet String is a slice of u8 bytes.
    ///
    /// The writing is done via a user-supplied callback `cb`, that is expected to fill the provided buffer with the data
    /// and to return the length of the written data.
    ///
    /// This method is useful when the data to be written needs to be computed first, and the computation needs a buffer where
    /// to operate.
    ///
    /// Note that this method always uses a Str16l value type to write the data, which restricts the data length to no more than
    /// 65535 bytes.
    ///
    /// Note also that this method might not be supported by all `TLVWrite` implementations.
    fn str_cb(
        &mut self,
        _tag: &TLVTag,
        _cb: impl FnOnce(&mut [u8]) -> Result<usize, Error>,
    ) -> Result<(), Error> {
        unimplemented!("str_cb not implemented for this TLVWrite instance");
    }

    /// Write a tag and a TLV Octet String to the TLV stream, where the Octet String is
    /// anything that can be turned into an iterator of u8 bytes.
    ///
    /// The exact octet string type (Str8l, Str16l, Str32l, or Str64l) is chosen based on the length of the data,
    /// whereas the smallest type filling the provided data length is chosen.
    ///
    /// NOTE: The length of the Octet String must be provided by the user and it must match the
    /// number of bytes returned by the provided iterator, or else the generated TLV stream will be invalid.
    fn stri<I>(&mut self, tag: &TLVTag, len: usize, data: I) -> Result<(), Error>
    where
        I: IntoIterator<Item = u8>,
    {
        if len <= u8::MAX as usize {
            self.raw_value(tag, TLVValueType::Str8l, &(len as u8).to_le_bytes())?;
        } else if len <= u16::MAX as usize {
            self.raw_value(tag, TLVValueType::Str16l, &(len as u16).to_le_bytes())?;
        } else if len <= u32::MAX as usize {
            self.raw_value(tag, TLVValueType::Str32l, &(len as u32).to_le_bytes())?;
        } else {
            self.raw_value(tag, TLVValueType::Str64l, &(len as u64).to_le_bytes())?;
        }

        self.write_raw_data(data)
    }

    /// Write a tag and a TLV UTF-8 String to the TLV stream, where the UTF-8 String is a str.
    ///
    /// The exact UTF-8 string type (Utf8l, Utf16l, Utf32l, or Utf64l) is chosen based on the length of the data,
    /// whereas the smallest type filling the provided data length is chosen.
    fn utf8(&mut self, tag: &TLVTag, data: &str) -> Result<(), Error> {
        self.utf8i(tag, data.len(), data.as_bytes().iter().copied())
    }

    /// Write a tag and a TLV UTF-8 String to the TLV stream, where the UTF-8 String is
    /// anything that can be turned into an iterator of u8 bytes.
    ///
    /// The exact UTF-8 string type (Utf8l, Utf16l, Utf32l, or Utf64l) is chosen based on the length of the data,
    /// whereas the smallest type filling the provided data length is chosen.
    ///
    /// NOTE 1: The length of the UTF-8 String must be provided by the user and it must match the
    /// number of bytes returned by the provided iterator, or else the generated TLV stream will be invalid.
    ///
    /// NOTE 2: The provided iterator must return valid UTF-8 bytes, or else the generated TLV stream will be invalid.
    fn utf8i<I>(&mut self, tag: &TLVTag, len: usize, data: I) -> Result<(), Error>
    where
        I: IntoIterator<Item = u8>,
    {
        if len <= u8::MAX as usize {
            self.raw_value(tag, TLVValueType::Utf8l, &(len as u8).to_le_bytes())?;
        } else if len <= u16::MAX as usize {
            self.raw_value(tag, TLVValueType::Utf16l, &(len as u16).to_le_bytes())?;
        } else if len <= u32::MAX as usize {
            self.raw_value(tag, TLVValueType::Utf32l, &(len as u32).to_le_bytes())?;
        } else {
            self.raw_value(tag, TLVValueType::Utf64l, &(len as u64).to_le_bytes())?;
        }

        self.write_raw_data(data)
    }

    /// Write a tag and a TLV UTF-8 String to the TLV stream, where the UTF-8 String is a str.
    ///
    /// The writing is done via a user-supplied callback `cb`, that is expected to fill the provided buffer with the data
    /// and to return the length of the written data.
    ///
    /// This method is useful when the data to be written needs to be computed first, and the computation needs a buffer where
    /// to operate.
    ///
    /// Note that this method always uses a Utf16l value type to write the data, which restricts the data length to no more than
    /// 65535 bytes.
    ///
    /// Note also that this method might not be supported by all `TLVWrite` implementations.
    fn utf8_cb(
        &mut self,
        _tag: &TLVTag,
        _cb: impl FnOnce(&mut [u8]) -> Result<usize, Error>,
    ) -> Result<(), Error> {
        unimplemented!("utf8_cb not implemented for this TLVWrite instance");
    }

    /// Write a tag and a value indicating the start of a Struct TLV container.
    ///
    /// NOTE: The user must call `end_container` after writing all the Struct fields
    /// to close the Struct container or else the generated TLV stream will be invalid.
    fn start_struct(&mut self, tag: &TLVTag) -> Result<(), Error> {
        self.raw_value(tag, TLVValueType::Struct, &[])
    }

    /// Write a tag and a value indicating the start of an Array TLV container.
    ///
    /// NOTE: The user must call `end_container` after writing all the Array elements
    /// to close the Array container or else the generated TLV stream will be invalid.
    fn start_array(&mut self, tag: &TLVTag) -> Result<(), Error> {
        self.raw_value(tag, TLVValueType::Array, &[])
    }

    /// Write a tag and a value indicating the start of a List TLV container.
    ///
    /// NOTE: The user must call `end_container` after writing all the List elements
    /// to close the List container or else the generated TLV stream will be invalid.
    fn start_list(&mut self, tag: &TLVTag) -> Result<(), Error> {
        self.raw_value(tag, TLVValueType::List, &[])
    }

    /// Write a tag and a value indicating the start of a Struct TLV container.
    ///
    /// NOTE: The user must call `end_container` after writing all the Struct fields
    /// to close the Struct container or else the generated TLV stream will be invalid.
    fn start_container(&mut self, tag: &TLVTag, container_type: TLVValueType) -> Result<(), Error> {
        if !container_type.is_container() {
            Err(ErrorCode::TLVTypeMismatch)?;
        }

        self.raw_value(tag, container_type, &[])
    }

    /// Write a value indicating the end of a Struct, Array, or List TLV container.
    ///
    /// NOTE: This method must be called only when the corresponding container has been opened
    /// using `start_struct`, `start_array`, or `start_list`, or else the generated TLV stream will be invalid.
    fn end_container(&mut self) -> Result<(), Error> {
        self.write(TLVControl::new(TLVTagType::Anonymous, TLVValueType::EndCnt).as_raw())
    }

    /// Write a tag and a TLV Null value to the TLV stream.
    fn null(&mut self, tag: &TLVTag) -> Result<(), Error> {
        self.raw_value(tag, TLVValueType::Null, &[])
    }

    /// Write a tag and a TLV True or False value to the TLV stream.
    fn bool(&mut self, tag: &TLVTag, val: bool) -> Result<(), Error> {
        self.raw_value(
            tag,
            if val {
                TLVValueType::True
            } else {
                TLVValueType::False
            },
            &[],
        )
    }

    /// Write a tag and a raw, already-encoded TLV value represented as a byte slice.
    fn raw_value(
        &mut self,
        tag: &TLVTag,
        value_type: TLVValueType,
        value_payload: &[u8],
    ) -> Result<(), Error> {
        self.write(TLVControl::new(tag.tag_type(), value_type).as_raw())?;

        match tag {
            TLVTag::Anonymous => Ok(()),
            TLVTag::Context(v) => self.write_raw_data(v.to_le_bytes()),
            TLVTag::CommonPrf16(v) | TLVTag::ImplPrf16(v) => self.write_raw_data(v.to_le_bytes()),
            TLVTag::CommonPrf32(v) | TLVTag::ImplPrf32(v) => self.write_raw_data(v.to_le_bytes()),
            TLVTag::FullQual48 {
                vendor_id,
                profile,
                tag,
            } => {
                self.write_raw_data(vendor_id.to_le_bytes())?;
                self.write_raw_data(profile.to_le_bytes())?;
                self.write_raw_data(tag.to_le_bytes())
            }
            TLVTag::FullQual64 {
                vendor_id,
                profile,
                tag,
            } => {
                self.write_raw_data(vendor_id.to_le_bytes())?;
                self.write_raw_data(profile.to_le_bytes())?;
                self.write_raw_data(tag.to_le_bytes())
            }
        }?;

        self.write_raw_data(value_payload.iter().copied())
    }

    /// Append multiple raw bytes to the TLV stream.
    fn write_raw_data<I>(&mut self, bytes: I) -> Result<(), Error>
    where
        I: IntoIterator<Item = u8>,
    {
        for byte in bytes {
            self.write(byte)?;
        }

        Ok(())
    }

    /// Append a single byte to the TLV stream.
    fn write(&mut self, byte: u8) -> Result<(), Error>;

    /// Get the current position in the TLV stream.
    ///
    /// NOTE: This method might not be supported by all implementations and therefore it might panic.
    fn get_tail(&self) -> Self::Position {
        unimplemented!("get_tail not implemented for this TLVWrite instance");
    }

    /// Rewind the TLV stream to a previous position.
    ///
    /// NOTE: This method might not be supported by all implementations and therefore it might panic.
    fn rewind_to(&mut self, _pos: Self::Position) {
        unimplemented!("rewind_to not implemented for this TLVWrite instance");
    }

    /// Get a mutable slice of the available space in the TLV stream.
    ///
    /// NOTE: This method assumes that the TLV write implementation is writing to a buffer,
    /// which might not be the case for all implementations. Therefore, this method might panic
    /// if the implementation does not support it.
    fn available_space(&mut self) -> &mut [u8] {
        unimplemented!("available_space not implemented for this TLVWrite instance");
    }
}

impl<T> TLVWrite for &mut T
where
    T: TLVWrite,
{
    type Position = T::Position;

    fn write(&mut self, byte: u8) -> Result<(), Error> {
        (**self).write(byte)
    }

    fn get_tail(&self) -> Self::Position {
        (**self).get_tail()
    }

    fn rewind_to(&mut self, pos: Self::Position) {
        (**self).rewind_to(pos)
    }

    fn available_space(&mut self) -> &mut [u8] {
        (**self).available_space()
    }

    fn str_cb(
        &mut self,
        tag: &TLVTag,
        cb: impl FnOnce(&mut [u8]) -> Result<usize, Error>,
    ) -> Result<(), Error> {
        (**self).str_cb(tag, cb)
    }

    fn utf8_cb(
        &mut self,
        tag: &TLVTag,
        cb: impl FnOnce(&mut [u8]) -> Result<usize, Error>,
    ) -> Result<(), Error> {
        (**self).utf8_cb(tag, cb)
    }
}

impl TLVWrite for WriteBuf<'_> {
    type Position = usize;

    fn write(&mut self, byte: u8) -> Result<(), Error> {
        WriteBuf::append(self, &[byte])
    }

    fn get_tail(&self) -> Self::Position {
        WriteBuf::get_tail(self)
    }

    fn rewind_to(&mut self, pos: Self::Position) {
        WriteBuf::rewind_tail_to(self, pos)
    }

    fn available_space(&mut self) -> &mut [u8] {
        WriteBuf::empty_as_mut_slice(self)
    }

    fn str_cb(
        &mut self,
        tag: &TLVTag,
        cb: impl FnOnce(&mut [u8]) -> Result<usize, Error>,
    ) -> Result<(), Error> {
        WriteBuf::str_cb(self, tag, cb)
    }

    fn utf8_cb(
        &mut self,
        tag: &TLVTag,
        cb: impl FnOnce(&mut [u8]) -> Result<usize, Error>,
    ) -> Result<(), Error> {
        WriteBuf::utf8_cb(self, tag, cb)
    }
}

impl WriteBuf<'_> {
    /// Write a tag and a TLV Octet String to the TLV stream, where the Octet String is a slice of u8 bytes.
    ///
    /// The writing is done via a user-supplied callback `cb`, that is expected to fill the provided buffer with the data
    /// and to return the length of the written data.
    ///
    /// This method is useful when the data to be written needs to be computed first, and the computation needs a buffer where
    /// to operate.
    ///
    /// Note that this method reserves a Str16l header before invoking the callback, restricting
    /// the data length to no more than 65535 bytes. If the actual length fits in a single byte,
    /// the header is downgraded in-place to a canonical Str8l encoding (shortest-form length),
    /// which some strict Matter controllers (e.g. SmartThings) require.
    pub fn str_cb(
        &mut self,
        tag: &TLVTag,
        cb: impl FnOnce(&mut [u8]) -> Result<usize, Error>,
    ) -> Result<(), Error> {
        let control_offset = self.get_tail();
        self.raw_value(tag, TLVValueType::Str16l, &0_u16.to_le_bytes())?;

        let value_offset = self.get_tail();

        let len = self.append_with_buf(cb)?;

        Self::finalize_len_header(
            self,
            control_offset,
            value_offset,
            len,
            tag.tag_type(),
            TLVValueType::Str8l,
        );

        Ok(())
    }

    /// Write a tag and a TLV UTF-8 String to the TLV stream, where the UTF-8 String is a str.
    ///
    /// The writing is done via a user-supplied callback `cb`, that is expected to fill the provided buffer with the data
    /// and to return the length of the written data.
    ///
    /// This method is useful when the data to be written needs to be computed first, and the computation needs a buffer where
    /// to operate.
    ///
    /// Note that this method reserves a Utf16l header before invoking the callback, restricting
    /// the data length to no more than 65535 bytes. If the actual length fits in a single byte,
    /// the header is downgraded in-place to a canonical Utf8l encoding (shortest-form length).
    pub fn utf8_cb(
        &mut self,
        tag: &TLVTag,
        cb: impl FnOnce(&mut [u8]) -> Result<usize, Error>,
    ) -> Result<(), Error> {
        let control_offset = self.get_tail();
        self.raw_value(tag, TLVValueType::Utf16l, &0_u16.to_le_bytes())?;

        let value_offset = self.get_tail();

        let len = self.append_with_buf(cb)?;

        Self::finalize_len_header(
            self,
            control_offset,
            value_offset,
            len,
            tag.tag_type(),
            TLVValueType::Utf8l,
        );

        Ok(())
    }

    /// Rewrite the length header reserved by `str_cb` / `utf8_cb` so that the shortest
    /// possible length encoding is used (canonical Matter TLV).
    ///
    /// Before the call, the buffer layout is:
    ///   [... prefix ...][control=<16l>][tag bytes][0x00][0x00][data ...]
    ///                   ^control_offset           ^value_offset-2      ^value_offset+len
    ///
    /// If `len <= u8::MAX`, the header is rewritten to:
    ///   [... prefix ...][control=<8l>][tag bytes][len][data ...]
    /// and `end` is decremented by 1.
    ///
    /// Otherwise, the 16-bit length is simply patched in place.
    fn finalize_len_header(
        this: &mut WriteBuf<'_>,
        control_offset: usize,
        value_offset: usize,
        len: usize,
        tag_type: TLVTagType,
        short_value_type: TLVValueType,
    ) {
        if len <= u8::MAX as usize {
            // Canonical: use 1-byte length encoding.
            this.buf[control_offset] = TLVControl::new(tag_type, short_value_type).as_raw();
            this.buf[value_offset - 2] = len as u8;
            this.buf
                .copy_within(value_offset..value_offset + len, value_offset - 1);
            this.rewind_tail_to(this.get_tail() - 1);
        } else if len <= u16::MAX as usize {
            // Keep 2-byte length encoding and patch the placeholder.
            this.buf[value_offset - 2..value_offset].copy_from_slice(&(len as u16).to_le_bytes());
        } else {
            // This should not happen, as the callback is expected to respect the reserved header size.
            panic!("Callback wrote more data than the reserved header can encode");
        }
    }
}

#[cfg(test)]
mod tests {
    use core::f32;

    use super::{TLVTag, TLVWrite};
    use crate::{tlv::TLVValue, utils::storage::WriteBuf};

    #[test]
    fn test_write_success() {
        let mut buf = [0; 20];
        let mut tw = WriteBuf::new(&mut buf);

        tw.start_struct(&TLVTag::Anonymous).unwrap();
        tw.u8(&TLVTag::Anonymous, 12).unwrap();
        tw.u8(&TLVTag::Context(1), 13).unwrap();
        tw.u16(&TLVTag::Anonymous, 0x1212).unwrap();
        tw.u16(&TLVTag::Context(2), 0x1313).unwrap();
        tw.start_array(&TLVTag::Context(3)).unwrap();
        tw.bool(&TLVTag::Anonymous, true).unwrap();
        tw.end_container().unwrap();
        tw.end_container().unwrap();
        assert_eq!(
            buf,
            [21, 4, 12, 36, 1, 13, 5, 0x12, 0x012, 37, 2, 0x13, 0x13, 54, 3, 9, 24, 24, 0, 0]
        );
    }

    #[test]
    fn test_write_overflow() {
        let mut buf = [0; 6];
        let mut tw = WriteBuf::new(&mut buf);

        tw.u8(&TLVTag::Anonymous, 12).unwrap();
        tw.u8(&TLVTag::Context(1), 13).unwrap();
        if tw.u16(&TLVTag::Anonymous, 12).is_ok() {
            panic!("This should have returned error")
        }
        if tw.u16(&TLVTag::Context(2), 13).is_ok() {
            panic!("This should have returned error")
        }
        assert_eq!(buf, [4, 12, 36, 1, 13, 4]);
    }

    #[test]
    fn test_put_str8() {
        let mut buf = [0; 20];
        let mut tw = WriteBuf::new(&mut buf);

        tw.u8(&TLVTag::Context(1), 13).unwrap();
        tw.str(&TLVTag::Anonymous, &[10, 11, 12, 13, 14]).unwrap();
        tw.u16(&TLVTag::Context(2), 0x1313).unwrap();
        tw.str(&TLVTag::Context(3), &[20, 21, 22]).unwrap();
        assert_eq!(
            buf,
            [36, 1, 13, 16, 5, 10, 11, 12, 13, 14, 37, 2, 0x13, 0x13, 48, 3, 3, 20, 21, 22]
        );
    }

    #[test]
    fn test_matter_spec_examples() {
        let mut buf = [0; 200];
        let mut tw = WriteBuf::new(&mut buf);

        // Boolean false

        tw.bool(&TLVTag::Anonymous, false).unwrap();
        assert_eq!(&[0x08], tw.as_slice());

        // Boolean true

        tw.reset();
        tw.bool(&TLVTag::Anonymous, true).unwrap();
        assert_eq!(&[0x09], tw.as_slice());

        // Signed Integer, 1-octet, value 42

        tw.reset();
        tw.i8(&TLVTag::Anonymous, 42).unwrap();
        assert_eq!(&[0x00, 0x2a], tw.as_slice());

        // Signed Integer, 1-octet, value -17

        tw.reset();
        tw.i32(&TLVTag::Anonymous, -17).unwrap();
        assert_eq!(&[0x00, 0xef], tw.as_slice());

        // Unsigned Integer, 1-octet, value 42U

        tw.reset();
        tw.u8(&TLVTag::Anonymous, 42).unwrap();
        assert_eq!(&[0x04, 0x2a], tw.as_slice());

        // Signed Integer, 2-octet, value 422

        tw.reset();
        tw.i16(&TLVTag::Anonymous, 422).unwrap();
        assert_eq!(&[0x01, 0xa6, 0x01], tw.as_slice());

        // Signed Integer, 4-octet, value -170000

        tw.reset();
        tw.i32(&TLVTag::Anonymous, -170000).unwrap();
        assert_eq!(&[0x02, 0xf0, 0x67, 0xfd, 0xff], tw.as_slice());

        // Signed Integer, 8-octet, value 40000000000

        tw.reset();
        tw.i64(&TLVTag::Anonymous, 40000000000).unwrap();
        assert_eq!(
            &[0x03, 0x00, 0x90, 0x2f, 0x50, 0x09, 0x00, 0x00, 0x00],
            tw.as_slice()
        );

        // UTF-8 String, 1-octet length, "Hello!"

        tw.reset();
        tw.utf8(&TLVTag::Anonymous, "Hello!").unwrap();
        assert_eq!(
            &[0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21],
            tw.as_slice()
        );

        // UTF-8 String, 1-octet length, "Tschüs"

        tw.reset();
        tw.utf8i(
            &TLVTag::Anonymous,
            "Tschüs".len(),
            "Tschüs".as_bytes().iter().copied(),
        )
        .unwrap();
        assert_eq!(
            &[0x0c, 0x07, 0x54, 0x73, 0x63, 0x68, 0xc3, 0xbc, 0x73],
            tw.as_slice()
        );

        // Octet String, 1-octet length, octets 00 01 02 03 04

        tw.reset();
        tw.str(&TLVTag::Anonymous, &[0x00, 0x01, 0x02, 0x03, 0x04])
            .unwrap();
        assert_eq!(&[0x10, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04], tw.as_slice());

        // Null

        tw.reset();
        tw.tlv(&TLVTag::Anonymous, &TLVValue::Null).unwrap();
        assert_eq!(&[0x14], tw.as_slice());

        // Single precision floating point 0.0

        tw.reset();
        tw.tlv(&TLVTag::Anonymous, &TLVValue::F32(0.0)).unwrap();
        assert_eq!(&[0x0a, 0x00, 0x00, 0x00, 0x00], tw.as_slice());

        // Single precision floating point (1.0 / 3.0)

        tw.reset();
        tw.f32(&TLVTag::Anonymous, 1.0 / 3.0).unwrap();
        assert_eq!(&[0x0a, 0xab, 0xaa, 0xaa, 0x3e], tw.as_slice());

        // Single precision floating point 17.9

        tw.reset();
        tw.f32(&TLVTag::Anonymous, 17.9).unwrap();
        assert_eq!(&[0x0a, 0x33, 0x33, 0x8f, 0x41], tw.as_slice());

        // Single precision floating point infinity

        tw.reset();
        tw.f32(&TLVTag::Anonymous, f32::INFINITY).unwrap();
        assert_eq!(&[0x0a, 0x00, 0x00, 0x80, 0x7f], tw.as_slice());

        // Single precision floating point negative infinity

        tw.reset();
        tw.f32(&TLVTag::Anonymous, f32::NEG_INFINITY).unwrap();
        assert_eq!(&[0x0a, 0x00, 0x00, 0x80, 0xff], tw.as_slice());

        // Double precision floating point 0.0

        tw.reset();
        tw.f64(&TLVTag::Anonymous, 0.0).unwrap();
        assert_eq!(
            &[0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
            tw.as_slice()
        );

        // Double precision floating point (1.0 / 3.0)

        tw.reset();
        tw.f64(&TLVTag::Anonymous, 1.0 / 3.0).unwrap();
        assert_eq!(
            &[0x0b, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xd5, 0x3f],
            tw.as_slice()
        );

        // Double precision floating point 17.9

        tw.reset();
        tw.f64(&TLVTag::Anonymous, 17.9).unwrap();
        assert_eq!(
            &[0x0b, 0x66, 0x66, 0x66, 0x66, 0x66, 0xe6, 0x31, 0x40],
            tw.as_slice()
        );

        // Double precision floating point infinity (∞)

        tw.reset();
        tw.f64(&TLVTag::Anonymous, f64::INFINITY).unwrap();
        assert_eq!(
            &[0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x7f],
            tw.as_slice()
        );

        // Double precision floating point negative infinity

        tw.reset();
        tw.f64(&TLVTag::Anonymous, f64::NEG_INFINITY).unwrap();
        assert_eq!(
            &[0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff],
            tw.as_slice()
        );

        // Empty Structure, {}

        tw.reset();
        tw.start_struct(&TLVTag::Anonymous).unwrap();
        tw.end_container().unwrap();
        assert_eq!(&[0x15, 0x18], tw.as_slice());

        // Empty Array, []

        tw.reset();
        tw.start_array(&TLVTag::Anonymous).unwrap();
        tw.end_container().unwrap();
        assert_eq!(&[0x16, 0x18], tw.as_slice());

        // Empty List, []

        tw.reset();
        tw.start_list(&TLVTag::Anonymous).unwrap();
        tw.end_container().unwrap();
        assert_eq!(&[0x17, 0x18], tw.as_slice());

        // Structure, two context specific tags, Signed Integer, 1 octet values, {0 = 42, 1 = -17}

        tw.reset();
        tw.start_struct(&TLVTag::Anonymous).unwrap();
        tw.i8(&TLVTag::Context(0), 42).unwrap();
        tw.i32(&TLVTag::Context(1), -17).unwrap();
        tw.end_container().unwrap();
        assert_eq!(
            &[0x15, 0x20, 0x00, 0x2a, 0x20, 0x01, 0xef, 0x18],
            tw.as_slice()
        );

        // Array, Signed Integer, 1-octet values, [0, 1, 2, 3, 4]

        tw.reset();
        tw.start_array(&TLVTag::Anonymous).unwrap();
        for i in 0..5 {
            tw.i8(&TLVTag::Anonymous, i as i8).unwrap();
        }
        tw.end_container().unwrap();
        assert_eq!(
            &[0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x18],
            tw.as_slice()
        );

        // List, mix of anonymous and context tags, Signed Integer, 1 octet values, [[1, 0 = 42, 2, 3, 0 = -17]]

        tw.reset();
        tw.start_list(&TLVTag::Anonymous).unwrap();
        tw.i64(&TLVTag::Anonymous, 1).unwrap();
        tw.i16(&TLVTag::Context(0), 42).unwrap();
        tw.i8(&TLVTag::Anonymous, 2).unwrap();
        tw.i8(&TLVTag::Anonymous, 3).unwrap();
        tw.i32(&TLVTag::Context(0), -17).unwrap();
        tw.end_container().unwrap();
        assert_eq!(
            &[0x17, 0x00, 0x01, 0x20, 0x00, 0x2a, 0x00, 0x02, 0x00, 0x03, 0x20, 0x00, 0xef, 0x18],
            tw.as_slice()
        );

        // Array, mix of element types, [42, -170000, {}, 17.9, "Hello!"]

        tw.reset();
        tw.start_array(&TLVTag::Anonymous).unwrap();
        tw.i64(&TLVTag::Anonymous, 42).unwrap();
        tw.i64(&TLVTag::Anonymous, -170000).unwrap();
        tw.start_struct(&TLVTag::Anonymous).unwrap();
        tw.end_container().unwrap();
        tw.f32(&TLVTag::Anonymous, 17.9).unwrap();
        tw.utf8(&TLVTag::Anonymous, "Hello!").unwrap();
        tw.end_container().unwrap();
        assert_eq!(
            &[
                0x16, 0x00, 0x2a, 0x02, 0xf0, 0x67, 0xfd, 0xff, 0x15, 0x18, 0x0a, 0x33, 0x33, 0x8f,
                0x41, 0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0x18,
            ],
            tw.as_slice()
        );

        // Anonymous tag, Unsigned Integer, 1-octet value, 42U

        tw.reset();
        tw.u64(&TLVTag::Anonymous, 42).unwrap();
        assert_eq!(&[0x04, 0x2a], tw.as_slice());

        // Context tag 1, Unsigned Integer, 1-octet value, 1 = 42U

        tw.reset();
        tw.u64(&TLVTag::Context(1), 42).unwrap();
        assert_eq!(&[0x24, 0x01, 0x2a], tw.as_slice());

        // Common profile tag 1, Unsigned Integer, 1-octet value, Matter::1 = 42U

        tw.reset();
        tw.u64(&TLVTag::CommonPrf16(1), 42).unwrap();
        assert_eq!(&[0x44, 0x01, 0x00, 0x2a], tw.as_slice());

        // Common profile tag 100000, Unsigned Integer, 1-octet value, Matter::100000 = 42U

        tw.reset();
        tw.u64(&TLVTag::CommonPrf32(100000), 42).unwrap();
        assert_eq!(&[0x64, 0xa0, 0x86, 0x01, 0x00, 0x2a], tw.as_slice());

        // Fully qualified tag, Vendor ID 0xFFF1/65521, pro­file number 0xDEED/57069,
        // 2-octet tag 1, Unsigned Integer, 1-octet value 42, 65521::57069:1 = 42U

        tw.reset();
        tw.u64(
            &TLVTag::FullQual48 {
                vendor_id: 65521,
                profile: 57069,
                tag: 1,
            },
            42,
        )
        .unwrap();
        assert_eq!(
            &[0xc4, 0xf1, 0xff, 0xed, 0xde, 0x01, 0x00, 0x2a],
            tw.as_slice()
        );

        // Fully qualified tag, Vendor ID 0xFFF1/65521, pro­file number 0xDEED/57069,
        // 4-octet tag 0xAA55FEED/2857762541, Unsigned Integer, 1-octet value 42, 65521::57069:2857762541 = 42U

        tw.reset();
        tw.u64(
            &TLVTag::FullQual64 {
                vendor_id: 65521,
                profile: 57069,
                tag: 2857762541,
            },
            42,
        )
        .unwrap();
        assert_eq!(
            &[0xe4, 0xf1, 0xff, 0xed, 0xde, 0xed, 0xfe, 0x55, 0xaa, 0x2a],
            tw.as_slice()
        );

        // Structure with the fully qualified tag, Vendor ID 0xFFF1/65521, profile number 0xDEED/57069,
        // 2-octet tag 1. The structure contains a single ele­ment labeled using a fully qualified tag under
        // the same profile, with 2-octet tag 0xAA55/43605. 65521::57069:1 = {65521::57069:43605 = 42U}

        tw.reset();
        tw.start_struct(&TLVTag::FullQual48 {
            vendor_id: 65521,
            profile: 57069,
            tag: 1,
        })
        .unwrap();
        tw.u64(
            &TLVTag::FullQual48 {
                vendor_id: 65521,
                profile: 57069,
                tag: 43605,
            },
            42,
        )
        .unwrap();
        tw.end_container().unwrap();
        assert_eq!(
            &[
                0xd5, 0xf1, 0xff, 0xed, 0xde, 0x01, 0x00, 0xc4, 0xf1, 0xff, 0xed, 0xde, 0x55, 0xaa,
                0x2a, 0x18,
            ],
            tw.as_slice()
        );
    }
}