Skip to main content

wacore_binary/
decoder.rs

1use crate::error::{BinaryError, Result};
2use crate::jid::{JidRef, jid_ref_to_compact};
3use crate::node::{AttrsRef, NodeContentRef, NodeRef, NodeStr, ValueRef};
4use crate::token;
5use compact_str::CompactString;
6use std::borrow::Cow;
7
8/// Each byte's two output characters, so unpacking is one load and one 2-byte
9/// store per input byte instead of two shifts, two lookups and two bounds
10/// checks. Packed values on the wire (a 13-digit phone number, a 20-character
11/// id) are shorter than the SIMD chunk above, so this is the path that runs.
12static HEX_PAIRS: [[u8; 2]; 256] = {
13    const HEX: [u8; 16] = *b"0123456789ABCDEF";
14    let mut table = [[0u8; 2]; 256];
15    let mut i = 0;
16    while i < 256 {
17        table[i] = [HEX[i >> 4], HEX[i & 0x0F]];
18        i += 1;
19    }
20    table
21};
22
23/// Nibble values 12, 13 and 14 encode nothing, so they are marked and the byte
24/// carrying one falls back to the scalar path, which reports which half was
25/// bad. `NIBBLE_INVALID` cannot collide with an output character.
26const NIBBLE_INVALID: u8 = 0xFF;
27static NIBBLE_PAIRS: [[u8; 2]; 256] = {
28    const fn glyph(nibble: usize) -> u8 {
29        match nibble {
30            0..=9 => b'0' + nibble as u8,
31            10 => b'-',
32            11 => b'.',
33            15 => 0,
34            _ => NIBBLE_INVALID,
35        }
36    }
37    let mut table = [[0u8; 2]; 256];
38    let mut i = 0;
39    while i < 256 {
40        table[i] = [glyph(i >> 4), glyph(i & 0x0F)];
41        i += 1;
42    }
43    table
44};
45
46/// Node-nesting cap rejecting deep-`LIST` frames that would overflow the stack via
47/// unbounded `read_node_ref` recursion (real WA trees are well under 20 levels).
48pub(crate) const MAX_NODE_DEPTH: usize = 128;
49
50/// A node's head as [`Decoder::read_node_open`] decodes it, its children left
51/// in the input.
52pub(crate) struct NodeOpen<'a> {
53    pub(crate) tag: NodeStr<'a>,
54    pub(crate) attrs: AttrsRef<'a>,
55    pub(crate) content: OpenContent<'a>,
56}
57
58/// What follows a node's attributes on the wire.
59#[derive(Debug, PartialEq)]
60pub enum OpenContent<'a> {
61    /// Nothing, or an empty list.
62    None,
63    /// A list of this many child nodes, each still to be decoded.
64    Children(usize),
65    /// A string or a byte payload: decoded whole, since it has no parts.
66    Scalar(NodeContentRef<'a>),
67}
68
69pub(crate) struct Decoder<'a> {
70    data: &'a [u8],
71    position: usize,
72}
73
74impl<'a> Decoder<'a> {
75    pub(crate) fn new(data: &'a [u8]) -> Self {
76        Self { data, position: 0 }
77    }
78
79    pub(crate) fn is_finished(&self) -> bool {
80        self.position >= self.data.len()
81    }
82
83    pub(crate) fn bytes_left(&self) -> usize {
84        self.data.len() - self.position
85    }
86
87    #[inline(always)]
88    fn check_eos(&self, len: usize) -> Result<()> {
89        if self.bytes_left() >= len {
90            Ok(())
91        } else {
92            Err(BinaryError::UnexpectedEof)
93        }
94    }
95
96    #[inline(always)]
97    fn read_u8(&mut self) -> Result<u8> {
98        self.check_eos(1)?;
99        let position = self.position;
100        self.position += 1;
101        Ok(self.data[position])
102    }
103
104    #[inline(always)]
105    fn read_u16_be(&mut self) -> Result<u16> {
106        self.check_eos(2)?;
107        let position = self.position;
108        self.position += 2;
109        Ok(u16::from_be_bytes([
110            self.data[position],
111            self.data[position + 1],
112        ]))
113    }
114
115    #[inline(always)]
116    fn read_u20_be(&mut self) -> Result<u32> {
117        self.check_eos(3)?;
118        let position = self.position;
119        self.position += 3;
120        let bytes = [
121            self.data[position],
122            self.data[position + 1],
123            self.data[position + 2],
124        ];
125        Ok(((bytes[0] as u32 & 0x0F) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32))
126    }
127
128    #[inline(always)]
129    fn read_u32_be(&mut self) -> Result<u32> {
130        self.check_eos(4)?;
131        let position = self.position;
132        self.position += 4;
133        Ok(u32::from_be_bytes([
134            self.data[position],
135            self.data[position + 1],
136            self.data[position + 2],
137            self.data[position + 3],
138        ]))
139    }
140
141    #[inline(always)]
142    fn read_bytes(&mut self, len: usize) -> Result<&'a [u8]> {
143        self.check_eos(len)?;
144        let start = self.position;
145        let end = start + len;
146        self.position = end;
147        Ok(&self.data[start..end])
148    }
149
150    #[inline(always)]
151    fn read_string(&mut self, len: usize) -> Result<NodeStr<'a>> {
152        let bytes = self.read_bytes(len)?;
153        // smoothutf8 has a faster fast-path for the short strings dominating the
154        // wire (tags, attribute values, JID parts). It only answers valid/invalid,
155        // so the cold rejection path reuses std to recover the precise Utf8Error.
156        if let Some(s) = smoothutf8::from_utf8(bytes) {
157            Ok(NodeStr::Borrowed(s))
158        } else {
159            match std::str::from_utf8(bytes) {
160                Ok(s) => Ok(NodeStr::Borrowed(s)),
161                Err(e) => Err(BinaryError::InvalidUtf8(e)),
162            }
163        }
164    }
165
166    #[inline(always)]
167    fn read_list_size(&mut self, tag: u8) -> Result<usize> {
168        match tag {
169            token::LIST_EMPTY => Ok(0),
170            token::LIST_8 => self.read_u8().map(|v| v as usize),
171            token::LIST_16 => self.read_u16_be().map(|v| v as usize),
172            _ => Err(BinaryError::InvalidToken(tag)),
173        }
174    }
175
176    fn read_jid_pair(&mut self) -> Result<JidRef<'a>> {
177        let user = self.read_value_as_string()?.unwrap_or_default();
178        let server_str = self.read_value_as_string()?.unwrap_or_default();
179        let server = crate::jid::Server::try_from(server_str.as_ref()).map_err(|_| {
180            BinaryError::AttrParse(format!(
181                "JID_PAIR unknown server ({} bytes)",
182                server_str.len()
183            ))
184        })?;
185        Ok(JidRef {
186            user,
187            server,
188            agent: 0,
189            device: 0,
190            integrator: 0,
191        })
192    }
193
194    fn read_ad_jid(&mut self) -> Result<JidRef<'a>> {
195        let agent = self.read_u8()?;
196        let device = self.read_u8()? as u16;
197        let Some(user) = self.read_value_as_string()? else {
198            return Err(BinaryError::InvalidNode);
199        };
200
201        // Domain type mapping must mirror WA Web decodeJidU.
202        // WA Web: 0=WHATSAPP, 1=LID, even+bit7=HOSTED, 129=HOSTED_LID, else throw.
203        let server = match agent {
204            0 => crate::jid::Server::Pn,
205            1 => crate::jid::Server::Lid,
206            128 => crate::jid::Server::Hosted,
207            129 => crate::jid::Server::HostedLid,
208            n if (n & 128) != 0 && (n & 1) == 0 => crate::jid::Server::Hosted,
209            _ => {
210                return Err(BinaryError::AttrParse(format!(
211                    "read_ad_jid - Invalid domain type encoding {agent}"
212                )));
213            }
214        };
215
216        Ok(JidRef {
217            user,
218            server,
219            // The domain byte is not an agent — it is `server` in wire form, and
220            // `write_jid_*` re-derives it from `server` on the way out. Keeping a
221            // second copy here put a field in the derived `PartialEq`/`Hash` that
222            // only wire-decoded JIDs ever carry, so the same JID compared unequal
223            // depending on whether it came off the wire or out of the store (which
224            // holds JIDs as text, where `Display` suppresses the agent anyway).
225            agent: 0,
226            device,
227            integrator: 0,
228        })
229    }
230
231    fn read_interop_jid(&mut self) -> Result<JidRef<'a>> {
232        let Some(user) = self.read_value_as_string()? else {
233            return Err(BinaryError::InvalidNode);
234        };
235        let device = self.read_u16_be()?;
236        let integrator = self.read_u16_be()?;
237        let server_str = self.read_value_as_string()?.unwrap_or_default();
238        if server_str.as_ref() != crate::jid::INTEROP_SERVER {
239            return Err(BinaryError::InvalidNode);
240        }
241        Ok(JidRef {
242            user,
243            server: crate::jid::Server::Interop,
244            device,
245            integrator,
246            agent: 0,
247        })
248    }
249
250    fn read_fb_jid(&mut self) -> Result<JidRef<'a>> {
251        let Some(user) = self.read_value_as_string()? else {
252            return Err(BinaryError::InvalidNode);
253        };
254        let device = self.read_u16_be()?;
255        let server_str = self.read_value_as_string()?.unwrap_or_default();
256        if server_str.as_ref() != crate::jid::MESSENGER_SERVER {
257            return Err(BinaryError::InvalidNode);
258        }
259        Ok(JidRef {
260            user,
261            server: crate::jid::Server::Messenger,
262            device,
263            agent: 0,
264            integrator: 0,
265        })
266    }
267
268    fn read_value_as_string(&mut self) -> Result<Option<NodeStr<'a>>> {
269        let tag = self.read_u8()?;
270        self.read_value_as_string_from_tag(tag)
271    }
272
273    #[inline(always)]
274    fn read_value_as_string_from_tag(&mut self, tag: u8) -> Result<Option<NodeStr<'a>>> {
275        match tag {
276            token::LIST_EMPTY => Ok(None),
277            token::BINARY_8 => {
278                let size = self.read_u8()? as usize;
279                self.read_string(size).map(Some)
280            }
281            token::BINARY_20 => {
282                let size = self.read_u20_be()? as usize;
283                self.read_string(size).map(Some)
284            }
285            token::BINARY_32 => {
286                let size = self.read_u32_be()? as usize;
287                self.read_string(size).map(Some)
288            }
289            token::JID_PAIR => self
290                .read_jid_pair()
291                .map(|j| Some(NodeStr::Owned(jid_ref_to_compact(&j)))),
292            token::AD_JID => self
293                .read_ad_jid()
294                .map(|j| Some(NodeStr::Owned(jid_ref_to_compact(&j)))),
295            token::INTEROP_JID => self
296                .read_interop_jid()
297                .map(|j| Some(NodeStr::Owned(jid_ref_to_compact(&j)))),
298            token::FB_JID => self
299                .read_fb_jid()
300                .map(|j| Some(NodeStr::Owned(jid_ref_to_compact(&j)))),
301            token::NIBBLE_8 | token::HEX_8 => {
302                self.read_packed(tag).map(|s| Some(NodeStr::Owned(s)))
303            }
304            tag @ token::DICTIONARY_0..=token::DICTIONARY_3 => {
305                let index = self.read_u8()?;
306                match token::get_double_token(tag - token::DICTIONARY_0, index) {
307                    Some(s) => Ok(Some(NodeStr::Borrowed(s))),
308                    None => Err(BinaryError::InvalidToken(tag)),
309                }
310            }
311            _ => match token::get_single_token(tag) {
312                Some(s) => Ok(Some(NodeStr::Borrowed(s))),
313                None => Err(BinaryError::InvalidToken(tag)),
314            },
315        }
316    }
317
318    fn read_value(&mut self) -> Result<Option<ValueRef<'a>>> {
319        let tag = self.read_u8()?;
320        match tag {
321            token::LIST_EMPTY => Ok(None),
322            token::BINARY_8 => {
323                let size = self.read_u8()? as usize;
324                self.read_string(size).map(|s| Some(ValueRef::String(s)))
325            }
326            token::BINARY_20 => {
327                let size = self.read_u20_be()? as usize;
328                self.read_string(size).map(|s| Some(ValueRef::String(s)))
329            }
330            token::BINARY_32 => {
331                let size = self.read_u32_be()? as usize;
332                self.read_string(size).map(|s| Some(ValueRef::String(s)))
333            }
334            token::JID_PAIR => self.read_jid_pair().map(|j| Some(ValueRef::Jid(j))),
335            token::AD_JID => self.read_ad_jid().map(|j| Some(ValueRef::Jid(j))),
336            token::INTEROP_JID => self.read_interop_jid().map(|j| Some(ValueRef::Jid(j))),
337            token::FB_JID => self.read_fb_jid().map(|j| Some(ValueRef::Jid(j))),
338            token::NIBBLE_8 | token::HEX_8 => self
339                .read_packed(tag)
340                .map(|s| Some(ValueRef::String(NodeStr::Owned(s)))),
341            tag @ token::DICTIONARY_0..=token::DICTIONARY_3 => {
342                let index = self.read_u8()?;
343                match token::get_double_token(tag - token::DICTIONARY_0, index) {
344                    Some(s) => Ok(Some(ValueRef::String(NodeStr::Borrowed(s)))),
345                    None => Err(BinaryError::InvalidToken(tag)),
346                }
347            }
348            _ => match token::get_single_token(tag) {
349                Some(s) => Ok(Some(ValueRef::String(NodeStr::Borrowed(s)))),
350                None => Err(BinaryError::InvalidToken(tag)),
351            },
352        }
353    }
354
355    /// Decode packed nibble/hex into a stack buffer, then create CompactString.
356    /// Max unpacked length is 254 bytes (127 packed × 2), so the stack buffer
357    /// is always sufficient. Short values (≤24 bytes) are stored inline.
358    fn read_packed(&mut self, tag: u8) -> Result<CompactString> {
359        let packed_len_byte = self.read_u8()?;
360        let is_half_byte = (packed_len_byte & 0x80) != 0;
361        let len = (packed_len_byte & 0x7F) as usize;
362
363        if len == 0 {
364            return Ok(CompactString::default());
365        }
366
367        let packed_data = self.read_bytes(len)?;
368        // Phone numbers and message IDs usually fit in 24 decoded bytes.
369        if len <= 12 {
370            Self::decode_packed::<24>(tag, packed_data, is_half_byte)
371        } else {
372            Self::decode_packed::<254>(tag, packed_data, is_half_byte)
373        }
374    }
375
376    #[inline(always)]
377    fn decode_packed<const N: usize>(
378        tag: u8,
379        packed_data: &[u8],
380        is_half_byte: bool,
381    ) -> Result<CompactString> {
382        let mut buf = [0u8; N];
383        let mut pos = 0;
384
385        match tag {
386            token::HEX_8 => Self::decode_packed_hex(packed_data, &mut buf, &mut pos),
387            token::NIBBLE_8 => Self::decode_packed_nibble(packed_data, &mut buf, &mut pos)?,
388            _ => return Err(BinaryError::InvalidToken(tag)),
389        }
390
391        if is_half_byte && pos > 0 {
392            pos -= 1;
393        }
394
395        // Unlike `read_string`, which validates bytes that came off the wire,
396        // this validates bytes the tables above just wrote, so it can never
397        // fail. Keeping a check at all is cheap insurance against a future
398        // table edit; smoothutf8 is the same validator the wire path uses.
399        let s = smoothutf8::from_utf8(&buf[..pos]).expect("packed decode produced non-ASCII");
400        Ok(CompactString::from(s))
401    }
402
403    // Deliberately scalar. A vectorised version of this loop lived here until
404    // it was measured against the table: `HEX_PAIRS[byte]` is one 2-byte load
405    // per input byte, and a shuffle/interleave/store sequence does not beat
406    // that. Under callgrind the SIMD path cost 4.5% more instructions on a
407    // 20-character id and 9.7% more on a 32-character one, and enabling real
408    // `pshufb` (`-Ctarget-cpu=x86-64-v2`) only narrowed the loss to 7.0%.
409    // Packed payloads are ids and phone numbers, so the loop also needed a
410    // 31-character string before it engaged at all.
411    #[inline]
412    fn decode_packed_hex(packed_data: &[u8], out: &mut [u8], pos: &mut usize) {
413        let written = packed_data.len() * 2;
414        for (slot, &byte) in out[*pos..*pos + written]
415            .as_chunks_mut::<2>()
416            .0
417            .iter_mut()
418            .zip(packed_data)
419        {
420            slot.copy_from_slice(&HEX_PAIRS[byte as usize]);
421        }
422        *pos += written;
423    }
424
425    // Scalar for the same reason as `decode_packed_hex`, and more so: the
426    // vector version had to validate every lane against the two legal
427    // out-of-range nibbles before it could shuffle, then fall back to this
428    // loop anyway whenever a lane failed.
429    #[inline]
430    fn decode_packed_nibble(packed_data: &[u8], out: &mut [u8], pos: &mut usize) -> Result<()> {
431        let written = packed_data.len() * 2;
432        for (slot, &byte) in out[*pos..*pos + written]
433            .as_chunks_mut::<2>()
434            .0
435            .iter_mut()
436            .zip(packed_data)
437        {
438            let pair = NIBBLE_PAIRS[byte as usize];
439            // Valid glyphs are ASCII. An invalid nibble sets the high bit.
440            if (pair[0] | pair[1]) & 0x80 != 0 {
441                // Report the bad half in the order the byte carries it.
442                Self::unpack_nibble((byte & 0xF0) >> 4)?;
443                Self::unpack_nibble(byte & 0x0F)?;
444            }
445            slot.copy_from_slice(&pair);
446        }
447        *pos += written;
448
449        Ok(())
450    }
451
452    #[inline(always)]
453    fn unpack_nibble(value: u8) -> Result<u8> {
454        match value {
455            0..=9 => Ok(b'0' + value),
456            10 => Ok(b'-'),
457            11 => Ok(b'.'),
458            15 => Ok(0),
459            _ => Err(BinaryError::InvalidToken(value)),
460        }
461    }
462
463    fn read_attributes(&mut self, size: usize) -> Result<AttrsRef<'a>> {
464        if size == 0 {
465            return Ok(AttrsRef::Empty);
466        }
467        let mut v = Vec::with_capacity(size);
468        for _ in 0..size {
469            let Some(key) = self.read_value_as_string()? else {
470                return Err(BinaryError::NonStringKey);
471            };
472            let value = match self.read_value()? {
473                Some(v) => v,
474                None => ValueRef::String(NodeStr::Borrowed("")),
475            };
476            v.push((key, value));
477        }
478        Ok(AttrsRef::from_vec(v))
479    }
480
481    #[inline(always)]
482    fn read_content_from_tag(
483        &mut self,
484        tag: u8,
485        depth: usize,
486    ) -> Result<Option<NodeContentRef<'a>>> {
487        match tag {
488            token::LIST_EMPTY => Ok(None),
489
490            token::LIST_8 | token::LIST_16 => {
491                let size = self.read_list_size(tag)?;
492                let mut nodes = Vec::with_capacity(size);
493                for _ in 0..size {
494                    nodes.push(self.read_node_ref_at(depth + 1)?);
495                }
496                Ok(Some(NodeContentRef::Nodes(nodes.into_boxed_slice())))
497            }
498
499            token::BINARY_8 => {
500                let len = self.read_u8()? as usize;
501                let bytes = self.read_bytes(len)?;
502                Ok(Some(NodeContentRef::Bytes(Cow::Borrowed(bytes))))
503            }
504            token::BINARY_20 => {
505                let len = self.read_u20_be()? as usize;
506                let bytes = self.read_bytes(len)?;
507                Ok(Some(NodeContentRef::Bytes(Cow::Borrowed(bytes))))
508            }
509            token::BINARY_32 => {
510                let len = self.read_u32_be()? as usize;
511                let bytes = self.read_bytes(len)?;
512                Ok(Some(NodeContentRef::Bytes(Cow::Borrowed(bytes))))
513            }
514
515            _ => {
516                let string_content = self.read_value_as_string_from_tag(tag)?;
517
518                match string_content {
519                    Some(s) => Ok(Some(NodeContentRef::String(s))),
520                    None => Ok(None),
521                }
522            }
523        }
524    }
525
526    pub(crate) fn read_node_ref(&mut self) -> Result<NodeRef<'a>> {
527        self.read_node_ref_at(0)
528    }
529
530    /// Bytes consumed so far: what a caller feeding this decoder from a larger
531    /// buffer has to drop once it is done with what was decoded.
532    #[inline]
533    pub(crate) fn position(&self) -> usize {
534        self.position
535    }
536
537    /// Decode a node's head only: tag, attributes and what its content is,
538    /// leaving any child nodes unread for the caller to decode one at a time.
539    /// The counterpart of [`Self::read_node_ref_at`] for a node too large to
540    /// hold as a tree; it reads exactly the bytes that precede the first child.
541    pub(crate) fn read_node_open(&mut self) -> Result<NodeOpen<'a>> {
542        let tag = self.read_u8()?;
543        let list_size = self.read_list_size(tag)?;
544        if list_size == 0 {
545            return Err(BinaryError::InvalidNode);
546        }
547
548        let Some(tag) = self.read_value_as_string()? else {
549            return Err(BinaryError::InvalidNode);
550        };
551
552        let attr_count = (list_size - 1) / 2;
553        let has_content = list_size.is_multiple_of(2);
554
555        let attrs = self.read_attributes(attr_count)?;
556        let content = if has_content {
557            let content_tag = self.read_u8()?;
558            match content_tag {
559                token::LIST_EMPTY => OpenContent::None,
560                token::LIST_8 | token::LIST_16 => {
561                    OpenContent::Children(self.read_list_size(content_tag)?)
562                }
563                // Depth 0 is fine: a scalar never recurses.
564                _ => match self.read_content_from_tag(content_tag, 0)? {
565                    Some(scalar) => OpenContent::Scalar(scalar),
566                    None => OpenContent::None,
567                },
568            }
569        } else {
570            OpenContent::None
571        };
572
573        Ok(NodeOpen {
574            tag,
575            attrs,
576            content,
577        })
578    }
579
580    /// Walk past one value token without building anything: the measuring
581    /// pass of a streaming decode, which has to learn how many bytes a node
582    /// takes before it can decode it from a buffer it may still have to grow.
583    ///
584    /// Mirrors [`Self::read_value`] token for token, validation included: a
585    /// string that is not UTF-8 or a packed nibble outside its alphabet is an
586    /// error here as it is there, so a node the stream skips unread is held
587    /// to what the tree decoder would have rejected. The JID forms reuse the
588    /// readers because their layout is validation, not just length.
589    fn skip_value(&mut self) -> Result<()> {
590        let tag = self.read_u8()?;
591        self.skip_value_from_tag(tag)
592    }
593
594    fn skip_value_from_tag(&mut self, tag: u8) -> Result<()> {
595        match tag {
596            token::LIST_EMPTY => Ok(()),
597            token::BINARY_8 => {
598                let size = self.read_u8()? as usize;
599                self.read_string(size).map(drop)
600            }
601            token::BINARY_20 => {
602                let size = self.read_u20_be()? as usize;
603                self.read_string(size).map(drop)
604            }
605            token::BINARY_32 => {
606                let size = self.read_u32_be()? as usize;
607                self.read_string(size).map(drop)
608            }
609            token::JID_PAIR => self.read_jid_pair().map(drop),
610            token::AD_JID => self.read_ad_jid().map(drop),
611            token::INTEROP_JID => self.read_interop_jid().map(drop),
612            token::FB_JID => self.read_fb_jid().map(drop),
613            token::NIBBLE_8 | token::HEX_8 => {
614                let len = (self.read_u8()? & 0x7F) as usize;
615                let packed = self.read_bytes(len)?;
616                // Every byte is a valid hex pair; only nibbles have holes.
617                if tag == token::NIBBLE_8
618                    && let Some(&byte) = packed.iter().find(|&&byte| {
619                        let pair = NIBBLE_PAIRS[byte as usize];
620                        pair[0] == NIBBLE_INVALID || pair[1] == NIBBLE_INVALID
621                    })
622                {
623                    Self::unpack_nibble((byte & 0xF0) >> 4)?;
624                    Self::unpack_nibble(byte & 0x0F)?;
625                }
626                Ok(())
627            }
628            tag @ token::DICTIONARY_0..=token::DICTIONARY_3 => {
629                let index = self.read_u8()?;
630                token::get_double_token(tag - token::DICTIONARY_0, index)
631                    .map(drop)
632                    .ok_or(BinaryError::InvalidToken(tag))
633            }
634            _ => token::get_single_token(tag)
635                .map(drop)
636                .ok_or(BinaryError::InvalidToken(tag)),
637        }
638    }
639
640    /// Walk past a node's scalar content, whose tag has been read. Binary
641    /// content is opaque to [`Self::read_content_from_tag`] too, so only its
642    /// length is checked; anything else is a string value and validated as one.
643    fn skip_scalar_content(&mut self, tag: u8) -> Result<()> {
644        match tag {
645            token::BINARY_8 => {
646                let len = self.read_u8()? as usize;
647                self.read_bytes(len).map(drop)
648            }
649            token::BINARY_20 => {
650                let len = self.read_u20_be()? as usize;
651                self.read_bytes(len).map(drop)
652            }
653            token::BINARY_32 => {
654                let len = self.read_u32_be()? as usize;
655                self.read_bytes(len).map(drop)
656            }
657            _ => self.skip_value_from_tag(tag),
658        }
659    }
660
661    /// Walk past a node's head (through the child count, when it has one) and
662    /// report how many children were announced. The measuring twin of
663    /// [`Self::read_node_open`].
664    pub(crate) fn skip_node_open(&mut self) -> Result<usize> {
665        let tag = self.read_u8()?;
666        let list_size = self.read_list_size(tag)?;
667        if list_size == 0 {
668            return Err(BinaryError::InvalidNode);
669        }
670        // The same two shapes `read_node_open` refuses: a node with no tag,
671        // and an attribute whose key is not a string.
672        let tag_token = self.read_u8()?;
673        if tag_token == token::LIST_EMPTY {
674            return Err(BinaryError::InvalidNode);
675        }
676        self.skip_value_from_tag(tag_token)?;
677        let attr_count = (list_size - 1) / 2;
678        for _ in 0..attr_count {
679            let key_token = self.read_u8()?;
680            if key_token == token::LIST_EMPTY {
681                return Err(BinaryError::NonStringKey);
682            }
683            self.skip_value_from_tag(key_token)?;
684            self.skip_value()?;
685        }
686        if !list_size.is_multiple_of(2) {
687            return Ok(0);
688        }
689        let content_tag = self.read_u8()?;
690        match content_tag {
691            token::LIST_EMPTY => Ok(0),
692            token::LIST_8 | token::LIST_16 => self.read_list_size(content_tag),
693            _ => {
694                self.skip_scalar_content(content_tag)?;
695                Ok(0)
696            }
697        }
698    }
699
700    /// Walk past a whole node, subtree included. The measuring twin of
701    /// [`Self::read_node_ref_at`], with the same depth cap.
702    pub(crate) fn skip_node_at(&mut self, depth: usize) -> Result<()> {
703        if depth >= MAX_NODE_DEPTH {
704            return Err(BinaryError::MaxDepthExceeded);
705        }
706        let children = self.skip_node_open()?;
707        for _ in 0..children {
708            self.skip_node_at(depth + 1)?;
709        }
710        Ok(())
711    }
712
713    pub(crate) fn read_node_ref_at(&mut self, depth: usize) -> Result<NodeRef<'a>> {
714        // Reject before recursing, so a hostile deep-LIST frame errors instead of
715        // aborting the process on a stack overflow.
716        if depth >= MAX_NODE_DEPTH {
717            return Err(BinaryError::MaxDepthExceeded);
718        }
719        // One head reader for both decoders: the tree is the head plus its
720        // children read whole, which is also what keeps the two in agreement
721        // on what a malformed head is.
722        let head = self.read_node_open()?;
723        let content = match head.content {
724            OpenContent::None => None,
725            OpenContent::Scalar(scalar) => Some(scalar),
726            OpenContent::Children(count) => {
727                let mut nodes = Vec::with_capacity(count);
728                for _ in 0..count {
729                    nodes.push(self.read_node_ref_at(depth + 1)?);
730                }
731                Some(NodeContentRef::Nodes(nodes.into_boxed_slice()))
732            }
733        };
734
735        Ok(NodeRef {
736            tag: head.tag,
737            attrs: head.attrs,
738            content,
739        })
740    }
741}
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746    use crate::node::{Attrs, Node};
747
748    type TestResult = Result<()>;
749
750    #[test]
751    fn test_decode_node() -> TestResult {
752        let node = Node::new(
753            "message",
754            Attrs::new(),
755            Some(crate::node::NodeContent::String("receipt".into())),
756        );
757
758        let mut buffer = Vec::new();
759        {
760            let mut encoder = crate::encoder::Encoder::new(std::io::Cursor::new(&mut buffer))?;
761            encoder.write_node(&node)?;
762        }
763
764        let mut decoder = Decoder::new(&buffer[1..]);
765        let decoded = decoder.read_node_ref().unwrap();
766
767        assert_eq!(decoded.tag, "message");
768        assert!(decoded.attrs.is_empty());
769        match &decoded.content {
770            Some(content) => match content {
771                NodeContentRef::String(s) => assert_eq!(s, "receipt"),
772                _ => panic!("Expected string content"),
773            },
774            None => panic!("Expected content"),
775        }
776        Ok(())
777    }
778
779    #[test]
780    fn test_decode_nibble_packing() -> TestResult {
781        let test_str = "-.0123456789";
782        let node = Node::new(
783            "test",
784            Attrs::new(),
785            Some(crate::node::NodeContent::String(test_str.into())),
786        );
787
788        let mut buffer = Vec::new();
789        {
790            let mut encoder = crate::encoder::Encoder::new(std::io::Cursor::new(&mut buffer))?;
791            encoder.write_node(&node)?;
792        }
793
794        let mut decoder = Decoder::new(&buffer[1..]);
795        let decoded = decoder.read_node_ref().unwrap();
796
797        assert_eq!(decoded.tag, "test");
798        assert!(decoded.attrs.is_empty());
799        match &decoded.content {
800            Some(content) => match content {
801                NodeContentRef::String(s) => assert_eq!(s, test_str),
802                _ => panic!("Expected string content"),
803            },
804            None => panic!("Expected content"),
805        }
806        Ok(())
807    }
808
809    #[test]
810    fn test_invalid_nibble_rejection() {
811        let invalid_data = vec![1, 0xC0];
812
813        let mut decoder = Decoder::new(&invalid_data);
814        let result = decoder.read_packed(token::NIBBLE_8);
815        assert!(
816            result.is_err(),
817            "Expected error for invalid nibble 12, got: {:?}",
818            result
819        );
820
821        if let Err(BinaryError::InvalidToken(invalid_nibble)) = result {
822            assert_eq!(invalid_nibble, 12, "Expected invalid nibble 12");
823        } else {
824            panic!("Expected InvalidToken error, got: {:?}", result);
825        }
826    }
827
828    /// Test empty input returns appropriate error
829    #[test]
830    fn test_empty_input() {
831        let mut decoder = Decoder::new(&[]);
832        let result = decoder.read_node_ref();
833        assert!(result.is_err());
834    }
835
836    /// Test truncated u16 read
837    #[test]
838    fn test_truncated_u16() {
839        // Only one byte when u16 expected
840        let data = vec![0x42];
841        let mut decoder = Decoder::new(&data);
842        let result = decoder.read_u16_be();
843        assert!(result.is_err());
844        if let Err(BinaryError::UnexpectedEof) = result {
845            // Expected
846        } else {
847            panic!("Expected UnexpectedEof, got: {:?}", result);
848        }
849    }
850
851    /// Test truncated u20 read
852    #[test]
853    fn test_truncated_u20() {
854        // Only two bytes when u20 (3 bytes) expected
855        let data = vec![0x42, 0x43];
856        let mut decoder = Decoder::new(&data);
857        let result = decoder.read_u20_be();
858        assert!(result.is_err());
859    }
860
861    /// Test truncated u32 read
862    #[test]
863    fn test_truncated_u32() {
864        // Only three bytes when u32 expected
865        let data = vec![0x42, 0x43, 0x44];
866        let mut decoder = Decoder::new(&data);
867        let result = decoder.read_u32_be();
868        assert!(result.is_err());
869    }
870
871    /// Test BINARY_8 with length larger than remaining buffer
872    #[test]
873    fn test_binary8_length_exceeds_buffer() {
874        // BINARY_8 token, length 100, but only 5 bytes of data
875        let data = vec![token::BINARY_8, 100, 1, 2, 3, 4, 5];
876        let mut decoder = Decoder::new(&data);
877        let result = decoder.read_value_as_string();
878        assert!(result.is_err());
879    }
880
881    /// Test BINARY_20 with length larger than remaining buffer
882    #[test]
883    fn test_binary20_length_exceeds_buffer() {
884        // BINARY_20 token, length encoded as 256, but only a few bytes of data
885        let data = vec![token::BINARY_20, 0x00, 0x01, 0x00, 1, 2, 3]; // length = 256
886        let mut decoder = Decoder::new(&data);
887        let result = decoder.read_value_as_string();
888        assert!(result.is_err());
889    }
890
891    /// Test LIST_8 with size larger than remaining data
892    #[test]
893    fn test_list8_size_exceeds_data() {
894        // LIST_8 token, size 10, but not enough data for 10 nodes
895        let data = vec![token::LIST_8, 10, 1]; // Only 1 byte of data for nodes
896        let mut decoder = Decoder::new(&data);
897        let result = decoder.read_node_ref();
898        assert!(result.is_err());
899    }
900
901    /// Attribute storage capacity must not change how a broken attribute list
902    /// is rejected: a truncated pair, a non-string key and a declared count the
903    /// frame cannot back all fail the same way they did before.
904    #[test]
905    fn malformed_attribute_lists_keep_their_errors() {
906        // <message> claiming one attribute, cut off after the key.
907        let truncated = [
908            token::LIST_8,
909            3,
910            token::DICTIONARY_0,
911            0,
912            token::BINARY_8,
913            2,
914            b'i',
915            b'd',
916        ];
917        assert!(matches!(
918            Decoder::new(&truncated).read_node_ref(),
919            Err(BinaryError::UnexpectedEof)
920        ));
921
922        // An empty list where a string key is required.
923        let non_string_key = [token::LIST_8, 3, token::DICTIONARY_0, 0, token::LIST_EMPTY];
924        assert!(matches!(
925            Decoder::new(&non_string_key).read_node_ref(),
926            Err(BinaryError::NonStringKey)
927        ));
928
929        // Declares 4 attributes, carries none.
930        let overlong_count = [token::LIST_8, 9, token::DICTIONARY_0, 0];
931        assert!(matches!(
932            Decoder::new(&overlong_count).read_node_ref(),
933            Err(BinaryError::UnexpectedEof)
934        ));
935
936        // A list size of zero has no room even for the tag.
937        assert!(matches!(
938            Decoder::new(&[token::LIST_EMPTY]).read_node_ref(),
939            Err(BinaryError::InvalidNode)
940        ));
941    }
942
943    /// Test invalid token value
944    #[test]
945    fn test_invalid_token() {
946        // Use a token value that's reserved and not valid as a string token
947        // e.g., AD_JID (247) followed by insufficient data
948        let data = vec![token::AD_JID]; // No data following
949        let mut decoder = Decoder::new(&data);
950        let result = decoder.read_value_as_string();
951        assert!(result.is_err());
952    }
953
954    #[test]
955    fn test_ad_jid_rejects_invalid_domain_type() {
956        let data = vec![token::AD_JID, 2, 1, token::BINARY_8, 3, b'1', b'2', b'3'];
957        let mut decoder = Decoder::new(&data);
958        let result = decoder.read_value_as_string();
959
960        match result {
961            Err(BinaryError::AttrParse(msg)) => {
962                assert!(
963                    msg.contains("Invalid domain type encoding 2"),
964                    "unexpected error message: {msg}"
965                );
966            }
967            other => panic!("expected AttrParse for invalid AD_JID domain type, got {other:?}"),
968        }
969    }
970
971    /// Test read_bytes with exact length
972    #[test]
973    fn test_read_bytes_exact_length() {
974        let data = vec![1, 2, 3, 4, 5];
975        let mut decoder = Decoder::new(&data);
976        let bytes = decoder.read_bytes(5).unwrap();
977        assert_eq!(bytes, &[1, 2, 3, 4, 5]);
978        assert!(decoder.is_finished());
979    }
980
981    /// Test read_bytes exceeding length
982    #[test]
983    fn test_read_bytes_exceeding_length() {
984        let data = vec![1, 2, 3];
985        let mut decoder = Decoder::new(&data);
986        let result = decoder.read_bytes(5);
987        assert!(result.is_err());
988    }
989
990    /// Test u20 encoding/decoding values
991    #[test]
992    fn test_u20_encoding() {
993        // Test value 0
994        let data = vec![0x00, 0x00, 0x00];
995        let mut decoder = Decoder::new(&data);
996        assert_eq!(decoder.read_u20_be().unwrap(), 0);
997
998        // Test value 256 (0x100)
999        let data = vec![0x00, 0x01, 0x00];
1000        let mut decoder = Decoder::new(&data);
1001        assert_eq!(decoder.read_u20_be().unwrap(), 256);
1002
1003        // Test value 65536 (0x10000)
1004        let data = vec![0x01, 0x00, 0x00];
1005        let mut decoder = Decoder::new(&data);
1006        assert_eq!(decoder.read_u20_be().unwrap(), 65536);
1007
1008        // Test max u20 value (0xFFFFF = 1048575)
1009        let data = vec![0x0F, 0xFF, 0xFF];
1010        let mut decoder = Decoder::new(&data);
1011        assert_eq!(decoder.read_u20_be().unwrap(), 1048575);
1012    }
1013
1014    /// Test bytes_left tracking
1015    #[test]
1016    fn test_bytes_left() {
1017        let data = vec![1, 2, 3, 4, 5];
1018        let mut decoder = Decoder::new(&data);
1019
1020        assert_eq!(decoder.bytes_left(), 5);
1021        decoder.read_u8().unwrap();
1022        assert_eq!(decoder.bytes_left(), 4);
1023        decoder.read_u8().unwrap();
1024        assert_eq!(decoder.bytes_left(), 3);
1025        decoder.read_bytes(3).unwrap();
1026        assert_eq!(decoder.bytes_left(), 0);
1027        assert!(decoder.is_finished());
1028    }
1029
1030    /// Test hex packed string decoding
1031    #[test]
1032    fn test_hex_packed_decoding() {
1033        // Encode "ABCDEF" as hex packed
1034        // Each byte packs two hex digits
1035        // A=10, B=11, C=12, D=13, E=14, F=15
1036        let packed_data = vec![
1037            3,    // length = 3 bytes = 6 characters
1038            0xAB, // AB
1039            0xCD, // CD
1040            0xEF, // EF
1041        ];
1042
1043        let mut decoder = Decoder::new(&packed_data);
1044        let result = decoder.read_packed(token::HEX_8).unwrap();
1045        assert_eq!(result, "ABCDEF");
1046    }
1047
1048    /// Test nibble packed string with odd length
1049    #[test]
1050    fn packed_scratch_handles_short_long_and_odd_values() {
1051        for length in [11, 12, 13, 127] {
1052            for odd in [false, true] {
1053                let mut wire = vec![0x23; length + 1];
1054                wire[0] = length as u8 | if odd { 0x80 } else { 0 };
1055                let expected = "23".repeat(length);
1056                let expected = &expected[..expected.len() - usize::from(odd)];
1057                for tag in [token::HEX_8, token::NIBBLE_8] {
1058                    let mut decoder = Decoder::new(&wire);
1059                    assert_eq!(decoder.read_packed(tag).unwrap(), expected);
1060                    assert!(decoder.is_finished());
1061                }
1062                wire[1] = 0xcd;
1063                assert!(matches!(
1064                    Decoder::new(&wire).read_packed(token::NIBBLE_8),
1065                    Err(BinaryError::InvalidToken(12))
1066                ));
1067                wire[1] = 0x3e;
1068                assert!(matches!(
1069                    Decoder::new(&wire).read_packed(token::NIBBLE_8),
1070                    Err(BinaryError::InvalidToken(14))
1071                ));
1072            }
1073        }
1074    }
1075
1076    #[test]
1077    fn test_nibble_packed_odd_length() {
1078        // Encode "123" as nibble packed (odd length = 3)
1079        // 1=1, 2=2, 3=3, pad=15
1080        let packed_data = vec![
1081            0x82, // length = 2 bytes, high bit set for odd
1082            0x12, // 12
1083            0x3F, // 3 + pad (15)
1084        ];
1085
1086        let mut decoder = Decoder::new(&packed_data);
1087        let result = decoder.read_packed(token::NIBBLE_8).unwrap();
1088        assert_eq!(result, "123");
1089    }
1090
1091    /// Test empty packed string
1092    #[test]
1093    fn test_empty_packed_string() {
1094        let packed_data = vec![0]; // length = 0
1095
1096        let mut decoder = Decoder::new(&packed_data);
1097        let result = decoder.read_packed(token::NIBBLE_8).unwrap();
1098        assert_eq!(result, "");
1099    }
1100
1101    /// Test invalid nibble value 12 (only 0-11, 15 are valid)
1102    #[test]
1103    fn test_invalid_nibble_value_12() {
1104        // 12 (0xC) is not a valid nibble
1105        let packed_data = vec![1, 0xC0]; // first nibble is 12
1106
1107        let mut decoder = Decoder::new(&packed_data);
1108        let result = decoder.read_packed(token::NIBBLE_8);
1109        assert!(result.is_err());
1110    }
1111
1112    /// Test invalid nibble value 13
1113    #[test]
1114    fn test_invalid_nibble_value_13() {
1115        let packed_data = vec![1, 0xD0]; // first nibble is 13
1116
1117        let mut decoder = Decoder::new(&packed_data);
1118        let result = decoder.read_packed(token::NIBBLE_8);
1119        assert!(result.is_err());
1120    }
1121
1122    /// Test invalid nibble value 14
1123    #[test]
1124    fn test_invalid_nibble_value_14() {
1125        let packed_data = vec![1, 0xE0]; // first nibble is 14
1126
1127        let mut decoder = Decoder::new(&packed_data);
1128        let result = decoder.read_packed(token::NIBBLE_8);
1129        assert!(result.is_err());
1130    }
1131
1132    /// Test deeply nested nodes (recursion safety)
1133    #[test]
1134    fn test_nested_nodes() -> TestResult {
1135        // Create a 50-level deep node structure
1136        let mut current = Node::new("leaf", Attrs::new(), None);
1137
1138        for i in 0..50 {
1139            let tag = format!("level{}", i);
1140            current = Node::new(
1141                tag,
1142                Attrs::new(),
1143                Some(crate::node::NodeContent::Nodes(vec![current])),
1144            );
1145        }
1146
1147        let mut buffer = Vec::new();
1148        {
1149            let mut encoder = crate::encoder::Encoder::new(std::io::Cursor::new(&mut buffer))?;
1150            encoder.write_node(&current)?;
1151        }
1152
1153        let mut decoder = Decoder::new(&buffer[1..]);
1154        let decoded = decoder.read_node_ref()?;
1155
1156        // Verify top level tag
1157        assert_eq!(decoded.tag, "level49");
1158        Ok(())
1159    }
1160
1161    fn encode_nested(levels: usize) -> Vec<u8> {
1162        let mut current = Node::new("leaf", Attrs::new(), None);
1163        for i in 0..levels {
1164            current = Node::new(
1165                format!("l{i}"),
1166                Attrs::new(),
1167                Some(crate::node::NodeContent::Nodes(vec![current])),
1168            );
1169        }
1170        let mut buffer = Vec::new();
1171        {
1172            let mut encoder =
1173                crate::encoder::Encoder::new(std::io::Cursor::new(&mut buffer)).unwrap();
1174            encoder.write_node(&current).unwrap();
1175        }
1176        buffer
1177    }
1178
1179    fn is_max_depth_err(buffer: &[u8]) -> bool {
1180        matches!(
1181            Decoder::new(&buffer[1..]).read_node_ref(),
1182            Err(BinaryError::MaxDepthExceeded)
1183        )
1184    }
1185
1186    /// The deepest accepted nesting (a leaf at depth `MAX_NODE_DEPTH - 1`) decodes.
1187    /// Pins the exact accept side of the cap so a `>`/`>=` flip is caught.
1188    #[test]
1189    fn deeply_nested_at_cap_decodes() -> TestResult {
1190        let buffer = encode_nested(MAX_NODE_DEPTH - 1);
1191        let decoded = Decoder::new(&buffer[1..]).read_node_ref()?;
1192        assert_eq!(decoded.tag, format!("l{}", MAX_NODE_DEPTH - 2).as_str());
1193        Ok(())
1194    }
1195
1196    /// Exactly one level past the accepted range is rejected (pins the reject side).
1197    #[test]
1198    fn deeply_nested_one_past_cap_is_rejected() {
1199        assert!(is_max_depth_err(&encode_nested(MAX_NODE_DEPTH)));
1200    }
1201
1202    /// A frame nested far past the cap must return `MaxDepthExceeded`, not overflow
1203    /// the native stack — this test completing at all is the assertion against abort.
1204    #[test]
1205    fn deeply_nested_far_past_cap_is_rejected() {
1206        assert!(is_max_depth_err(&encode_nested(MAX_NODE_DEPTH * 3)));
1207    }
1208}