Skip to main content

wacore_binary/
stream.rs

1//! Incremental decoding of one node: a cursor that walks a node's children one
2//! at a time instead of building the whole tree.
3//!
4//! The tree decoder ([`unmarshal_ref`](crate::marshal::unmarshal_ref), [`OwnedNodeRef`]) needs every
5//! decompressed byte of a node in memory at once and one heap object per node
6//! and attribute list. For a stanza of a few thousand small children that is
7//! more memory than the payload by an order of magnitude, and on a
8//! microcontroller it is more memory than there is. A [`NodeStream`] decodes the
9//! same wire format from a source that produces bytes on demand, so a caller
10//! that wants a handful of children out of thousands keeps one child, and one
11//! inflate window, alive at a time.
12//!
13//! The cursor moves through a node the way the bytes are laid out: [`open`]
14//! reads the head of the next node (tag, attributes, what its content is) and
15//! descends into it; [`next_child`] decodes the next child whole; [`close`]
16//! leaves the open node, skipping any children not yet read. What comes back
17//! borrows the stream's buffer and is valid until the next call.
18//!
19//! [`open`]: NodeStream::open
20//! [`next_child`]: NodeStream::next_child
21//! [`close`]: NodeStream::close
22//! [`OwnedNodeRef`]: crate::OwnedNodeRef
23
24use std::io;
25
26use crate::decoder::{Decoder, MAX_NODE_DEPTH, OpenContent};
27use crate::error::{BinaryError, Result};
28use crate::node::{AttrsRef, NodeRef, NodeStr, ValueRef};
29use crate::util::{FORMAT_COMPRESSED, MAX_DECOMPRESSED_SIZE};
30use crate::zlib_pool::InflateReader;
31
32/// Inflate window for a compressed frame decoded through a stream.
33///
34/// The window is the stream's whole footprint beyond the pooled zlib state and
35/// the child being decoded, so it is sized for the smallest target rather than
36/// for throughput: a 4 KB window holds any run of the sub-100-byte children a
37/// props response is made of, and a child larger than it grows the window to
38/// fit. On a host the cost is one inflate call per 4 KB of output instead of
39/// one per payload, a few microseconds on a 100 KB frame.
40const FRAME_INFLATE_CHUNK: usize = 4096;
41
42/// Where a stream's bytes come from.
43enum Source<'a> {
44    /// Node bytes already in memory.
45    Plain { data: &'a [u8], pos: usize },
46    /// Node bytes inflated from a compressed payload as they are needed.
47    Inflate(InflateReader<'a>),
48}
49
50impl Source<'_> {
51    #[inline]
52    fn available(&self) -> &[u8] {
53        match self {
54            Self::Plain { data, pos } => &data[*pos..],
55            Self::Inflate(reader) => reader.available(),
56        }
57    }
58
59    #[inline]
60    fn consume(&mut self, n: usize) {
61        match self {
62            Self::Plain { data, pos } => *pos = (*pos + n).min(data.len()),
63            Self::Inflate(reader) => reader.consume(n),
64        }
65    }
66
67    /// Make at least `need` bytes available, or every byte there is.
68    fn ensure(&mut self, need: usize) -> Result<bool> {
69        match self {
70            Self::Plain { data, pos } => Ok(data.len() - *pos >= need),
71            Self::Inflate(reader) => reader.ensure(need).map_err(zlib_error),
72        }
73    }
74}
75
76fn zlib_error(e: io::Error) -> BinaryError {
77    BinaryError::Zlib(e.to_string())
78}
79
80/// The head of a node the stream has descended into.
81///
82/// Borrows the stream's buffer, so it lives until the stream's next call;
83/// anything kept longer is copied out.
84#[derive(Debug)]
85pub struct OpenNode<'b> {
86    pub tag: NodeStr<'b>,
87    pub attrs: AttrsRef<'b>,
88    pub content: OpenContent<'b>,
89}
90
91impl<'b> OpenNode<'b> {
92    /// Look up a single attribute by key.
93    pub fn get_attr(&self, key: &str) -> Option<&ValueRef<'b>> {
94        self.attrs.iter().find(|(k, _)| k == key).map(|(_, v)| v)
95    }
96
97    /// An attribute as text, whatever its wire form.
98    pub fn attr_str(&self, key: &str) -> Option<std::borrow::Cow<'_, str>> {
99        self.get_attr(key).map(|v| v.as_str())
100    }
101
102    /// How many children the node has still to offer, when its content is a
103    /// list of nodes.
104    pub fn child_count(&self) -> usize {
105        match self.content {
106            OpenContent::Children(n) => n,
107            _ => 0,
108        }
109    }
110}
111
112/// One node the cursor has descended into: how many of its children are still
113/// unread.
114struct Level {
115    remaining: usize,
116}
117
118/// A cursor over one node's wire bytes; see the [module docs](self).
119pub struct NodeStream<'a> {
120    source: Source<'a>,
121    /// Bytes decoded by the last `open`/`next_child`, still backing what that
122    /// call returned. Consumed at the start of the next call.
123    pending: usize,
124    /// Every byte consumed so far. A materialization needs all of them, so it
125    /// is only offered while this is still zero.
126    consumed: usize,
127    levels: Vec<Level>,
128    /// The root has been opened (or skipped): there is no node left at depth 0.
129    root_done: bool,
130}
131
132impl<'a> NodeStream<'a> {
133    /// A stream over a packed payload: the format byte and, behind it, node
134    /// bytes that are inflated on demand when the byte says they are compressed.
135    ///
136    /// This is what the receive path holds after decryption. A compressed
137    /// payload checks out the thread's pooled inflate state for the life of the
138    /// stream.
139    pub fn from_packed(packed: &'a [u8]) -> Result<Self> {
140        let Some((&format, node_bytes)) = packed.split_first() else {
141            return Err(BinaryError::EmptyData);
142        };
143        if format & FORMAT_COMPRESSED != 0 {
144            Ok(Self::with_source(Source::Inflate(
145                InflateReader::with_chunk(node_bytes, MAX_DECOMPRESSED_SIZE, FRAME_INFLATE_CHUNK),
146            )))
147        } else {
148            Ok(Self::from_node_bytes(node_bytes))
149        }
150    }
151
152    /// A stream over node bytes already in memory (no format byte): the
153    /// buffer behind an [`OwnedNodeRef`](crate::OwnedNodeRef), for a consumer
154    /// that walks a node it was handed whole.
155    pub fn from_node_bytes(node_bytes: &'a [u8]) -> Self {
156        Self::with_source(Source::Plain {
157            data: node_bytes,
158            pos: 0,
159        })
160    }
161
162    fn with_source(source: Source<'a>) -> Self {
163        Self {
164            source,
165            pending: 0,
166            consumed: 0,
167            levels: Vec::new(),
168            root_done: false,
169        }
170    }
171
172    /// Whether the bytes are being inflated as they are read.
173    pub fn is_compressed(&self) -> bool {
174        matches!(self.source, Source::Inflate(_))
175    }
176
177    /// How deep the cursor is: 0 before the root is opened, 1 inside it.
178    pub fn depth(&self) -> usize {
179        self.levels.len()
180    }
181
182    /// Decode the head of the next node and descend into it.
183    ///
184    /// At depth 0 that is the root; inside an open node it is that node's next
185    /// child, which then becomes the open node. `None` when the open node has
186    /// no children left (or, at depth 0, once the root has been read).
187    pub fn open(&mut self) -> Result<Option<OpenNode<'_>>> {
188        if !self.take_slot() {
189            return Ok(None);
190        }
191        if self.levels.len() >= MAX_NODE_DEPTH {
192            return Err(BinaryError::MaxDepthExceeded);
193        }
194        let Self {
195            source,
196            pending,
197            levels,
198            ..
199        } = self;
200        let (head, used) = Self::decode_next(source, |decoder| decoder.read_node_open())?;
201        *pending = used;
202        levels.push(Level {
203            remaining: match head.content {
204                OpenContent::Children(n) => n,
205                _ => 0,
206            },
207        });
208        Ok(Some(OpenNode {
209            tag: head.tag,
210            attrs: head.attrs,
211            content: head.content,
212        }))
213    }
214
215    /// Decode the open node's next child whole, subtree and all.
216    ///
217    /// `None` once the open node has no children left, or at depth 0 once the
218    /// root has been read.
219    pub fn next_child(&mut self) -> Result<Option<NodeRef<'_>>> {
220        if !self.take_slot() {
221            return Ok(None);
222        }
223        let depth = self.levels.len();
224        let Self {
225            source, pending, ..
226        } = self;
227        let (node, used) = Self::decode_next(source, |decoder| decoder.read_node_ref_at(depth))?;
228        *pending = used;
229        Ok(Some(node))
230    }
231
232    /// Leave the open node, decoding and discarding any children not yet read,
233    /// so the cursor stands at the parent's next child.
234    pub fn close(&mut self) -> Result<()> {
235        self.settle();
236        let Some(level) = self.levels.last() else {
237            return Ok(());
238        };
239        let mut remaining = level.remaining;
240        while remaining > 0 {
241            // Skipping still walks every byte: the wire carries no lengths, so
242            // a child's end is only known once its tokens have been read.
243            let depth = self.levels.len();
244            let used = Self::skip_next(&mut self.source, |decoder| decoder.skip_node_at(depth))?;
245            self.source.consume(used);
246            self.consumed += used;
247            remaining -= 1;
248        }
249        self.levels.pop();
250        Ok(())
251    }
252
253    /// Consume everything after the cursor and check that the bytes end where
254    /// the node does: nothing left over behind the root, and for a compressed
255    /// payload a properly terminated stream (the checksum in the trailer is
256    /// what says every inflated byte was the one the peer sent).
257    ///
258    /// The strictness [`unmarshal_ref`](crate::marshal::unmarshal_ref) applies to a tree
259    /// (it rejects leftover data), applied to a stream that was only partly
260    /// read. Only worth calling once what was wanted has been read: a stream
261    /// abandoned on a parse error is simply dropped.
262    pub fn finish(&mut self) -> Result<()> {
263        while !self.levels.is_empty() {
264            self.close()?;
265        }
266        if !self.root_done {
267            // Nothing was ever read; the root still has to be walked.
268            self.root_done = true;
269            let used = Self::skip_next(&mut self.source, |decoder| decoder.skip_node_at(0))?;
270            self.source.consume(used);
271            self.consumed += used;
272        }
273        self.settle();
274        match &mut self.source {
275            Source::Plain { data, pos } => {
276                if *pos < data.len() {
277                    return Err(BinaryError::LeftoverData(data.len() - *pos));
278                }
279            }
280            Source::Inflate(reader) => {
281                // Pull the trailer through: a stream that ends exactly on the
282                // root's last byte has its adler32 still unread.
283                if reader.ensure(1).map_err(zlib_error)? {
284                    return Err(BinaryError::LeftoverData(reader.available().len()));
285                }
286                if !reader.stream_ended() {
287                    return Err(BinaryError::Zlib("zlib stream truncated".into()));
288                }
289            }
290        }
291        Ok(())
292    }
293
294    /// The whole node as one buffer, the way [`unpack`](crate::util::unpack)
295    /// would have produced it, for a caller that looked at the root's head and
296    /// decided the node is one to hold as a tree after all.
297    ///
298    /// Only for a compressed payload, and only before anything was consumed
299    /// (an [`open`](Self::open) of the root consumes nothing until the next
300    /// call): the bytes of a plain payload are the caller's own, and a
301    /// consumed prefix is gone. Both return `None`.
302    pub fn into_inflated(self) -> Option<Result<Vec<u8>>> {
303        if self.consumed != 0 {
304            return None;
305        }
306        match self.source {
307            Source::Plain { .. } => None,
308            Source::Inflate(reader) => Some(reader.read_to_end().map_err(zlib_error)),
309        }
310    }
311
312    /// Drop the bytes behind what the last call returned.
313    fn settle(&mut self) {
314        if self.pending != 0 {
315            self.source.consume(self.pending);
316            self.consumed += self.pending;
317            self.pending = 0;
318        }
319    }
320
321    /// Claim the next node at the cursor: a child of the open node, or the
322    /// root. False when there is none.
323    fn take_slot(&mut self) -> bool {
324        self.settle();
325        match self.levels.last_mut() {
326            Some(level) => {
327                if level.remaining == 0 {
328                    return false;
329                }
330                level.remaining -= 1;
331                true
332            }
333            None => {
334                if self.root_done {
335                    return false;
336                }
337                self.root_done = true;
338                true
339            }
340        }
341    }
342
343    /// Decode the next node out of the window, growing the window and decoding
344    /// again when it ends mid-node. Returns what `decode` produced and how
345    /// many bytes it took.
346    ///
347    /// The wire carries no lengths, so whether the window holds the whole node
348    /// is only known once the node has been read. Decoding straight from the
349    /// window and retrying on a short read costs one wasted attempt per window
350    /// boundary the node straddles, a few per frame; walking the node first to
351    /// size it (what [`Self::skip_next`] does) would cost a second pass over
352    /// every node, a quarter of the decode. Each retry asks for double the
353    /// window, so retries stay logarithmic in the node's size; a source that
354    /// cannot grow turns the shortfall into a real `UnexpectedEof`.
355    fn decode_next<'s, T>(
356        source: &'s mut Source<'_>,
357        decode: impl Fn(&mut Decoder<'s>) -> Result<T>,
358    ) -> Result<(T, usize)> {
359        loop {
360            let window: *const [u8] = source.available();
361            // SAFETY: `window` is a live slice of the source's buffer, and the
362            // buffer is not touched again on the path that keeps `bytes`: a
363            // successful decode returns at once, with `bytes` (and anything
364            // `T` borrows from it) bound to `'s`, the exclusive borrow of
365            // `source`, so no growth can follow while the value lives. On the
366            // short-read path neither `bytes` nor the decoder over it is used
367            // again once `grow` writes to the buffer. The raw pointer is what
368            // lets the borrow checker accept a borrow that is returned on one
369            // path and mutated past on the other (NLL problem case 3).
370            let bytes: &'s [u8] = unsafe { &*window };
371            let have = bytes.len();
372            let mut decoder = Decoder::new(bytes);
373            match decode(&mut decoder) {
374                Ok(value) => return Ok((value, decoder.position())),
375                Err(BinaryError::UnexpectedEof) => {}
376                Err(e) => return Err(e),
377            }
378            if !Self::grow(source, have)? {
379                return Err(BinaryError::UnexpectedEof);
380            }
381        }
382    }
383
384    /// Size the next node without decoding it (no allocation), growing the
385    /// window as [`Self::decode_next`] does. For nodes that are only skipped.
386    fn skip_next(
387        source: &mut Source<'_>,
388        walk: impl Fn(&mut Decoder<'_>) -> Result<()>,
389    ) -> Result<usize> {
390        loop {
391            let have = source.available().len();
392            let mut decoder = Decoder::new(source.available());
393            match walk(&mut decoder) {
394                Ok(()) => return Ok(decoder.position()),
395                Err(BinaryError::UnexpectedEof) => {}
396                Err(e) => return Err(e),
397            }
398            if !Self::grow(source, have)? {
399                return Err(BinaryError::UnexpectedEof);
400            }
401        }
402    }
403
404    /// Grow the window past `have` bytes, asking for double. False when the
405    /// source has nothing more.
406    fn grow(source: &mut Source<'_>, have: usize) -> Result<bool> {
407        let want = have.max(64).saturating_mul(2);
408        Ok(source.ensure(want)? || source.available().len() > have)
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415    use crate::builder::NodeBuilder;
416    use crate::marshal::marshal;
417    use crate::node::{Node, NodeContent, NodeContentRef};
418    use crate::zlib_pool::test_support::stored_zlib;
419
420    /// The compressed form of a packed payload. Stored blocks, not deflate:
421    /// the inflate path is what is under test, and a real compressor is not
422    /// Miri-clean (see `stored_zlib`).
423    fn compress(node_bytes: &[u8]) -> Vec<u8> {
424        let mut out = vec![FORMAT_COMPRESSED];
425        out.extend_from_slice(&stored_zlib(node_bytes));
426        out
427    }
428
429    /// The same node as a plain packed payload and as a compressed one.
430    fn both_forms(node: &Node) -> Vec<(&'static str, Vec<u8>)> {
431        let packed = marshal(node).unwrap();
432        let compressed = compress(&packed[1..]);
433        vec![("plain", packed), ("compressed", compressed)]
434    }
435
436    fn prop(code: u32, value: &str) -> Node {
437        NodeBuilder::new("prop")
438            .attr("config_code", code)
439            .attr("config_value", value)
440            .build()
441    }
442
443    /// A props-shaped response: many small children under one child of the
444    /// root, with one child much larger than the inflate window.
445    fn props_iq(count: usize) -> Node {
446        let mut children: Vec<Node> = (0..count as u32)
447            .map(|i| prop(1000 + i, if i % 3 == 0 { "true" } else { "17" }))
448            .collect();
449        let big_value = "x".repeat(3 * FRAME_INFLATE_CHUNK);
450        children.insert(count / 2, prop(7, &big_value));
451        let props = NodeBuilder::new("props")
452            .attr("protocol", "1")
453            .attr("hash", "abc")
454            .children(children)
455            .build();
456        NodeBuilder::new("iq")
457            .attr("type", "result")
458            .attr("id", "42")
459            .attr("from", "s.whatsapp.net")
460            .children(vec![props])
461            .build()
462    }
463
464    #[test]
465    #[cfg_attr(miri, ignore)]
466    fn walks_children_one_at_a_time_in_both_forms() {
467        let node = props_iq(2000);
468        let expected: Vec<Node> = match &node.content {
469            Some(NodeContent::Nodes(c)) => match &c[0].content {
470                Some(NodeContent::Nodes(props)) => props.clone(),
471                _ => unreachable!(),
472            },
473            _ => unreachable!(),
474        };
475        for (form, packed) in both_forms(&node) {
476            let mut stream = NodeStream::from_packed(&packed).unwrap();
477            assert_eq!(stream.is_compressed(), form == "compressed");
478            let root = stream.open().unwrap().expect("root");
479            assert_eq!(root.tag, "iq");
480            assert_eq!(root.attr_str("id").as_deref(), Some("42"));
481            assert_eq!(root.child_count(), 1);
482            let props = stream.open().unwrap().expect("props");
483            assert_eq!(props.tag, "props");
484            assert_eq!(props.attr_str("hash").as_deref(), Some("abc"));
485            assert_eq!(props.child_count(), expected.len());
486            assert_eq!(stream.depth(), 2);
487
488            let mut seen = 0;
489            while let Some(child) = stream.next_child().unwrap() {
490                assert_eq!(child.to_owned(), expected[seen], "{form}: child {seen}");
491                seen += 1;
492            }
493            assert_eq!(seen, expected.len(), "{form}");
494            stream.close().unwrap();
495            assert!(
496                stream.next_child().unwrap().is_none(),
497                "{form}: iq has one child"
498            );
499            stream.close().unwrap();
500            assert!(
501                stream.open().unwrap().is_none(),
502                "{form}: nothing after the root"
503            );
504            stream.finish().unwrap();
505        }
506    }
507
508    #[test]
509    fn close_skips_unread_children_and_continues_with_siblings() {
510        let node = NodeBuilder::new("iq")
511            .children(vec![
512                NodeBuilder::new("first")
513                    .children((0..50).map(|i| prop(i, "v")))
514                    .build(),
515                NodeBuilder::new("second")
516                    .children(vec![prop(1, "a"), prop(2, "b")])
517                    .build(),
518                NodeBuilder::new("third").attr("k", "v").build(),
519            ])
520            .build();
521        for (form, packed) in both_forms(&node) {
522            let mut stream = NodeStream::from_packed(&packed).unwrap();
523            stream.open().unwrap().expect("root");
524            let first = stream.open().unwrap().expect("first");
525            assert_eq!(first.tag, "first");
526            // Read three, leave the rest.
527            for _ in 0..3 {
528                stream.next_child().unwrap().expect("child");
529            }
530            stream.close().unwrap();
531
532            let second = stream.next_child().unwrap().expect("second, whole");
533            assert_eq!(second.tag, "second");
534            assert_eq!(second.children().map(|c| c.len()), Some(2));
535
536            let third = stream.open().unwrap().expect("third");
537            assert_eq!(third.tag, "third");
538            assert_eq!(third.attr_str("k").as_deref(), Some("v"));
539            assert_eq!(third.content, OpenContent::None);
540            assert!(stream.next_child().unwrap().is_none());
541            stream.close().unwrap();
542            assert!(stream.next_child().unwrap().is_none(), "{form}");
543            stream.finish().unwrap();
544        }
545    }
546
547    #[test]
548    fn scalar_content_and_empty_nodes_open_without_children() {
549        let node = NodeBuilder::new("message")
550            .children(vec![
551                NodeBuilder::new("body").string_content("hello").build(),
552                NodeBuilder::new("enc").bytes(vec![1, 2, 3]).build(),
553                NodeBuilder::new("empty").build(),
554            ])
555            .build();
556        for (_, packed) in both_forms(&node) {
557            let mut stream = NodeStream::from_packed(&packed).unwrap();
558            stream.open().unwrap().expect("root");
559            let body = stream.open().unwrap().expect("body");
560            // The tree decoder holds string content as its wire bytes too.
561            assert!(matches!(
562                &body.content,
563                OpenContent::Scalar(NodeContentRef::Bytes(b)) if b.as_ref() == b"hello"
564            ));
565            assert!(stream.next_child().unwrap().is_none());
566            stream.close().unwrap();
567            let enc = stream.open().unwrap().expect("enc");
568            assert!(matches!(
569                &enc.content,
570                OpenContent::Scalar(NodeContentRef::Bytes(b)) if b.as_ref() == [1, 2, 3]
571            ));
572            stream.close().unwrap();
573            let empty = stream.open().unwrap().expect("empty");
574            assert_eq!(empty.content, OpenContent::None);
575            stream.close().unwrap();
576            stream.finish().unwrap();
577        }
578    }
579
580    /// `finish` applies the tree decoder's strictness: trailing bytes behind the
581    /// root, and a compressed stream without its trailer, are errors.
582    #[test]
583    #[cfg_attr(miri, ignore)]
584    fn finish_rejects_leftover_bytes_and_a_truncated_stream() {
585        let node = props_iq(10);
586        let mut packed = marshal(&node).unwrap();
587        packed.push(0);
588        let mut stream = NodeStream::from_packed(&packed).unwrap();
589        stream.open().unwrap();
590        assert!(matches!(stream.finish(), Err(BinaryError::LeftoverData(1))));
591
592        // Larger, so a cut inside the stream still leaves the head decodable.
593        let node = props_iq(300);
594        let compressed = compress(&marshal(&node).unwrap()[1..]);
595        let truncated = &compressed[..compressed.len() - 2];
596        let mut stream = NodeStream::from_packed(truncated).unwrap();
597        stream.open().unwrap();
598        stream.open().unwrap();
599        while stream.next_child().unwrap().is_some() {}
600        assert!(matches!(stream.finish(), Err(BinaryError::Zlib(_))));
601
602        // A stream cut inside a child fails on that child, as `UnexpectedEof`.
603        let truncated = &compressed[..compressed.len() * 9 / 10];
604        let mut stream = NodeStream::from_packed(truncated).unwrap();
605        stream.open().unwrap();
606        stream.open().unwrap();
607        let mut result = Ok(());
608        loop {
609            match stream.next_child() {
610                Ok(Some(_)) => {}
611                Ok(None) => break,
612                Err(e) => {
613                    result = Err(e);
614                    break;
615                }
616            }
617        }
618        assert!(
619            matches!(result, Err(BinaryError::UnexpectedEof)),
620            "{result:?}"
621        );
622
623        // An untouched stream is walked whole by `finish` and still validated.
624        let mut stream = NodeStream::from_packed(&compressed).unwrap();
625        stream.finish().unwrap();
626    }
627
628    /// A stream that only looked at the root's head can still hand over the
629    /// whole payload, identical to what the one-shot unpack produces.
630    #[test]
631    #[cfg_attr(miri, ignore)]
632    fn into_inflated_after_peeking_the_root_matches_unpack() {
633        let node = props_iq(500);
634        let packed = marshal(&node).unwrap();
635        let compressed = compress(&packed[1..]);
636
637        let mut stream = NodeStream::from_packed(&compressed).unwrap();
638        let root = stream.open().unwrap().expect("root");
639        assert_eq!(root.tag, "iq");
640        let whole = stream.into_inflated().expect("compressed").unwrap();
641        assert_eq!(&whole[..], &packed[1..]);
642
643        // Plain payloads and consumed streams have nothing to hand over.
644        let mut stream = NodeStream::from_packed(&packed).unwrap();
645        stream.open().unwrap();
646        assert!(stream.into_inflated().is_none());
647        let mut stream = NodeStream::from_packed(&compressed).unwrap();
648        stream.open().unwrap();
649        stream.open().unwrap();
650        assert!(stream.into_inflated().is_none());
651    }
652
653    #[test]
654    #[cfg_attr(miri, ignore)]
655    fn depth_is_capped_like_the_tree_decoder() {
656        let mut node = NodeBuilder::new("leaf").build();
657        for _ in 0..(MAX_NODE_DEPTH + 2) {
658            node = NodeBuilder::new("n").children(vec![node]).build();
659        }
660        let packed = marshal(&node).unwrap();
661        let mut stream = NodeStream::from_packed(&packed).unwrap();
662        let mut result = Ok(());
663        loop {
664            match stream.open() {
665                Ok(Some(_)) => {}
666                Ok(None) => break,
667                Err(e) => {
668                    result = Err(e);
669                    break;
670                }
671            }
672        }
673        assert!(matches!(result, Err(BinaryError::MaxDepthExceeded)));
674    }
675
676    #[test]
677    fn empty_payload_is_refused() {
678        assert!(matches!(
679            NodeStream::from_packed(&[]),
680            Err(BinaryError::EmptyData)
681        ));
682    }
683
684    /// A child the stream skips unread is still held to the tree decoder's
685    /// validation: a string that is not UTF-8, or a packed digit outside the
686    /// nibble alphabet, fails `close` and `finish` as it fails `unmarshal_ref`.
687    #[test]
688    fn skipping_a_malformed_child_fails_like_the_tree_decoder() {
689        let node = NodeBuilder::new("iq")
690            .children(vec![
691                NodeBuilder::new("first").build(),
692                prop(1, "hello"),
693                prop(2, "12345"),
694            ])
695            .build();
696        let packed = marshal(&node).unwrap();
697
698        // "hello" is a BINARY_8 string; a 0xFF inside it is not UTF-8.
699        let mut bad_utf8 = packed.clone();
700        let at = bad_utf8
701            .windows(5)
702            .position(|w| w == b"hello")
703            .expect("the value is stored verbatim");
704        bad_utf8[at] = 0xFF;
705        // "12345" is packed as nibbles 0x12 0x34 0x5F; nibble 0xC is not a digit.
706        let mut bad_nibble = packed.clone();
707        let at = bad_nibble
708            .windows(3)
709            .position(|w| w == [0x12, 0x34, 0x5F])
710            .expect("the digits are nibble-packed");
711        bad_nibble[at] = 0xC2;
712
713        for (name, bytes) in [("utf-8", bad_utf8), ("nibble", bad_nibble)] {
714            assert!(
715                crate::marshal::unmarshal_ref(&bytes[1..]).is_err(),
716                "{name}: the tree decoder must reject the fixture"
717            );
718            let mut stream = NodeStream::from_packed(&bytes).unwrap();
719            stream.open().unwrap().expect("root");
720            stream.open().unwrap().expect("first");
721            stream.close().unwrap();
722            assert!(
723                stream.close().is_err(),
724                "{name}: skipping the rest must fail"
725            );
726
727            let mut stream = NodeStream::from_packed(&bytes).unwrap();
728            assert!(stream.finish().is_err(), "{name}: finish must fail");
729        }
730    }
731
732    /// Two more shapes the tree decoder refuses (`InvalidNode` for a node
733    /// without a tag, `NonStringKey` for an attribute key that is not a
734    /// string), hand-built since no encoder writes them, and skipped by the
735    /// stream the same way.
736    #[test]
737    fn skipping_a_child_with_no_tag_or_a_non_string_key_fails_like_the_tree_decoder() {
738        use crate::token::{BINARY_8, LIST_8, LIST_EMPTY};
739        let root_head = [LIST_8, 2, BINARY_8, 2, b'i', b'q', LIST_8, 2];
740        let first = [LIST_8, 1, BINARY_8, 5, b'f', b'i', b'r', b's', b't'];
741        let no_tag = vec![LIST_8, 1, LIST_EMPTY];
742        let bad_key = vec![LIST_8, 3, BINARY_8, 1, b'p', LIST_EMPTY, BINARY_8, 1, b'v'];
743
744        for (name, child, expected) in [
745            ("no tag", no_tag, BinaryError::InvalidNode),
746            ("non-string key", bad_key, BinaryError::NonStringKey),
747        ] {
748            let mut packed = vec![crate::util::FORMAT_PLAIN];
749            packed.extend_from_slice(&root_head);
750            packed.extend_from_slice(&first);
751            packed.extend_from_slice(&child);
752            assert!(
753                matches!(&crate::marshal::unmarshal_ref(&packed[1..]), Err(e) if std::mem::discriminant(e) == std::mem::discriminant(&expected)),
754                "{name}: the tree decoder must reject the fixture with {expected:?}"
755            );
756
757            let mut stream = NodeStream::from_packed(&packed).unwrap();
758            stream.open().unwrap().expect("root");
759            stream.open().unwrap().expect("first");
760            stream.close().unwrap();
761            let err = stream.close().expect_err("skipping the rest must fail");
762            assert_eq!(
763                std::mem::discriminant(&err),
764                std::mem::discriminant(&expected),
765                "{name}: {err:?}"
766            );
767            let mut stream = NodeStream::from_packed(&packed).unwrap();
768            assert!(stream.finish().is_err(), "{name}: finish must fail");
769        }
770    }
771}