wacore-binary 0.8.0

Binary data and constants for WhatsApp protocol
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
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
use crate::error::{BinaryError, Result};
use crate::jid::{JidRef, jid_ref_to_compact};
use crate::node::{AttrsRef, NodeContentRef, NodeRef, NodeStr, ValueRef};
use crate::token;
use compact_str::CompactString;
use std::borrow::Cow;

/// Each byte's two output characters, so unpacking is one load and one 2-byte
/// store per input byte instead of two shifts, two lookups and two bounds
/// checks. Packed values on the wire (a 13-digit phone number, a 20-character
/// id) are shorter than the SIMD chunk above, so this is the path that runs.
static HEX_PAIRS: [[u8; 2]; 256] = {
    const HEX: [u8; 16] = *b"0123456789ABCDEF";
    let mut table = [[0u8; 2]; 256];
    let mut i = 0;
    while i < 256 {
        table[i] = [HEX[i >> 4], HEX[i & 0x0F]];
        i += 1;
    }
    table
};

/// Nibble values 12, 13 and 14 encode nothing, so they are marked and the byte
/// carrying one falls back to the scalar path, which reports which half was
/// bad. `NIBBLE_INVALID` cannot collide with an output character.
const NIBBLE_INVALID: u8 = 0xFF;
static NIBBLE_PAIRS: [[u8; 2]; 256] = {
    const fn glyph(nibble: usize) -> u8 {
        match nibble {
            0..=9 => b'0' + nibble as u8,
            10 => b'-',
            11 => b'.',
            15 => 0,
            _ => NIBBLE_INVALID,
        }
    }
    let mut table = [[0u8; 2]; 256];
    let mut i = 0;
    while i < 256 {
        table[i] = [glyph(i >> 4), glyph(i & 0x0F)];
        i += 1;
    }
    table
};

/// Node-nesting cap rejecting deep-`LIST` frames that would overflow the stack via
/// unbounded `read_node_ref` recursion (real WA trees are well under 20 levels).
pub(crate) const MAX_NODE_DEPTH: usize = 128;

/// A node's head as [`Decoder::read_node_open`] decodes it, its children left
/// in the input.
pub(crate) struct NodeOpen<'a> {
    pub(crate) tag: NodeStr<'a>,
    pub(crate) attrs: AttrsRef<'a>,
    pub(crate) content: OpenContent<'a>,
}

/// What follows a node's attributes on the wire.
#[derive(Debug, PartialEq)]
pub enum OpenContent<'a> {
    /// Nothing, or an empty list.
    None,
    /// A list of this many child nodes, each still to be decoded.
    Children(usize),
    /// A string or a byte payload: decoded whole, since it has no parts.
    Scalar(NodeContentRef<'a>),
}

pub(crate) struct Decoder<'a> {
    data: &'a [u8],
    position: usize,
}

impl<'a> Decoder<'a> {
    pub(crate) fn new(data: &'a [u8]) -> Self {
        Self { data, position: 0 }
    }

    pub(crate) fn is_finished(&self) -> bool {
        self.position >= self.data.len()
    }

    pub(crate) fn bytes_left(&self) -> usize {
        self.data.len() - self.position
    }

    #[inline(always)]
    fn check_eos(&self, len: usize) -> Result<()> {
        if self.bytes_left() >= len {
            Ok(())
        } else {
            Err(BinaryError::UnexpectedEof)
        }
    }

    #[inline(always)]
    fn read_u8(&mut self) -> Result<u8> {
        self.check_eos(1)?;
        let position = self.position;
        self.position += 1;
        Ok(self.data[position])
    }

    #[inline(always)]
    fn read_u16_be(&mut self) -> Result<u16> {
        self.check_eos(2)?;
        let position = self.position;
        self.position += 2;
        Ok(u16::from_be_bytes([
            self.data[position],
            self.data[position + 1],
        ]))
    }

    #[inline(always)]
    fn read_u20_be(&mut self) -> Result<u32> {
        self.check_eos(3)?;
        let position = self.position;
        self.position += 3;
        let bytes = [
            self.data[position],
            self.data[position + 1],
            self.data[position + 2],
        ];
        Ok(((bytes[0] as u32 & 0x0F) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32))
    }

    #[inline(always)]
    fn read_u32_be(&mut self) -> Result<u32> {
        self.check_eos(4)?;
        let position = self.position;
        self.position += 4;
        Ok(u32::from_be_bytes([
            self.data[position],
            self.data[position + 1],
            self.data[position + 2],
            self.data[position + 3],
        ]))
    }

    #[inline(always)]
    fn read_bytes(&mut self, len: usize) -> Result<&'a [u8]> {
        self.check_eos(len)?;
        let start = self.position;
        let end = start + len;
        self.position = end;
        Ok(&self.data[start..end])
    }

    #[inline(always)]
    fn read_string(&mut self, len: usize) -> Result<NodeStr<'a>> {
        let bytes = self.read_bytes(len)?;
        // smoothutf8 has a faster fast-path for the short strings dominating the
        // wire (tags, attribute values, JID parts). It only answers valid/invalid,
        // so the cold rejection path reuses std to recover the precise Utf8Error.
        if let Some(s) = smoothutf8::from_utf8(bytes) {
            Ok(NodeStr::Borrowed(s))
        } else {
            match std::str::from_utf8(bytes) {
                Ok(s) => Ok(NodeStr::Borrowed(s)),
                Err(e) => Err(BinaryError::InvalidUtf8(e)),
            }
        }
    }

    #[inline(always)]
    fn read_list_size(&mut self, tag: u8) -> Result<usize> {
        match tag {
            token::LIST_EMPTY => Ok(0),
            token::LIST_8 => self.read_u8().map(|v| v as usize),
            token::LIST_16 => self.read_u16_be().map(|v| v as usize),
            _ => Err(BinaryError::InvalidToken(tag)),
        }
    }

    fn read_jid_pair(&mut self) -> Result<JidRef<'a>> {
        let user = self.read_value_as_string()?.unwrap_or_default();
        let server_str = self.read_value_as_string()?.unwrap_or_default();
        let server = crate::jid::Server::try_from(server_str.as_ref()).map_err(|_| {
            BinaryError::AttrParse(format!(
                "JID_PAIR unknown server ({} bytes)",
                server_str.len()
            ))
        })?;
        Ok(JidRef {
            user,
            server,
            agent: 0,
            device: 0,
            integrator: 0,
        })
    }

    fn read_ad_jid(&mut self) -> Result<JidRef<'a>> {
        let agent = self.read_u8()?;
        let device = self.read_u8()? as u16;
        let Some(user) = self.read_value_as_string()? else {
            return Err(BinaryError::InvalidNode);
        };

        // Domain type mapping must mirror WA Web decodeJidU.
        // WA Web: 0=WHATSAPP, 1=LID, even+bit7=HOSTED, 129=HOSTED_LID, else throw.
        let server = match agent {
            0 => crate::jid::Server::Pn,
            1 => crate::jid::Server::Lid,
            128 => crate::jid::Server::Hosted,
            129 => crate::jid::Server::HostedLid,
            n if (n & 128) != 0 && (n & 1) == 0 => crate::jid::Server::Hosted,
            _ => {
                return Err(BinaryError::AttrParse(format!(
                    "read_ad_jid - Invalid domain type encoding {agent}"
                )));
            }
        };

        Ok(JidRef {
            user,
            server,
            // The domain byte is not an agent — it is `server` in wire form, and
            // `write_jid_*` re-derives it from `server` on the way out. Keeping a
            // second copy here put a field in the derived `PartialEq`/`Hash` that
            // only wire-decoded JIDs ever carry, so the same JID compared unequal
            // depending on whether it came off the wire or out of the store (which
            // holds JIDs as text, where `Display` suppresses the agent anyway).
            agent: 0,
            device,
            integrator: 0,
        })
    }

    fn read_interop_jid(&mut self) -> Result<JidRef<'a>> {
        let Some(user) = self.read_value_as_string()? else {
            return Err(BinaryError::InvalidNode);
        };
        let device = self.read_u16_be()?;
        let integrator = self.read_u16_be()?;
        let server_str = self.read_value_as_string()?.unwrap_or_default();
        if server_str.as_ref() != crate::jid::INTEROP_SERVER {
            return Err(BinaryError::InvalidNode);
        }
        Ok(JidRef {
            user,
            server: crate::jid::Server::Interop,
            device,
            integrator,
            agent: 0,
        })
    }

    fn read_fb_jid(&mut self) -> Result<JidRef<'a>> {
        let Some(user) = self.read_value_as_string()? else {
            return Err(BinaryError::InvalidNode);
        };
        let device = self.read_u16_be()?;
        let server_str = self.read_value_as_string()?.unwrap_or_default();
        if server_str.as_ref() != crate::jid::MESSENGER_SERVER {
            return Err(BinaryError::InvalidNode);
        }
        Ok(JidRef {
            user,
            server: crate::jid::Server::Messenger,
            device,
            agent: 0,
            integrator: 0,
        })
    }

    fn read_value_as_string(&mut self) -> Result<Option<NodeStr<'a>>> {
        let tag = self.read_u8()?;
        self.read_value_as_string_from_tag(tag)
    }

    #[inline(always)]
    fn read_value_as_string_from_tag(&mut self, tag: u8) -> Result<Option<NodeStr<'a>>> {
        match tag {
            token::LIST_EMPTY => Ok(None),
            token::BINARY_8 => {
                let size = self.read_u8()? as usize;
                self.read_string(size).map(Some)
            }
            token::BINARY_20 => {
                let size = self.read_u20_be()? as usize;
                self.read_string(size).map(Some)
            }
            token::BINARY_32 => {
                let size = self.read_u32_be()? as usize;
                self.read_string(size).map(Some)
            }
            token::JID_PAIR => self
                .read_jid_pair()
                .map(|j| Some(NodeStr::Owned(jid_ref_to_compact(&j)))),
            token::AD_JID => self
                .read_ad_jid()
                .map(|j| Some(NodeStr::Owned(jid_ref_to_compact(&j)))),
            token::INTEROP_JID => self
                .read_interop_jid()
                .map(|j| Some(NodeStr::Owned(jid_ref_to_compact(&j)))),
            token::FB_JID => self
                .read_fb_jid()
                .map(|j| Some(NodeStr::Owned(jid_ref_to_compact(&j)))),
            token::NIBBLE_8 | token::HEX_8 => {
                self.read_packed(tag).map(|s| Some(NodeStr::Owned(s)))
            }
            tag @ token::DICTIONARY_0..=token::DICTIONARY_3 => {
                let index = self.read_u8()?;
                match token::get_double_token(tag - token::DICTIONARY_0, index) {
                    Some(s) => Ok(Some(NodeStr::Borrowed(s))),
                    None => Err(BinaryError::InvalidToken(tag)),
                }
            }
            _ => match token::get_single_token(tag) {
                Some(s) => Ok(Some(NodeStr::Borrowed(s))),
                None => Err(BinaryError::InvalidToken(tag)),
            },
        }
    }

    fn read_value(&mut self) -> Result<Option<ValueRef<'a>>> {
        let tag = self.read_u8()?;
        match tag {
            token::LIST_EMPTY => Ok(None),
            token::BINARY_8 => {
                let size = self.read_u8()? as usize;
                self.read_string(size).map(|s| Some(ValueRef::String(s)))
            }
            token::BINARY_20 => {
                let size = self.read_u20_be()? as usize;
                self.read_string(size).map(|s| Some(ValueRef::String(s)))
            }
            token::BINARY_32 => {
                let size = self.read_u32_be()? as usize;
                self.read_string(size).map(|s| Some(ValueRef::String(s)))
            }
            token::JID_PAIR => self.read_jid_pair().map(|j| Some(ValueRef::Jid(j))),
            token::AD_JID => self.read_ad_jid().map(|j| Some(ValueRef::Jid(j))),
            token::INTEROP_JID => self.read_interop_jid().map(|j| Some(ValueRef::Jid(j))),
            token::FB_JID => self.read_fb_jid().map(|j| Some(ValueRef::Jid(j))),
            token::NIBBLE_8 | token::HEX_8 => self
                .read_packed(tag)
                .map(|s| Some(ValueRef::String(NodeStr::Owned(s)))),
            tag @ token::DICTIONARY_0..=token::DICTIONARY_3 => {
                let index = self.read_u8()?;
                match token::get_double_token(tag - token::DICTIONARY_0, index) {
                    Some(s) => Ok(Some(ValueRef::String(NodeStr::Borrowed(s)))),
                    None => Err(BinaryError::InvalidToken(tag)),
                }
            }
            _ => match token::get_single_token(tag) {
                Some(s) => Ok(Some(ValueRef::String(NodeStr::Borrowed(s)))),
                None => Err(BinaryError::InvalidToken(tag)),
            },
        }
    }

    /// Decode packed nibble/hex into a stack buffer, then create CompactString.
    /// Max unpacked length is 254 bytes (127 packed × 2), so the stack buffer
    /// is always sufficient. Short values (≤24 bytes) are stored inline.
    fn read_packed(&mut self, tag: u8) -> Result<CompactString> {
        let packed_len_byte = self.read_u8()?;
        let is_half_byte = (packed_len_byte & 0x80) != 0;
        let len = (packed_len_byte & 0x7F) as usize;

        if len == 0 {
            return Ok(CompactString::default());
        }

        let packed_data = self.read_bytes(len)?;
        // Phone numbers and message IDs usually fit in 24 decoded bytes.
        if len <= 12 {
            Self::decode_packed::<24>(tag, packed_data, is_half_byte)
        } else {
            Self::decode_packed::<254>(tag, packed_data, is_half_byte)
        }
    }

    #[inline(always)]
    fn decode_packed<const N: usize>(
        tag: u8,
        packed_data: &[u8],
        is_half_byte: bool,
    ) -> Result<CompactString> {
        let mut buf = [0u8; N];
        let mut pos = 0;

        match tag {
            token::HEX_8 => Self::decode_packed_hex(packed_data, &mut buf, &mut pos),
            token::NIBBLE_8 => Self::decode_packed_nibble(packed_data, &mut buf, &mut pos)?,
            _ => return Err(BinaryError::InvalidToken(tag)),
        }

        if is_half_byte && pos > 0 {
            pos -= 1;
        }

        // Unlike `read_string`, which validates bytes that came off the wire,
        // this validates bytes the tables above just wrote, so it can never
        // fail. Keeping a check at all is cheap insurance against a future
        // table edit; smoothutf8 is the same validator the wire path uses.
        let s = smoothutf8::from_utf8(&buf[..pos]).expect("packed decode produced non-ASCII");
        Ok(CompactString::from(s))
    }

    // Deliberately scalar. A vectorised version of this loop lived here until
    // it was measured against the table: `HEX_PAIRS[byte]` is one 2-byte load
    // per input byte, and a shuffle/interleave/store sequence does not beat
    // that. Under callgrind the SIMD path cost 4.5% more instructions on a
    // 20-character id and 9.7% more on a 32-character one, and enabling real
    // `pshufb` (`-Ctarget-cpu=x86-64-v2`) only narrowed the loss to 7.0%.
    // Packed payloads are ids and phone numbers, so the loop also needed a
    // 31-character string before it engaged at all.
    #[inline]
    fn decode_packed_hex(packed_data: &[u8], out: &mut [u8], pos: &mut usize) {
        let written = packed_data.len() * 2;
        for (slot, &byte) in out[*pos..*pos + written]
            .as_chunks_mut::<2>()
            .0
            .iter_mut()
            .zip(packed_data)
        {
            slot.copy_from_slice(&HEX_PAIRS[byte as usize]);
        }
        *pos += written;
    }

    // Scalar for the same reason as `decode_packed_hex`, and more so: the
    // vector version had to validate every lane against the two legal
    // out-of-range nibbles before it could shuffle, then fall back to this
    // loop anyway whenever a lane failed.
    #[inline]
    fn decode_packed_nibble(packed_data: &[u8], out: &mut [u8], pos: &mut usize) -> Result<()> {
        let written = packed_data.len() * 2;
        for (slot, &byte) in out[*pos..*pos + written]
            .as_chunks_mut::<2>()
            .0
            .iter_mut()
            .zip(packed_data)
        {
            let pair = NIBBLE_PAIRS[byte as usize];
            // Valid glyphs are ASCII. An invalid nibble sets the high bit.
            if (pair[0] | pair[1]) & 0x80 != 0 {
                // Report the bad half in the order the byte carries it.
                Self::unpack_nibble((byte & 0xF0) >> 4)?;
                Self::unpack_nibble(byte & 0x0F)?;
            }
            slot.copy_from_slice(&pair);
        }
        *pos += written;

        Ok(())
    }

    #[inline(always)]
    fn unpack_nibble(value: u8) -> Result<u8> {
        match value {
            0..=9 => Ok(b'0' + value),
            10 => Ok(b'-'),
            11 => Ok(b'.'),
            15 => Ok(0),
            _ => Err(BinaryError::InvalidToken(value)),
        }
    }

    fn read_attributes(&mut self, size: usize) -> Result<AttrsRef<'a>> {
        if size == 0 {
            return Ok(AttrsRef::Empty);
        }
        let mut v = Vec::with_capacity(size);
        for _ in 0..size {
            let Some(key) = self.read_value_as_string()? else {
                return Err(BinaryError::NonStringKey);
            };
            let value = match self.read_value()? {
                Some(v) => v,
                None => ValueRef::String(NodeStr::Borrowed("")),
            };
            v.push((key, value));
        }
        Ok(AttrsRef::from_vec(v))
    }

    #[inline(always)]
    fn read_content_from_tag(
        &mut self,
        tag: u8,
        depth: usize,
    ) -> Result<Option<NodeContentRef<'a>>> {
        match tag {
            token::LIST_EMPTY => Ok(None),

            token::LIST_8 | token::LIST_16 => {
                let size = self.read_list_size(tag)?;
                let mut nodes = Vec::with_capacity(size);
                for _ in 0..size {
                    nodes.push(self.read_node_ref_at(depth + 1)?);
                }
                Ok(Some(NodeContentRef::Nodes(nodes.into_boxed_slice())))
            }

            token::BINARY_8 => {
                let len = self.read_u8()? as usize;
                let bytes = self.read_bytes(len)?;
                Ok(Some(NodeContentRef::Bytes(Cow::Borrowed(bytes))))
            }
            token::BINARY_20 => {
                let len = self.read_u20_be()? as usize;
                let bytes = self.read_bytes(len)?;
                Ok(Some(NodeContentRef::Bytes(Cow::Borrowed(bytes))))
            }
            token::BINARY_32 => {
                let len = self.read_u32_be()? as usize;
                let bytes = self.read_bytes(len)?;
                Ok(Some(NodeContentRef::Bytes(Cow::Borrowed(bytes))))
            }

            _ => {
                let string_content = self.read_value_as_string_from_tag(tag)?;

                match string_content {
                    Some(s) => Ok(Some(NodeContentRef::String(s))),
                    None => Ok(None),
                }
            }
        }
    }

    pub(crate) fn read_node_ref(&mut self) -> Result<NodeRef<'a>> {
        self.read_node_ref_at(0)
    }

    /// Bytes consumed so far: what a caller feeding this decoder from a larger
    /// buffer has to drop once it is done with what was decoded.
    #[inline]
    pub(crate) fn position(&self) -> usize {
        self.position
    }

    /// Decode a node's head only: tag, attributes and what its content is,
    /// leaving any child nodes unread for the caller to decode one at a time.
    /// The counterpart of [`Self::read_node_ref_at`] for a node too large to
    /// hold as a tree; it reads exactly the bytes that precede the first child.
    pub(crate) fn read_node_open(&mut self) -> Result<NodeOpen<'a>> {
        let tag = self.read_u8()?;
        let list_size = self.read_list_size(tag)?;
        if list_size == 0 {
            return Err(BinaryError::InvalidNode);
        }

        let Some(tag) = self.read_value_as_string()? else {
            return Err(BinaryError::InvalidNode);
        };

        let attr_count = (list_size - 1) / 2;
        let has_content = list_size.is_multiple_of(2);

        let attrs = self.read_attributes(attr_count)?;
        let content = if has_content {
            let content_tag = self.read_u8()?;
            match content_tag {
                token::LIST_EMPTY => OpenContent::None,
                token::LIST_8 | token::LIST_16 => {
                    OpenContent::Children(self.read_list_size(content_tag)?)
                }
                // Depth 0 is fine: a scalar never recurses.
                _ => match self.read_content_from_tag(content_tag, 0)? {
                    Some(scalar) => OpenContent::Scalar(scalar),
                    None => OpenContent::None,
                },
            }
        } else {
            OpenContent::None
        };

        Ok(NodeOpen {
            tag,
            attrs,
            content,
        })
    }

    /// Walk past one value token without building anything: the measuring
    /// pass of a streaming decode, which has to learn how many bytes a node
    /// takes before it can decode it from a buffer it may still have to grow.
    ///
    /// Mirrors [`Self::read_value`] token for token, validation included: a
    /// string that is not UTF-8 or a packed nibble outside its alphabet is an
    /// error here as it is there, so a node the stream skips unread is held
    /// to what the tree decoder would have rejected. The JID forms reuse the
    /// readers because their layout is validation, not just length.
    fn skip_value(&mut self) -> Result<()> {
        let tag = self.read_u8()?;
        self.skip_value_from_tag(tag)
    }

    fn skip_value_from_tag(&mut self, tag: u8) -> Result<()> {
        match tag {
            token::LIST_EMPTY => Ok(()),
            token::BINARY_8 => {
                let size = self.read_u8()? as usize;
                self.read_string(size).map(drop)
            }
            token::BINARY_20 => {
                let size = self.read_u20_be()? as usize;
                self.read_string(size).map(drop)
            }
            token::BINARY_32 => {
                let size = self.read_u32_be()? as usize;
                self.read_string(size).map(drop)
            }
            token::JID_PAIR => self.read_jid_pair().map(drop),
            token::AD_JID => self.read_ad_jid().map(drop),
            token::INTEROP_JID => self.read_interop_jid().map(drop),
            token::FB_JID => self.read_fb_jid().map(drop),
            token::NIBBLE_8 | token::HEX_8 => {
                let len = (self.read_u8()? & 0x7F) as usize;
                let packed = self.read_bytes(len)?;
                // Every byte is a valid hex pair; only nibbles have holes.
                if tag == token::NIBBLE_8
                    && let Some(&byte) = packed.iter().find(|&&byte| {
                        let pair = NIBBLE_PAIRS[byte as usize];
                        pair[0] == NIBBLE_INVALID || pair[1] == NIBBLE_INVALID
                    })
                {
                    Self::unpack_nibble((byte & 0xF0) >> 4)?;
                    Self::unpack_nibble(byte & 0x0F)?;
                }
                Ok(())
            }
            tag @ token::DICTIONARY_0..=token::DICTIONARY_3 => {
                let index = self.read_u8()?;
                token::get_double_token(tag - token::DICTIONARY_0, index)
                    .map(drop)
                    .ok_or(BinaryError::InvalidToken(tag))
            }
            _ => token::get_single_token(tag)
                .map(drop)
                .ok_or(BinaryError::InvalidToken(tag)),
        }
    }

    /// Walk past a node's scalar content, whose tag has been read. Binary
    /// content is opaque to [`Self::read_content_from_tag`] too, so only its
    /// length is checked; anything else is a string value and validated as one.
    fn skip_scalar_content(&mut self, tag: u8) -> Result<()> {
        match tag {
            token::BINARY_8 => {
                let len = self.read_u8()? as usize;
                self.read_bytes(len).map(drop)
            }
            token::BINARY_20 => {
                let len = self.read_u20_be()? as usize;
                self.read_bytes(len).map(drop)
            }
            token::BINARY_32 => {
                let len = self.read_u32_be()? as usize;
                self.read_bytes(len).map(drop)
            }
            _ => self.skip_value_from_tag(tag),
        }
    }

    /// Walk past a node's head (through the child count, when it has one) and
    /// report how many children were announced. The measuring twin of
    /// [`Self::read_node_open`].
    pub(crate) fn skip_node_open(&mut self) -> Result<usize> {
        let tag = self.read_u8()?;
        let list_size = self.read_list_size(tag)?;
        if list_size == 0 {
            return Err(BinaryError::InvalidNode);
        }
        // The same two shapes `read_node_open` refuses: a node with no tag,
        // and an attribute whose key is not a string.
        let tag_token = self.read_u8()?;
        if tag_token == token::LIST_EMPTY {
            return Err(BinaryError::InvalidNode);
        }
        self.skip_value_from_tag(tag_token)?;
        let attr_count = (list_size - 1) / 2;
        for _ in 0..attr_count {
            let key_token = self.read_u8()?;
            if key_token == token::LIST_EMPTY {
                return Err(BinaryError::NonStringKey);
            }
            self.skip_value_from_tag(key_token)?;
            self.skip_value()?;
        }
        if !list_size.is_multiple_of(2) {
            return Ok(0);
        }
        let content_tag = self.read_u8()?;
        match content_tag {
            token::LIST_EMPTY => Ok(0),
            token::LIST_8 | token::LIST_16 => self.read_list_size(content_tag),
            _ => {
                self.skip_scalar_content(content_tag)?;
                Ok(0)
            }
        }
    }

    /// Walk past a whole node, subtree included. The measuring twin of
    /// [`Self::read_node_ref_at`], with the same depth cap.
    pub(crate) fn skip_node_at(&mut self, depth: usize) -> Result<()> {
        if depth >= MAX_NODE_DEPTH {
            return Err(BinaryError::MaxDepthExceeded);
        }
        let children = self.skip_node_open()?;
        for _ in 0..children {
            self.skip_node_at(depth + 1)?;
        }
        Ok(())
    }

    pub(crate) fn read_node_ref_at(&mut self, depth: usize) -> Result<NodeRef<'a>> {
        // Reject before recursing, so a hostile deep-LIST frame errors instead of
        // aborting the process on a stack overflow.
        if depth >= MAX_NODE_DEPTH {
            return Err(BinaryError::MaxDepthExceeded);
        }
        // One head reader for both decoders: the tree is the head plus its
        // children read whole, which is also what keeps the two in agreement
        // on what a malformed head is.
        let head = self.read_node_open()?;
        let content = match head.content {
            OpenContent::None => None,
            OpenContent::Scalar(scalar) => Some(scalar),
            OpenContent::Children(count) => {
                let mut nodes = Vec::with_capacity(count);
                for _ in 0..count {
                    nodes.push(self.read_node_ref_at(depth + 1)?);
                }
                Some(NodeContentRef::Nodes(nodes.into_boxed_slice()))
            }
        };

        Ok(NodeRef {
            tag: head.tag,
            attrs: head.attrs,
            content,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::node::{Attrs, Node};

    type TestResult = Result<()>;

    #[test]
    fn test_decode_node() -> TestResult {
        let node = Node::new(
            "message",
            Attrs::new(),
            Some(crate::node::NodeContent::String("receipt".into())),
        );

        let mut buffer = Vec::new();
        {
            let mut encoder = crate::encoder::Encoder::new(std::io::Cursor::new(&mut buffer))?;
            encoder.write_node(&node)?;
        }

        let mut decoder = Decoder::new(&buffer[1..]);
        let decoded = decoder.read_node_ref().unwrap();

        assert_eq!(decoded.tag, "message");
        assert!(decoded.attrs.is_empty());
        match &decoded.content {
            Some(content) => match content {
                NodeContentRef::String(s) => assert_eq!(s, "receipt"),
                _ => panic!("Expected string content"),
            },
            None => panic!("Expected content"),
        }
        Ok(())
    }

    #[test]
    fn test_decode_nibble_packing() -> TestResult {
        let test_str = "-.0123456789";
        let node = Node::new(
            "test",
            Attrs::new(),
            Some(crate::node::NodeContent::String(test_str.into())),
        );

        let mut buffer = Vec::new();
        {
            let mut encoder = crate::encoder::Encoder::new(std::io::Cursor::new(&mut buffer))?;
            encoder.write_node(&node)?;
        }

        let mut decoder = Decoder::new(&buffer[1..]);
        let decoded = decoder.read_node_ref().unwrap();

        assert_eq!(decoded.tag, "test");
        assert!(decoded.attrs.is_empty());
        match &decoded.content {
            Some(content) => match content {
                NodeContentRef::String(s) => assert_eq!(s, test_str),
                _ => panic!("Expected string content"),
            },
            None => panic!("Expected content"),
        }
        Ok(())
    }

    #[test]
    fn test_invalid_nibble_rejection() {
        let invalid_data = vec![1, 0xC0];

        let mut decoder = Decoder::new(&invalid_data);
        let result = decoder.read_packed(token::NIBBLE_8);
        assert!(
            result.is_err(),
            "Expected error for invalid nibble 12, got: {:?}",
            result
        );

        if let Err(BinaryError::InvalidToken(invalid_nibble)) = result {
            assert_eq!(invalid_nibble, 12, "Expected invalid nibble 12");
        } else {
            panic!("Expected InvalidToken error, got: {:?}", result);
        }
    }

    /// Test empty input returns appropriate error
    #[test]
    fn test_empty_input() {
        let mut decoder = Decoder::new(&[]);
        let result = decoder.read_node_ref();
        assert!(result.is_err());
    }

    /// Test truncated u16 read
    #[test]
    fn test_truncated_u16() {
        // Only one byte when u16 expected
        let data = vec![0x42];
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_u16_be();
        assert!(result.is_err());
        if let Err(BinaryError::UnexpectedEof) = result {
            // Expected
        } else {
            panic!("Expected UnexpectedEof, got: {:?}", result);
        }
    }

    /// Test truncated u20 read
    #[test]
    fn test_truncated_u20() {
        // Only two bytes when u20 (3 bytes) expected
        let data = vec![0x42, 0x43];
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_u20_be();
        assert!(result.is_err());
    }

    /// Test truncated u32 read
    #[test]
    fn test_truncated_u32() {
        // Only three bytes when u32 expected
        let data = vec![0x42, 0x43, 0x44];
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_u32_be();
        assert!(result.is_err());
    }

    /// Test BINARY_8 with length larger than remaining buffer
    #[test]
    fn test_binary8_length_exceeds_buffer() {
        // BINARY_8 token, length 100, but only 5 bytes of data
        let data = vec![token::BINARY_8, 100, 1, 2, 3, 4, 5];
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_value_as_string();
        assert!(result.is_err());
    }

    /// Test BINARY_20 with length larger than remaining buffer
    #[test]
    fn test_binary20_length_exceeds_buffer() {
        // BINARY_20 token, length encoded as 256, but only a few bytes of data
        let data = vec![token::BINARY_20, 0x00, 0x01, 0x00, 1, 2, 3]; // length = 256
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_value_as_string();
        assert!(result.is_err());
    }

    /// Test LIST_8 with size larger than remaining data
    #[test]
    fn test_list8_size_exceeds_data() {
        // LIST_8 token, size 10, but not enough data for 10 nodes
        let data = vec![token::LIST_8, 10, 1]; // Only 1 byte of data for nodes
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_node_ref();
        assert!(result.is_err());
    }

    /// Attribute storage capacity must not change how a broken attribute list
    /// is rejected: a truncated pair, a non-string key and a declared count the
    /// frame cannot back all fail the same way they did before.
    #[test]
    fn malformed_attribute_lists_keep_their_errors() {
        // <message> claiming one attribute, cut off after the key.
        let truncated = [
            token::LIST_8,
            3,
            token::DICTIONARY_0,
            0,
            token::BINARY_8,
            2,
            b'i',
            b'd',
        ];
        assert!(matches!(
            Decoder::new(&truncated).read_node_ref(),
            Err(BinaryError::UnexpectedEof)
        ));

        // An empty list where a string key is required.
        let non_string_key = [token::LIST_8, 3, token::DICTIONARY_0, 0, token::LIST_EMPTY];
        assert!(matches!(
            Decoder::new(&non_string_key).read_node_ref(),
            Err(BinaryError::NonStringKey)
        ));

        // Declares 4 attributes, carries none.
        let overlong_count = [token::LIST_8, 9, token::DICTIONARY_0, 0];
        assert!(matches!(
            Decoder::new(&overlong_count).read_node_ref(),
            Err(BinaryError::UnexpectedEof)
        ));

        // A list size of zero has no room even for the tag.
        assert!(matches!(
            Decoder::new(&[token::LIST_EMPTY]).read_node_ref(),
            Err(BinaryError::InvalidNode)
        ));
    }

    /// Test invalid token value
    #[test]
    fn test_invalid_token() {
        // Use a token value that's reserved and not valid as a string token
        // e.g., AD_JID (247) followed by insufficient data
        let data = vec![token::AD_JID]; // No data following
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_value_as_string();
        assert!(result.is_err());
    }

    #[test]
    fn test_ad_jid_rejects_invalid_domain_type() {
        let data = vec![token::AD_JID, 2, 1, token::BINARY_8, 3, b'1', b'2', b'3'];
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_value_as_string();

        match result {
            Err(BinaryError::AttrParse(msg)) => {
                assert!(
                    msg.contains("Invalid domain type encoding 2"),
                    "unexpected error message: {msg}"
                );
            }
            other => panic!("expected AttrParse for invalid AD_JID domain type, got {other:?}"),
        }
    }

    /// Test read_bytes with exact length
    #[test]
    fn test_read_bytes_exact_length() {
        let data = vec![1, 2, 3, 4, 5];
        let mut decoder = Decoder::new(&data);
        let bytes = decoder.read_bytes(5).unwrap();
        assert_eq!(bytes, &[1, 2, 3, 4, 5]);
        assert!(decoder.is_finished());
    }

    /// Test read_bytes exceeding length
    #[test]
    fn test_read_bytes_exceeding_length() {
        let data = vec![1, 2, 3];
        let mut decoder = Decoder::new(&data);
        let result = decoder.read_bytes(5);
        assert!(result.is_err());
    }

    /// Test u20 encoding/decoding values
    #[test]
    fn test_u20_encoding() {
        // Test value 0
        let data = vec![0x00, 0x00, 0x00];
        let mut decoder = Decoder::new(&data);
        assert_eq!(decoder.read_u20_be().unwrap(), 0);

        // Test value 256 (0x100)
        let data = vec![0x00, 0x01, 0x00];
        let mut decoder = Decoder::new(&data);
        assert_eq!(decoder.read_u20_be().unwrap(), 256);

        // Test value 65536 (0x10000)
        let data = vec![0x01, 0x00, 0x00];
        let mut decoder = Decoder::new(&data);
        assert_eq!(decoder.read_u20_be().unwrap(), 65536);

        // Test max u20 value (0xFFFFF = 1048575)
        let data = vec![0x0F, 0xFF, 0xFF];
        let mut decoder = Decoder::new(&data);
        assert_eq!(decoder.read_u20_be().unwrap(), 1048575);
    }

    /// Test bytes_left tracking
    #[test]
    fn test_bytes_left() {
        let data = vec![1, 2, 3, 4, 5];
        let mut decoder = Decoder::new(&data);

        assert_eq!(decoder.bytes_left(), 5);
        decoder.read_u8().unwrap();
        assert_eq!(decoder.bytes_left(), 4);
        decoder.read_u8().unwrap();
        assert_eq!(decoder.bytes_left(), 3);
        decoder.read_bytes(3).unwrap();
        assert_eq!(decoder.bytes_left(), 0);
        assert!(decoder.is_finished());
    }

    /// Test hex packed string decoding
    #[test]
    fn test_hex_packed_decoding() {
        // Encode "ABCDEF" as hex packed
        // Each byte packs two hex digits
        // A=10, B=11, C=12, D=13, E=14, F=15
        let packed_data = vec![
            3,    // length = 3 bytes = 6 characters
            0xAB, // AB
            0xCD, // CD
            0xEF, // EF
        ];

        let mut decoder = Decoder::new(&packed_data);
        let result = decoder.read_packed(token::HEX_8).unwrap();
        assert_eq!(result, "ABCDEF");
    }

    /// Test nibble packed string with odd length
    #[test]
    fn packed_scratch_handles_short_long_and_odd_values() {
        for length in [11, 12, 13, 127] {
            for odd in [false, true] {
                let mut wire = vec![0x23; length + 1];
                wire[0] = length as u8 | if odd { 0x80 } else { 0 };
                let expected = "23".repeat(length);
                let expected = &expected[..expected.len() - usize::from(odd)];
                for tag in [token::HEX_8, token::NIBBLE_8] {
                    let mut decoder = Decoder::new(&wire);
                    assert_eq!(decoder.read_packed(tag).unwrap(), expected);
                    assert!(decoder.is_finished());
                }
                wire[1] = 0xcd;
                assert!(matches!(
                    Decoder::new(&wire).read_packed(token::NIBBLE_8),
                    Err(BinaryError::InvalidToken(12))
                ));
                wire[1] = 0x3e;
                assert!(matches!(
                    Decoder::new(&wire).read_packed(token::NIBBLE_8),
                    Err(BinaryError::InvalidToken(14))
                ));
            }
        }
    }

    #[test]
    fn test_nibble_packed_odd_length() {
        // Encode "123" as nibble packed (odd length = 3)
        // 1=1, 2=2, 3=3, pad=15
        let packed_data = vec![
            0x82, // length = 2 bytes, high bit set for odd
            0x12, // 12
            0x3F, // 3 + pad (15)
        ];

        let mut decoder = Decoder::new(&packed_data);
        let result = decoder.read_packed(token::NIBBLE_8).unwrap();
        assert_eq!(result, "123");
    }

    /// Test empty packed string
    #[test]
    fn test_empty_packed_string() {
        let packed_data = vec![0]; // length = 0

        let mut decoder = Decoder::new(&packed_data);
        let result = decoder.read_packed(token::NIBBLE_8).unwrap();
        assert_eq!(result, "");
    }

    /// Test invalid nibble value 12 (only 0-11, 15 are valid)
    #[test]
    fn test_invalid_nibble_value_12() {
        // 12 (0xC) is not a valid nibble
        let packed_data = vec![1, 0xC0]; // first nibble is 12

        let mut decoder = Decoder::new(&packed_data);
        let result = decoder.read_packed(token::NIBBLE_8);
        assert!(result.is_err());
    }

    /// Test invalid nibble value 13
    #[test]
    fn test_invalid_nibble_value_13() {
        let packed_data = vec![1, 0xD0]; // first nibble is 13

        let mut decoder = Decoder::new(&packed_data);
        let result = decoder.read_packed(token::NIBBLE_8);
        assert!(result.is_err());
    }

    /// Test invalid nibble value 14
    #[test]
    fn test_invalid_nibble_value_14() {
        let packed_data = vec![1, 0xE0]; // first nibble is 14

        let mut decoder = Decoder::new(&packed_data);
        let result = decoder.read_packed(token::NIBBLE_8);
        assert!(result.is_err());
    }

    /// Test deeply nested nodes (recursion safety)
    #[test]
    fn test_nested_nodes() -> TestResult {
        // Create a 50-level deep node structure
        let mut current = Node::new("leaf", Attrs::new(), None);

        for i in 0..50 {
            let tag = format!("level{}", i);
            current = Node::new(
                tag,
                Attrs::new(),
                Some(crate::node::NodeContent::Nodes(vec![current])),
            );
        }

        let mut buffer = Vec::new();
        {
            let mut encoder = crate::encoder::Encoder::new(std::io::Cursor::new(&mut buffer))?;
            encoder.write_node(&current)?;
        }

        let mut decoder = Decoder::new(&buffer[1..]);
        let decoded = decoder.read_node_ref()?;

        // Verify top level tag
        assert_eq!(decoded.tag, "level49");
        Ok(())
    }

    fn encode_nested(levels: usize) -> Vec<u8> {
        let mut current = Node::new("leaf", Attrs::new(), None);
        for i in 0..levels {
            current = Node::new(
                format!("l{i}"),
                Attrs::new(),
                Some(crate::node::NodeContent::Nodes(vec![current])),
            );
        }
        let mut buffer = Vec::new();
        {
            let mut encoder =
                crate::encoder::Encoder::new(std::io::Cursor::new(&mut buffer)).unwrap();
            encoder.write_node(&current).unwrap();
        }
        buffer
    }

    fn is_max_depth_err(buffer: &[u8]) -> bool {
        matches!(
            Decoder::new(&buffer[1..]).read_node_ref(),
            Err(BinaryError::MaxDepthExceeded)
        )
    }

    /// The deepest accepted nesting (a leaf at depth `MAX_NODE_DEPTH - 1`) decodes.
    /// Pins the exact accept side of the cap so a `>`/`>=` flip is caught.
    #[test]
    fn deeply_nested_at_cap_decodes() -> TestResult {
        let buffer = encode_nested(MAX_NODE_DEPTH - 1);
        let decoded = Decoder::new(&buffer[1..]).read_node_ref()?;
        assert_eq!(decoded.tag, format!("l{}", MAX_NODE_DEPTH - 2).as_str());
        Ok(())
    }

    /// Exactly one level past the accepted range is rejected (pins the reject side).
    #[test]
    fn deeply_nested_one_past_cap_is_rejected() {
        assert!(is_max_depth_err(&encode_nested(MAX_NODE_DEPTH)));
    }

    /// A frame nested far past the cap must return `MaxDepthExceeded`, not overflow
    /// the native stack — this test completing at all is the assertion against abort.
    #[test]
    fn deeply_nested_far_past_cap_is_rejected() {
        assert!(is_max_depth_err(&encode_nested(MAX_NODE_DEPTH * 3)));
    }
}