matter-codec 0.1.0

Matter protocol TLV (Tag-Length-Value) encoder and decoder.
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
//! Streaming TLV encoder. Appends to a caller-provided `Vec<u8>`.

use crate::error::{Error, Result};
use crate::reader::MAX_DEPTH;
use crate::tag::Tag;
use crate::value::Value;
use crate::{element_type as et, tag_control as tc};

/// A streaming TLV encoder that appends to a caller-provided `Vec<u8>`.
pub struct TlvWriter<'a> {
    out: &'a mut Vec<u8>,
}

impl<'a> TlvWriter<'a> {
    /// Construct a writer that appends to `out`. The writer borrows `out`
    /// mutably; release the borrow by dropping the writer.
    pub fn new(out: &'a mut Vec<u8>) -> Self {
        Self { out }
    }

    /// Write a control octet (tag form bits OR'd with element type bits)
    /// followed by any tag bytes the tag form requires.
    fn write_tag(&mut self, tag: Tag, element_type: u8) {
        match tag {
            Tag::Anonymous => {
                self.out.push(tc::ANONYMOUS | element_type);
            }
            Tag::Context(n) => {
                self.out.push(tc::CONTEXT | element_type);
                self.out.push(n);
            }
            Tag::CommonProfile(n) => {
                if let Ok(n16) = u16::try_from(n) {
                    self.out.push(tc::COMMON_PROFILE_2 | element_type);
                    self.out.extend_from_slice(&n16.to_le_bytes());
                } else {
                    self.out.push(tc::COMMON_PROFILE_4 | element_type);
                    self.out.extend_from_slice(&n.to_le_bytes());
                }
            }
            Tag::ImplicitProfile(n) => {
                if let Ok(n16) = u16::try_from(n) {
                    self.out.push(tc::IMPLICIT_PROFILE_2 | element_type);
                    self.out.extend_from_slice(&n16.to_le_bytes());
                } else {
                    self.out.push(tc::IMPLICIT_PROFILE_4 | element_type);
                    self.out.extend_from_slice(&n.to_le_bytes());
                }
            }
            Tag::FullyQualified {
                vendor,
                profile,
                tag,
            } => {
                if let Ok(tag16) = u16::try_from(tag) {
                    self.out.push(tc::FULLY_QUALIFIED_6 | element_type);
                    self.out.extend_from_slice(&vendor.to_le_bytes());
                    self.out.extend_from_slice(&profile.to_le_bytes());
                    self.out.extend_from_slice(&tag16.to_le_bytes());
                } else {
                    self.out.push(tc::FULLY_QUALIFIED_8 | element_type);
                    self.out.extend_from_slice(&vendor.to_le_bytes());
                    self.out.extend_from_slice(&profile.to_le_bytes());
                    self.out.extend_from_slice(&tag.to_le_bytes());
                }
            }
        }
    }

    /// Emit a boolean value with the given tag.
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn put_bool(&mut self, tag: Tag, v: bool) -> Result<()> {
        let et = if v { et::BOOL_TRUE } else { et::BOOL_FALSE };
        self.write_tag(tag, et);
        Ok(())
    }

    /// Emit a null value with the given tag.
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn put_null(&mut self, tag: Tag) -> Result<()> {
        self.write_tag(tag, et::NULL);
        Ok(())
    }

    /// Emit an unsigned integer with the given tag. The minimum-width
    /// encoding (1, 2, 4, or 8 bytes) is chosen automatically per
    /// Matter Core Spec §A.2.
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn put_uint(&mut self, tag: Tag, v: u64) -> Result<()> {
        if let Ok(n) = u8::try_from(v) {
            self.write_tag(tag, et::UINT8);
            self.out.push(n);
        } else if let Ok(n) = u16::try_from(v) {
            self.write_tag(tag, et::UINT16);
            self.out.extend_from_slice(&n.to_le_bytes());
        } else if let Ok(n) = u32::try_from(v) {
            self.write_tag(tag, et::UINT32);
            self.out.extend_from_slice(&n.to_le_bytes());
        } else {
            self.write_tag(tag, et::UINT64);
            self.out.extend_from_slice(&v.to_le_bytes());
        }
        Ok(())
    }

    /// Emit a signed integer with the given tag. The minimum-width
    /// encoding (1, 2, 4, or 8 bytes) is chosen automatically per
    /// Matter Core Spec §A.2.
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn put_int(&mut self, tag: Tag, v: i64) -> Result<()> {
        if let Ok(n) = i8::try_from(v) {
            self.write_tag(tag, et::INT8);
            self.out.push(n.to_le_bytes()[0]);
        } else if let Ok(n) = i16::try_from(v) {
            self.write_tag(tag, et::INT16);
            self.out.extend_from_slice(&n.to_le_bytes());
        } else if let Ok(n) = i32::try_from(v) {
            self.write_tag(tag, et::INT32);
            self.out.extend_from_slice(&n.to_le_bytes());
        } else {
            self.write_tag(tag, et::INT64);
            self.out.extend_from_slice(&v.to_le_bytes());
        }
        Ok(())
    }

    /// Emit a single-precision IEEE 754 float with the given tag.
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn put_float(&mut self, tag: Tag, v: f32) -> Result<()> {
        self.write_tag(tag, et::FLOAT32);
        self.out.extend_from_slice(&v.to_le_bytes());
        Ok(())
    }

    /// Emit a double-precision IEEE 754 float with the given tag.
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn put_double(&mut self, tag: Tag, v: f64) -> Result<()> {
        self.write_tag(tag, et::FLOAT64);
        self.out.extend_from_slice(&v.to_le_bytes());
        Ok(())
    }

    /// Emit a UTF-8 string with the given tag. The minimum-width length
    /// field (1, 2, 4, or 8 bytes) is chosen automatically.
    ///
    /// # Errors
    ///
    /// Returns [`Error::LengthOverflow`] if the string is longer than
    /// `u64::MAX` bytes (impossible in practice on any supported platform,
    /// but the return type is `Result` for portability).
    pub fn put_utf8(&mut self, tag: Tag, v: &str) -> Result<()> {
        self.put_string_payload(
            tag,
            v.as_bytes(),
            et::UTF8_LEN8,
            et::UTF8_LEN16,
            et::UTF8_LEN32,
            et::UTF8_LEN64,
        )
    }

    /// Emit an octet string with the given tag. The minimum-width length
    /// field (1, 2, 4, or 8 bytes) is chosen automatically.
    ///
    /// # Errors
    ///
    /// Returns [`Error::LengthOverflow`] if the slice is longer than
    /// `u64::MAX` bytes (impossible in practice on any supported platform,
    /// but the return type is `Result` for portability).
    pub fn put_bytes(&mut self, tag: Tag, v: &[u8]) -> Result<()> {
        self.put_string_payload(
            tag,
            v,
            et::BYTES_LEN8,
            et::BYTES_LEN16,
            et::BYTES_LEN32,
            et::BYTES_LEN64,
        )
    }

    /// Splice an already-encoded TLV element into the stream under a new
    /// `tag`, replacing the element's own tag control.
    ///
    /// `element` MUST be a single complete TLV element encoded with an
    /// **anonymous** tag (one control octet, no tag bytes), e.g. the output
    /// of another `TlvWriter` that began with `start_structure(Tag::Anonymous)`.
    /// Used to embed pre-encoded command-fields / payloads under a context
    /// tag without re-parsing them.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnexpectedEof`] if `element` is empty,
    /// [`Error::InvalidTagControl`] if `element` does not begin with an
    /// anonymous-tagged control octet, or [`Error::InvalidElementType`] if
    /// the element is a bare end-of-container marker (`0x18`), which is a
    /// delimiter, not a complete element.
    pub fn put_preencoded(&mut self, tag: Tag, element: &[u8]) -> Result<()> {
        let (&control, rest) = element.split_first().ok_or(Error::UnexpectedEof)?;
        if control & tc::TAG_CONTROL_MASK != tc::ANONYMOUS {
            return Err(Error::InvalidTagControl(control & tc::TAG_CONTROL_MASK));
        }
        let element_type = control & et::ELEMENT_TYPE_MASK;
        if element_type == et::END_OF_CONTAINER {
            return Err(Error::InvalidElementType(element_type));
        }
        self.write_tag(tag, element_type);
        self.out.extend_from_slice(rest);
        Ok(())
    }

    fn put_string_payload(
        &mut self,
        tag: Tag,
        bytes: &[u8],
        et_len8: u8,
        et_len16: u8,
        et_len32: u8,
        et_len64: u8,
    ) -> Result<()> {
        let len = bytes.len();
        if let Ok(len8) = u8::try_from(len) {
            self.write_tag(tag, et_len8);
            self.out.push(len8);
        } else if let Ok(len16) = u16::try_from(len) {
            self.write_tag(tag, et_len16);
            self.out.extend_from_slice(&len16.to_le_bytes());
        } else if let Ok(len32) = u32::try_from(len) {
            self.write_tag(tag, et_len32);
            self.out.extend_from_slice(&len32.to_le_bytes());
        } else {
            let len64 = u64::try_from(len).map_err(|_| Error::LengthOverflow)?;
            self.write_tag(tag, et_len64);
            self.out.extend_from_slice(&len64.to_le_bytes());
        }
        self.out.extend_from_slice(bytes);
        Ok(())
    }

    /// Begin a structure with the given tag. Children must be emitted
    /// with their own `put_*` / `write_value` calls; the structure is
    /// closed with [`Self::end_container`].
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn start_structure(&mut self, tag: Tag) -> Result<()> {
        self.write_tag(tag, et::STRUCTURE);
        Ok(())
    }

    /// Begin an array with the given tag. Children MUST be emitted with
    /// `Tag::Anonymous` per the Matter spec.
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn start_array(&mut self, tag: Tag) -> Result<()> {
        self.write_tag(tag, et::ARRAY);
        Ok(())
    }

    /// Begin a list with the given tag. List members may carry any tag
    /// form (including anonymous).
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn start_list(&mut self, tag: Tag) -> Result<()> {
        self.write_tag(tag, et::LIST);
        Ok(())
    }

    /// Emit the end-of-container marker (`0x18`) closing the most
    /// recently-opened container. The marker has no tag.
    ///
    /// # Errors
    ///
    /// Currently infallible; returns `Ok(())` always. The `Result` return
    /// type is reserved for future I/O-backed writers.
    pub fn end_container(&mut self) -> Result<()> {
        self.out.push(et::END_OF_CONTAINER);
        Ok(())
    }

    /// Walk a [`Value`] tree and emit the appropriate sequence of TLV
    /// elements. Scalar variants are dispatched to the corresponding
    /// `put_*` method; container variants (`Structure`, `Array`, `List`)
    /// recursively encode all members and close with [`Self::end_container`].
    ///
    /// Array elements are always written with [`Tag::Anonymous`] regardless of
    /// what tag is stored in the `Value`, enforcing the Matter spec requirement
    /// that array elements carry no tag.
    ///
    /// Container nesting is bounded by [`MAX_DEPTH`], mirroring the reader's
    /// limit. A `Value` tree nested deeper than that is rejected with
    /// [`Error::ContainerTooDeep`] rather than risking a stack overflow on a
    /// hostile or buggy input tree.
    ///
    /// # Errors
    ///
    /// - [`Error::ContainerTooDeep`] — the `value` tree nests containers more
    ///   than [`MAX_DEPTH`] levels deep.
    /// - Any error returned by the underlying `put_*` or container method.
    pub fn write_value(&mut self, tag: Tag, value: &Value) -> Result<()> {
        self.write_value_at_depth(tag, value, 0)
    }

    /// Recursive worker for [`Self::write_value`] that carries the current
    /// container nesting depth so it can fail closed before the native call
    /// stack is at risk.
    fn write_value_at_depth(&mut self, tag: Tag, value: &Value, depth: usize) -> Result<()> {
        match value {
            Value::Bool(v) => self.put_bool(tag, *v),
            Value::Null => self.put_null(tag),
            Value::Uint(v) => self.put_uint(tag, *v),
            Value::Int(v) => self.put_int(tag, *v),
            Value::Float(v) => self.put_float(tag, *v),
            Value::Double(v) => self.put_double(tag, *v),
            Value::Utf8(v) => self.put_utf8(tag, v),
            Value::Bytes(v) => self.put_bytes(tag, v),
            Value::Structure(members) => {
                if depth >= MAX_DEPTH {
                    return Err(Error::ContainerTooDeep);
                }
                self.start_structure(tag)?;
                for (member_tag, member_value) in members {
                    self.write_value_at_depth(*member_tag, member_value, depth + 1)?;
                }
                self.end_container()
            }
            Value::Array(elements) => {
                if depth >= MAX_DEPTH {
                    return Err(Error::ContainerTooDeep);
                }
                self.start_array(tag)?;
                for element in elements {
                    self.write_value_at_depth(Tag::Anonymous, element, depth + 1)?;
                }
                self.end_container()
            }
            Value::List(members) => {
                if depth >= MAX_DEPTH {
                    return Err(Error::ContainerTooDeep);
                }
                self.start_list(tag)?;
                for (member_tag, member_value) in members {
                    self.write_value_at_depth(*member_tag, member_value, depth + 1)?;
                }
                self.end_container()
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Test code: CLAUDE.md allows unwrap with
                              // a documented justification.
mod tests {
    use super::*;

    // --- Cycle 1: put_bool ---

    #[test]
    fn put_bool_true_anonymous_matches_vector_0001() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_bool(Tag::Anonymous, true).unwrap();
        assert_eq!(buf, [0x09]);
    }

    #[test]
    fn put_bool_false_anonymous_matches_vector_0002() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_bool(Tag::Anonymous, false).unwrap();
        assert_eq!(buf, [0x08]);
    }

    // --- Cycle 2: put_null ---

    #[test]
    fn put_null_anonymous_emits_0x14() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_null(Tag::Anonymous).unwrap();
        assert_eq!(buf, [0x14]);
    }

    // --- Cycle 3: put_uint ---

    #[test]
    fn put_uint_42_anonymous_picks_1_byte_width_matches_vector_0003() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::Anonymous, 42).unwrap();
        assert_eq!(buf, [0x04, 0x2A]);
    }

    #[test]
    fn put_uint_max_u8_anonymous_still_1_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::Anonymous, 255).unwrap();
        assert_eq!(buf, [0x04, 0xFF]);
    }

    #[test]
    fn put_uint_0x1234_anonymous_2_byte_le() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::Anonymous, 0x1234).unwrap();
        assert_eq!(buf, [0x05, 0x34, 0x12]);
    }

    #[test]
    fn put_uint_0xcafebabe_anonymous_4_byte_le() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::Anonymous, 0xCAFE_BABE).unwrap();
        assert_eq!(buf, [0x06, 0xBE, 0xBA, 0xFE, 0xCA]);
    }

    #[test]
    fn put_uint_big_anonymous_8_byte_le() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::Anonymous, 0x0123_4567_89AB_CDEF).unwrap();
        assert_eq!(buf, [0x07, 0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01]);
    }

    // --- Cycle 4: put_int ---

    #[test]
    fn put_int_neg17_anonymous_matches_vector_0008() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_int(Tag::Anonymous, -17).unwrap();
        assert_eq!(buf, [0x00, 0xEF]);
    }

    #[test]
    fn put_int_neg128_anonymous_1_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_int(Tag::Anonymous, -128).unwrap();
        assert_eq!(buf, [0x00, 0x80]);
    }

    #[test]
    fn put_int_neg129_anonymous_2_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_int(Tag::Anonymous, -129).unwrap();
        assert_eq!(buf, [0x01, 0x7F, 0xFF]);
    }

    #[test]
    fn put_int_i32_min_anonymous_4_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_int(Tag::Anonymous, i64::from(i32::MIN)).unwrap();
        assert_eq!(buf, [0x02, 0x00, 0x00, 0x00, 0x80]);
    }

    #[test]
    fn put_int_i64_min_anonymous_8_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_int(Tag::Anonymous, i64::MIN).unwrap();
        assert_eq!(buf, [0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]);
    }

    // --- Cycle 5: put_float and put_double ---

    #[test]
    fn put_float_zero_anonymous_matches_vector_0013() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_float(Tag::Anonymous, 0.0).unwrap();
        assert_eq!(buf, [0x0A, 0x00, 0x00, 0x00, 0x00]);
    }

    #[test]
    fn put_double_zero_anonymous_matches_vector_0014() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_double(Tag::Anonymous, 0.0).unwrap();
        assert_eq!(buf, [0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
    }

    // --- Cycle 6: context tag emission ---

    #[test]
    fn put_uint_with_context_tag_5_emits_tag_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::Context(5), 42).unwrap();
        // 0b001_00100 = 0x24 (context-tag form | UINT8 element type),
        // then tag number 0x05, then payload 0x2A.
        assert_eq!(buf, [0x24, 0x05, 0x2A]);
    }

    // --- Cycle 8: CommonProfile tag emission ---

    #[test]
    fn put_uint_with_common_profile_2_byte_tag() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::CommonProfile(7), 42).unwrap();
        // control = 0b010_00100 = 0x44 (CommonProfile 2-byte | UINT8)
        // tag bytes = 0x07 0x00 (LE u16), payload = 0x2A
        assert_eq!(buf, [0x44, 0x07, 0x00, 0x2A]);
    }

    #[test]
    fn put_uint_with_common_profile_4_byte_tag() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::CommonProfile(0x0001_2345), 42).unwrap();
        // control = 0b011_00100 = 0x64
        // tag bytes = 0x45 0x23 0x01 0x00 (LE u32), payload = 0x2A
        assert_eq!(buf, [0x64, 0x45, 0x23, 0x01, 0x00, 0x2A]);
    }

    #[test]
    fn put_uint_with_common_profile_at_u16_boundary_picks_2_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::CommonProfile(0xFFFF), 0).unwrap();
        assert_eq!(buf, [0x44, 0xFF, 0xFF, 0x00]);
    }

    #[test]
    fn put_uint_with_common_profile_just_above_u16_picks_4_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::CommonProfile(0x0001_0000), 0).unwrap();
        assert_eq!(buf, [0x64, 0x00, 0x00, 0x01, 0x00, 0x00]);
    }

    // --- Cycle 9: ImplicitProfile tag emission ---

    #[test]
    fn put_uint_with_implicit_profile_2_byte_tag() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::ImplicitProfile(7), 42).unwrap();
        // control = 0b100_00100 = 0x84
        assert_eq!(buf, [0x84, 0x07, 0x00, 0x2A]);
    }

    #[test]
    fn put_uint_with_implicit_profile_4_byte_tag() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(Tag::ImplicitProfile(0x0001_2345), 42).unwrap();
        // control = 0b101_00100 = 0xA4
        assert_eq!(buf, [0xA4, 0x45, 0x23, 0x01, 0x00, 0x2A]);
    }

    // --- Cycle 10: FullyQualified tag emission ---

    #[test]
    fn put_uint_with_fully_qualified_6_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(
            Tag::FullyQualified {
                vendor: 0xFFF1,
                profile: 0x0006,
                tag: 5,
            },
            42,
        )
        .unwrap();
        // control = 0b110_00100 = 0xC4 (FQ 6-byte | UINT8)
        // vendor 0xF1 0xFF, profile 0x06 0x00, tag 0x05 0x00, payload 0x2A
        assert_eq!(buf, [0xC4, 0xF1, 0xFF, 0x06, 0x00, 0x05, 0x00, 0x2A]);
    }

    #[test]
    fn put_uint_with_fully_qualified_8_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_uint(
            Tag::FullyQualified {
                vendor: 0xFFF1,
                profile: 0x0006,
                tag: 0x0001_2345,
            },
            42,
        )
        .unwrap();
        // control = 0b111_00100 = 0xE4
        assert_eq!(
            buf,
            [0xE4, 0xF1, 0xFF, 0x06, 0x00, 0x45, 0x23, 0x01, 0x00, 0x2A]
        );
    }

    // --- Cycle 11: put_utf8 ---

    #[test]
    fn put_utf8_hello_anonymous_matches_vector_0015() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_utf8(Tag::Anonymous, "Hello!").unwrap();
        assert_eq!(buf, [0x0C, 0x06, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x21]);
    }

    #[test]
    fn put_utf8_empty_anonymous_matches_vector_0016() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_utf8(Tag::Anonymous, "").unwrap();
        assert_eq!(buf, [0x0C, 0x00]);
    }

    #[test]
    fn put_utf8_at_255_byte_boundary_uses_len8() {
        let s: String = "a".repeat(255);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_utf8(Tag::Anonymous, &s).unwrap();
        assert_eq!(buf.len(), 1 + 1 + 255);
        assert_eq!(buf[0], 0x0C);
        assert_eq!(buf[1], 0xFF);
        assert!(buf[2..].iter().all(|&b| b == b'a'));
    }

    #[test]
    fn put_utf8_at_256_bytes_picks_len16() {
        let s: String = "a".repeat(256);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_utf8(Tag::Anonymous, &s).unwrap();
        assert_eq!(buf.len(), 1 + 2 + 256);
        assert_eq!(buf[0], 0x0D);
        assert_eq!(&buf[1..3], &[0x00, 0x01]);
        assert!(buf[3..].iter().all(|&b| b == b'a'));
    }

    #[test]
    fn put_utf8_at_u16_max_uses_len16() {
        let s: String = "a".repeat(usize::from(u16::MAX));
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_utf8(Tag::Anonymous, &s).unwrap();
        assert_eq!(buf[0], 0x0D);
        assert_eq!(&buf[1..3], &[0xFF, 0xFF]);
        assert_eq!(buf.len(), 1 + 2 + usize::from(u16::MAX));
    }

    #[test]
    fn put_utf8_above_u16_max_picks_len32() {
        let len = usize::from(u16::MAX) + 1; // 65,536
        let s: String = "a".repeat(len);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_utf8(Tag::Anonymous, &s).unwrap();
        assert_eq!(buf[0], 0x0E);
        assert_eq!(&buf[1..5], &[0x00, 0x00, 0x01, 0x00]);
        assert_eq!(buf.len(), 1 + 4 + len);
    }

    // --- Cycle 12: put_bytes ---

    #[test]
    fn put_bytes_five_bytes_anonymous_matches_vector_0017() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_bytes(Tag::Anonymous, &[0x00, 0x01, 0x02, 0x03, 0x04])
            .unwrap();
        assert_eq!(buf, [0x10, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04]);
    }

    #[test]
    fn put_bytes_empty_anonymous_matches_vector_0018() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_bytes(Tag::Anonymous, &[]).unwrap();
        assert_eq!(buf, [0x10, 0x00]);
    }

    #[test]
    fn put_bytes_at_256_bytes_picks_len16() {
        let data = vec![0xAB; 256];
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_bytes(Tag::Anonymous, &data).unwrap();
        assert_eq!(buf[0], 0x11);
        assert_eq!(&buf[1..3], &[0x00, 0x01]);
        assert_eq!(buf.len(), 1 + 2 + 256);
        assert!(buf[3..].iter().all(|&b| b == 0xAB));
    }

    // --- Cycle 7: write_value dispatch ---

    #[test]
    fn write_value_dispatches_on_utf8_and_bytes_variants() {
        for (value, expected) in [
            (
                Value::Utf8(String::from("Hello!")),
                vec![0x0C, 0x06, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x21],
            ),
            (
                Value::Bytes(vec![0x00, 0x01, 0x02, 0x03, 0x04]),
                vec![0x10, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04],
            ),
        ] {
            let mut buf = Vec::new();
            let mut w = TlvWriter::new(&mut buf);
            w.write_value(Tag::Anonymous, &value).unwrap();
            assert_eq!(buf, expected, "value={value:?}");
        }
    }

    #[test]
    fn write_value_dispatches_on_variant() {
        // One sanity case per variant. Bytes are taken from earlier per-method tests.
        for (value, expected) in [
            (Value::Bool(true), vec![0x09]),
            (Value::Null, vec![0x14]),
            (Value::Uint(42), vec![0x04, 0x2A]),
            (Value::Int(-17), vec![0x00, 0xEF]),
            (Value::Float(0.0), vec![0x0A, 0x00, 0x00, 0x00, 0x00]),
            (
                Value::Double(0.0),
                vec![0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
            ),
        ] {
            let mut buf = Vec::new();
            let mut w = TlvWriter::new(&mut buf);
            w.write_value(Tag::Anonymous, &value).unwrap();
            assert_eq!(buf, expected, "value={value:?}");
        }
    }

    // --- Phase 3 Task 2: container primitives ---

    #[test]
    fn start_structure_anonymous_emits_0x15() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        assert_eq!(buf, [0x15]);
    }

    #[test]
    fn start_array_anonymous_emits_0x16() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_array(Tag::Anonymous).unwrap();
        assert_eq!(buf, [0x16]);
    }

    #[test]
    fn start_list_anonymous_emits_0x17() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_list(Tag::Anonymous).unwrap();
        assert_eq!(buf, [0x17]);
    }

    #[test]
    fn end_container_emits_0x18() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.end_container().unwrap();
        assert_eq!(buf, [0x18]);
    }

    #[test]
    fn start_structure_with_context_tag_emits_combined_byte() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Context(7)).unwrap();
        // 0b001_10101 = 0x35 (context tag form | STRUCTURE element type)
        assert_eq!(buf, [0x35, 0x07]);
    }

    #[test]
    fn empty_structure_anonymous_matches_vector_0019() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.end_container().unwrap();
        assert_eq!(buf, [0x15, 0x18]);
    }

    #[test]
    fn structure_with_one_member_matches_vector_0021() {
        // [0x15, 0x24, 0x00, 0x2A, 0x18]
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_uint(Tag::Context(0), 42).unwrap();
        w.end_container().unwrap();
        assert_eq!(buf, [0x15, 0x24, 0x00, 0x2A, 0x18]);
    }

    // --- Phase 3 Task 3: write_value recursive container dispatch ---

    #[test]
    fn write_value_empty_structure_matches_vector_0019() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.write_value(Tag::Anonymous, &Value::Structure(Vec::new()))
            .unwrap();
        assert_eq!(buf, [0x15, 0x18]);
    }

    #[test]
    fn write_value_empty_array_matches_vector_0020() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.write_value(Tag::Anonymous, &Value::Array(Vec::new()))
            .unwrap();
        assert_eq!(buf, [0x16, 0x18]);
    }

    #[test]
    fn write_value_structure_with_ctx_member_matches_vector_0021() {
        let value = Value::Structure(vec![(Tag::Context(0), Value::Uint(42))]);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.write_value(Tag::Anonymous, &value).unwrap();
        assert_eq!(buf, [0x15, 0x24, 0x00, 0x2A, 0x18]);
    }

    #[test]
    fn write_value_array_of_three_uint8_matches_vector_0022() {
        let value = Value::Array(vec![Value::Uint(1), Value::Uint(2), Value::Uint(3)]);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.write_value(Tag::Anonymous, &value).unwrap();
        assert_eq!(buf, [0x16, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0x18]);
    }

    #[test]
    fn write_value_structure_with_bool_at_ctx7_matches_vector_0023() {
        let value = Value::Structure(vec![(Tag::Context(7), Value::Bool(true))]);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.write_value(Tag::Anonymous, &value).unwrap();
        assert_eq!(buf, [0x15, 0x29, 0x07, 0x18]);
    }

    #[test]
    fn write_value_empty_list_emits_0x17_0x18() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.write_value(Tag::Anonymous, &Value::List(Vec::new()))
            .unwrap();
        assert_eq!(buf, [0x17, 0x18]);
    }

    // --- put_preencoded ---

    #[test]
    fn put_preencoded_retags_anonymous_struct_to_context_1() {
        // An empty anonymous struct: 0x15 (anon-struct-start) 0x18 (end-container).
        let anonymous_struct = vec![0x15u8, 0x18];
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.put_preencoded(Tag::Context(1), &anonymous_struct)
            .unwrap();
        // Expected: context-tag struct at tag 1, then the body (0x18 end).
        // Control octet: tc::CONTEXT | et::STRUCTURE = 0x20 | 0x15 = 0x35
        // Tag byte: 0x01
        // Body: 0x18
        assert_eq!(buf, [0x35, 0x01, 0x18]);
    }

    #[test]
    fn put_preencoded_rejects_empty_input() {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        assert!(matches!(
            w.put_preencoded(Tag::Context(0), &[]),
            Err(Error::UnexpectedEof)
        ));
    }

    #[test]
    fn put_preencoded_rejects_non_anonymous_input() {
        // A context-tagged bool (tc::CONTEXT | et::BOOL_FALSE = 0x20 | 0x08 = 0x28).
        let non_anonymous = vec![0x28u8, 0x00];
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        assert!(matches!(
            w.put_preencoded(Tag::Context(0), &non_anonymous),
            Err(Error::InvalidTagControl(_))
        ));
    }

    #[test]
    fn put_preencoded_rejects_bare_end_of_container() {
        // 0x18 is END_OF_CONTAINER — anonymous tag bits (0b000) are valid, but
        // the element type is the delimiter, not a complete element.
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        assert!(matches!(
            w.put_preencoded(Tag::Context(1), &[0x18]),
            Err(Error::InvalidElementType(_))
        ));
    }

    #[test]
    fn write_value_nested_structure() {
        // outer { ctx(0): inner { ctx(0): uint8=42 } }
        let inner = Value::Structure(vec![(Tag::Context(0), Value::Uint(42))]);
        let outer = Value::Structure(vec![(Tag::Context(0), inner)]);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.write_value(Tag::Anonymous, &outer).unwrap();
        // 0x15 = anon-struct-start
        //   0x35 0x00 = ctx-tag-struct-start at tag 0 (0b001_10101)
        //     0x24 0x00 0x2A = ctx-tag uint8=42 at tag 0
        //   0x18 = inner end
        // 0x18 = outer end
        assert_eq!(buf, [0x15, 0x35, 0x00, 0x24, 0x00, 0x2A, 0x18, 0x18]);
    }

    // --- Task 19: write-side depth guard ---

    /// Build a `Value` tree of `levels` nested structures, innermost holding a
    /// single uint. `levels == 1` is one structure wrapping the scalar.
    fn nested_structure(levels: usize) -> Value {
        let mut v = Value::Uint(0);
        for _ in 0..levels {
            v = Value::Structure(vec![(Tag::Anonymous, v)]);
        }
        v
    }

    #[test]
    fn write_value_accepts_tree_at_max_depth() {
        // MAX_DEPTH nested containers is the deepest the reader accepts, so the
        // writer must accept it too (symmetric limits).
        let value = nested_structure(MAX_DEPTH);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        assert!(w.write_value(Tag::Anonymous, &value).is_ok());
    }

    #[test]
    fn write_value_rejects_over_deep_tree() {
        // One container deeper than the reader's limit must error (rather than
        // recurse far enough to risk a native stack overflow).
        let value = nested_structure(MAX_DEPTH + 1);
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        assert!(matches!(
            w.write_value(Tag::Anonymous, &value),
            Err(Error::ContainerTooDeep)
        ));
    }

    #[test]
    fn write_value_over_deep_tree_roundtrips_with_reader_limit() {
        // A tree the writer accepts (== MAX_DEPTH) must also decode back, and a
        // tree one deeper that the writer rejects matches the reader's own cap.
        let ok = nested_structure(MAX_DEPTH);
        let mut buf = Vec::new();
        TlvWriter::new(&mut buf)
            .write_value(Tag::Anonymous, &ok)
            .unwrap();
        let (_, decoded) = crate::reader::TlvReader::new(&buf).read_value().unwrap();
        assert_eq!(decoded, ok);
    }
}