Skip to main content

wacore_binary/
marshal.rs

1use std::io::Write;
2
3use crate::{
4    BinaryError, Node, NodeRef, Result,
5    decoder::Decoder,
6    encoder::{Encoder, build_marshaled_node_plan, build_marshaled_node_ref_plan},
7    node::{NodeContent, NodeContentRef, NodeValue},
8};
9
10const DEFAULT_MARSHAL_CAPACITY: usize = 1024;
11const AUTO_RESERVE_ATTRS_THRESHOLD: usize = 24;
12const AUTO_RESERVE_CHILDREN_THRESHOLD: usize = 64;
13const AUTO_RESERVE_SCALAR_THRESHOLD: usize = 8 * 1024;
14const AUTO_CHILD_SAMPLE_LIMIT: usize = 32;
15const AUTO_MAX_HINT_CAPACITY: usize = 512 * 1024;
16const AUTO_ATTR_ESTIMATE: usize = 24;
17const AUTO_CHILD_ESTIMATE: usize = 96;
18const AUTO_GRANDCHILD_ESTIMATE: usize = 40;
19
20/// Per node, before its own strings: `write_list_start`'s widest form
21/// (`LIST_16`: tag + u16), plus slack.
22const SHALLOW_NODE_OVERHEAD: usize = 4;
23/// A JID never encodes longer than its user plus the tag, agent, device,
24/// integrator and server-token bytes around it.
25const SHALLOW_JID_OVERHEAD: usize = 12;
26/// Children measured individually before the rest are extrapolated from them.
27const SHALLOW_CHILD_SAMPLE: usize = 32;
28/// Ceiling on the shallow reserve. An estimate this far out is a bug in the
29/// estimator, and past it one `Vec` growth is cheaper than trusting the guess.
30const SHALLOW_MAX_CAPACITY: usize = 4 * 1024 * 1024;
31
32/// Decode node bytes: the buffer without the format byte, which is what the
33/// receive path holds after [`unpack`](crate::util::unpack) and what
34/// `OwnedNodeRef` stores. For a buffer that still carries the format byte, as
35/// [`marshal`] writes it, use [`unmarshal_packed_ref`].
36pub fn unmarshal_ref(data: &[u8]) -> Result<NodeRef<'_>> {
37    let mut decoder = Decoder::new(data);
38    let node = decoder.read_node_ref()?;
39
40    if decoder.is_finished() {
41        Ok(node)
42    } else {
43        Err(BinaryError::LeftoverData(decoder.bytes_left()))
44    }
45}
46
47/// Decode a packed payload: the format byte plus node bytes, exactly what
48/// [`marshal`] produces and what a frame carries before `unpack`.
49///
50/// Only the uncompressed form is accepted: the returned node borrows from
51/// `data`, and decompressed bytes would have nowhere to live; reach for
52/// [`unpack`](crate::util::unpack) plus [`unmarshal_ref`] there.
53pub fn unmarshal_packed_ref(data: &[u8]) -> Result<NodeRef<'_>> {
54    crate::util::check_plain_payload(data)?;
55    unmarshal_ref(&data[1..])
56}
57
58pub fn marshal_to(node: &Node, writer: &mut impl Write) -> Result<()> {
59    let mut encoder = Encoder::new(writer)?;
60    encoder.write_node(node)?;
61    Ok(())
62}
63
64/// Serialize an owned node directly into a `Vec<u8>` using the fast vec writer path.
65pub fn marshal_to_vec(node: &Node, output: &mut Vec<u8>) -> Result<()> {
66    let mut encoder = Encoder::new_vec(output)?;
67    encoder.write_node(node)?;
68    Ok(())
69}
70
71pub fn marshal(node: &Node) -> Result<Vec<u8>> {
72    let mut payload = Vec::with_capacity(DEFAULT_MARSHAL_CAPACITY);
73    marshal_to_vec(node, &mut payload)?;
74    Ok(payload)
75}
76
77/// Serialize a `Node` using a conservative auto strategy.
78///
79/// This keeps the fast one-pass path for typical payloads and only uses
80/// a lightweight preallocation hint for obviously larger payload shapes.
81pub fn marshal_auto(node: &Node) -> Result<Vec<u8>> {
82    if should_auto_reserve_node(node) {
83        marshal_with_capacity(node, estimate_capacity_node(node))
84    } else {
85        marshal(node)
86    }
87}
88
89/// Serialize a `Node` using a two-pass strategy:
90/// 1) compute exact encoded size
91/// 2) write directly into a fixed-size output buffer
92///
93/// This avoids output buffer growth/copies and can be beneficial for large/variable payloads.
94pub fn marshal_exact(node: &Node) -> Result<Vec<u8>> {
95    let plan = build_marshaled_node_plan(node);
96    // Reserved, not zero-filled. `vec![0; plan.size]` memset every byte the
97    // encoder is about to overwrite, which for the large payloads this path
98    // exists for is a second full pass over the output. Appending into a `Vec`
99    // reserved to the exact plan size writes each byte once; the plan is still
100    // what decides the buffer's size, so a plan that undershoots grows the
101    // `Vec` and is caught by the length check below rather than silently
102    // truncating.
103    let mut payload = Vec::with_capacity(plan.size);
104    {
105        let mut encoder = Encoder::new_vec_with_hints(&mut payload, Some(&plan.hints))?;
106        encoder.write_node(node)?;
107    }
108    // Real checks, not debug_asserts: replayed hints are trusted in release,
109    // so a plan/encode traversal divergence must fail the marshal instead of
110    // shipping corrupt bytes. Two integer compares per stanza.
111    if payload.len() != plan.size || !plan.hints.fully_consumed() {
112        return Err(BinaryError::PlanMismatch);
113    }
114    Ok(payload)
115}
116
117/// Serialize a `Node` in one pass, into a buffer reserved from a shallow size
118/// estimate.
119///
120/// The reserve comes from the node's own byte lengths, which bound the
121/// encoding from above: a key, a token value, a JID and a packed id all encode
122/// shorter than they measure, so the sum overshoots by a modest constant and
123/// the write allocates exactly once. An undershoot — a tree whose sampled
124/// children are unrepresentative — costs a `Vec` growth, never a wrong
125/// encoding, which is what lets the estimate sample rather than walk.
126///
127/// Against [`marshal_exact`]: one traversal instead of two, at the price of a
128/// buffer that is a little larger than the payload.
129pub fn marshal_shallow(node: &Node) -> Result<Vec<u8>> {
130    marshal_with_capacity(node, shallow_capacity_node(node))
131}
132
133/// Zero-copy serialization of a `NodeRef` directly into a writer.
134/// This avoids the allocation overhead of converting to an owned `Node` first.
135pub fn marshal_ref_to(node: &NodeRef<'_>, writer: &mut impl Write) -> Result<()> {
136    let mut encoder = Encoder::new(writer)?;
137    encoder.write_node(node)?;
138    Ok(())
139}
140
141/// Serialize a borrowed node directly into a `Vec<u8>` using the fast vec writer path.
142pub fn marshal_ref_to_vec(node: &NodeRef<'_>, output: &mut Vec<u8>) -> Result<()> {
143    let mut encoder = Encoder::new_vec(output)?;
144    encoder.write_node(node)?;
145    Ok(())
146}
147
148/// Zero-copy serialization of a `NodeRef` to a new `Vec<u8>`.
149/// Prefer `marshal_ref_to` with a reusable buffer for best performance.
150pub fn marshal_ref(node: &NodeRef<'_>) -> Result<Vec<u8>> {
151    let mut payload = Vec::with_capacity(DEFAULT_MARSHAL_CAPACITY);
152    marshal_ref_to_vec(node, &mut payload)?;
153    Ok(payload)
154}
155
156/// Serialize a `NodeRef` using the same conservative auto strategy as `marshal_auto`.
157pub fn marshal_ref_auto(node: &NodeRef<'_>) -> Result<Vec<u8>> {
158    if should_auto_reserve_node_ref(node) {
159        marshal_ref_with_capacity(node, estimate_capacity_node_ref(node))
160    } else {
161        marshal_ref(node)
162    }
163}
164
165/// Serialize a `NodeRef` using a two-pass exact-size strategy.
166///
167/// This avoids output buffer growth/copies and preserves zero-copy input semantics.
168pub fn marshal_ref_exact(node: &NodeRef<'_>) -> Result<Vec<u8>> {
169    let plan = build_marshaled_node_ref_plan(node);
170    // Reserved rather than zero-filled, for the reason marshal_exact gives.
171    let mut payload = Vec::with_capacity(plan.size);
172    {
173        let mut encoder = Encoder::new_vec_with_hints(&mut payload, Some(&plan.hints))?;
174        encoder.write_node(node)?;
175    }
176    // Same invariant enforcement as marshal_exact.
177    if payload.len() != plan.size || !plan.hints.fully_consumed() {
178        return Err(BinaryError::PlanMismatch);
179    }
180    Ok(payload)
181}
182
183#[inline]
184fn marshal_with_capacity(node: &Node, capacity: usize) -> Result<Vec<u8>> {
185    let mut payload = Vec::with_capacity(capacity);
186    marshal_to_vec(node, &mut payload)?;
187    Ok(payload)
188}
189
190#[inline]
191fn marshal_ref_with_capacity(node: &NodeRef<'_>, capacity: usize) -> Result<Vec<u8>> {
192    let mut payload = Vec::with_capacity(capacity);
193    marshal_ref_to_vec(node, &mut payload)?;
194    Ok(payload)
195}
196
197/// Upper bound on a node's encoded size, from the lengths it already carries.
198///
199/// Breadth is sampled, depth is not. Sampling bounds the walk exactly where the
200/// tree is wide — the fan-out shapes this exists for — while a chain of narrow
201/// nodes is walked in full, because there the estimate costs no more than the
202/// encoder's own recursion over the same nodes and a depth cutoff would guess
203/// at whatever payload sits below it.
204fn shallow_capacity_node(node: &Node) -> usize {
205    let mut estimate = 0;
206    accumulate_shallow_estimate(node, &mut estimate);
207    estimate.min(SHALLOW_MAX_CAPACITY)
208}
209
210/// What a raw string of `len` bytes costs on the wire: the `BINARY_8`/`_20`/
211/// `_32` tag and its length field. Every other encoding of the same string —
212/// a token, a packed id, a JID — is shorter, which is what makes the sum of
213/// these an upper bound rather than a guess.
214#[inline]
215fn shallow_string_estimate(len: usize) -> usize {
216    const BINARY_20_LIMIT: usize = 1 << 20;
217    let header = if len < 256 {
218        2
219    } else if len < BINARY_20_LIMIT {
220        4
221    } else {
222        5
223    };
224    len + header
225}
226
227#[inline]
228fn shallow_value_estimate(value: &NodeValue) -> usize {
229    match value {
230        NodeValue::String(text) => shallow_string_estimate(text.len()),
231        NodeValue::Jid(jid) => jid.user.len() + SHALLOW_JID_OVERHEAD,
232    }
233}
234
235fn accumulate_shallow_estimate(node: &Node, estimate: &mut usize) {
236    *estimate += SHALLOW_NODE_OVERHEAD + shallow_string_estimate(node.tag.len());
237    for (key, value) in node.attrs.iter() {
238        *estimate += shallow_string_estimate(key.len()) + shallow_value_estimate(value);
239    }
240
241    match &node.content {
242        Some(NodeContent::Bytes(bytes)) => *estimate += shallow_string_estimate(bytes.len()),
243        Some(NodeContent::String(text)) => *estimate += shallow_string_estimate(text.len()),
244        Some(NodeContent::Nodes(children)) => {
245            if *estimate >= SHALLOW_MAX_CAPACITY {
246                return;
247            }
248            let sampled = children.len().min(SHALLOW_CHILD_SAMPLE);
249            let before = *estimate;
250            for child in &children[..sampled] {
251                accumulate_shallow_estimate(child, estimate);
252            }
253            // Every child past the sample is charged the sample's mean, rounded
254            // up. A fan-out is homogeneous by construction — one `<to>` per
255            // device — so this lands within the per-node slack; a tree that
256            // hides its bulk past the 32nd child pays one growth for it.
257            let remaining = children.len() - sampled;
258            if remaining > 0 {
259                *estimate += (*estimate - before).div_ceil(sampled) * remaining;
260            }
261        }
262        None => {}
263    }
264}
265
266#[inline]
267fn should_auto_reserve_node(node: &Node) -> bool {
268    if node.attrs.len() >= AUTO_RESERVE_ATTRS_THRESHOLD {
269        return true;
270    }
271
272    match &node.content {
273        Some(NodeContent::Bytes(bytes)) => bytes.len() >= AUTO_RESERVE_SCALAR_THRESHOLD,
274        Some(NodeContent::String(text)) => text.len() >= AUTO_RESERVE_SCALAR_THRESHOLD,
275        Some(NodeContent::Nodes(children)) => {
276            if children.len() >= AUTO_RESERVE_CHILDREN_THRESHOLD {
277                return true;
278            }
279            // Check one level deeper for large nested lists (e.g., <iq> -> <list> -> 812 keys)
280            children.iter().any(|child| {
281                matches!(&child.content, Some(NodeContent::Nodes(gc)) if gc.len() >= AUTO_RESERVE_CHILDREN_THRESHOLD)
282            })
283        }
284        None => false,
285    }
286}
287
288#[inline]
289fn should_auto_reserve_node_ref(node: &NodeRef<'_>) -> bool {
290    if node.attrs.len() >= AUTO_RESERVE_ATTRS_THRESHOLD {
291        return true;
292    }
293
294    match node.content.as_ref() {
295        Some(NodeContentRef::Bytes(bytes)) => bytes.len() >= AUTO_RESERVE_SCALAR_THRESHOLD,
296        Some(NodeContentRef::String(text)) => text.len() >= AUTO_RESERVE_SCALAR_THRESHOLD,
297        Some(NodeContentRef::Nodes(children)) => {
298            if children.len() >= AUTO_RESERVE_CHILDREN_THRESHOLD {
299                return true;
300            }
301            // Check one level deeper for large nested lists (e.g., <iq> -> <list> -> 812 keys)
302            children.iter().any(|child| {
303                matches!(child.content.as_ref(), Some(NodeContentRef::Nodes(gc)) if gc.len() >= AUTO_RESERVE_CHILDREN_THRESHOLD)
304            })
305        }
306        None => false,
307    }
308}
309
310#[inline]
311fn estimate_capacity_node(node: &Node) -> usize {
312    let mut estimate = DEFAULT_MARSHAL_CAPACITY + 16;
313    estimate += node.tag.len();
314    estimate += node.attrs.len() * AUTO_ATTR_ESTIMATE;
315
316    match &node.content {
317        Some(NodeContent::Bytes(bytes)) => {
318            estimate += bytes.len() + 8;
319        }
320        Some(NodeContent::String(text)) => {
321            estimate += text.len() + 8;
322        }
323        Some(NodeContent::Nodes(children)) => {
324            estimate += children.len() * AUTO_CHILD_ESTIMATE;
325            for child in children.iter().take(AUTO_CHILD_SAMPLE_LIMIT) {
326                estimate += child.tag.len() + child.attrs.len() * AUTO_ATTR_ESTIMATE;
327                match &child.content {
328                    Some(NodeContent::Bytes(bytes)) => estimate += bytes.len() + 8,
329                    Some(NodeContent::String(text)) => estimate += text.len() + 8,
330                    Some(NodeContent::Nodes(grand_children)) => {
331                        estimate += grand_children.len() * AUTO_GRANDCHILD_ESTIMATE;
332                    }
333                    None => {}
334                }
335                if estimate >= AUTO_MAX_HINT_CAPACITY {
336                    return AUTO_MAX_HINT_CAPACITY;
337                }
338            }
339        }
340        None => {}
341    }
342
343    estimate.clamp(DEFAULT_MARSHAL_CAPACITY, AUTO_MAX_HINT_CAPACITY)
344}
345
346#[inline]
347fn estimate_capacity_node_ref(node: &NodeRef<'_>) -> usize {
348    let mut estimate = DEFAULT_MARSHAL_CAPACITY + 16;
349    estimate += node.tag.len();
350    estimate += node.attrs.len() * AUTO_ATTR_ESTIMATE;
351
352    match node.content.as_ref() {
353        Some(NodeContentRef::Bytes(bytes)) => {
354            estimate += bytes.len() + 8;
355        }
356        Some(NodeContentRef::String(text)) => {
357            estimate += text.len() + 8;
358        }
359        Some(NodeContentRef::Nodes(children)) => {
360            estimate += children.len() * AUTO_CHILD_ESTIMATE;
361            for child in children.iter().take(AUTO_CHILD_SAMPLE_LIMIT) {
362                estimate += child.tag.len() + child.attrs.len() * AUTO_ATTR_ESTIMATE;
363                match child.content.as_ref() {
364                    Some(NodeContentRef::Bytes(bytes)) => estimate += bytes.len() + 8,
365                    Some(NodeContentRef::String(text)) => estimate += text.len() + 8,
366                    Some(NodeContentRef::Nodes(grand_children)) => {
367                        estimate += grand_children.len() * AUTO_GRANDCHILD_ESTIMATE;
368                    }
369                    None => {}
370                }
371                if estimate >= AUTO_MAX_HINT_CAPACITY {
372                    return AUTO_MAX_HINT_CAPACITY;
373                }
374            }
375        }
376        None => {}
377    }
378
379    estimate.clamp(DEFAULT_MARSHAL_CAPACITY, AUTO_MAX_HINT_CAPACITY)
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385    use crate::jid::Jid;
386    use crate::node::{Attrs, NodeContent, NodeValue};
387
388    type TestResult = Result<()>;
389
390    /// An interop JID's `integrator` has a wire field only in `INTEROP_JID`.
391    /// Encoded as a `JID_PAIR` it is simply absent, so two interop destinations
392    /// that differ only there went out as the same bytes.
393    ///
394    /// Asserted on the emitted bytes rather than by round-tripping: our decoder
395    /// reads a trailing server that the outbound form does not carry (see
396    /// `write_interop_jid`), so a local encode/decode cycle is the wrong oracle
397    /// here — the two directions of this token genuinely differ.
398    ///
399    /// Every encoder path is covered because `marshal_exact` sizes its output
400    /// buffer from the size estimator before writing into it: an estimator that
401    /// disagrees with the writer surfaces as `PlanMismatch`, not as wrong bytes,
402    /// and `marshal_exact` is what production sends through.
403    #[test]
404    fn interop_jid_carries_its_integrator_onto_the_wire() -> TestResult {
405        use crate::jid::Server;
406
407        fn node_for(jid: &Jid) -> Node {
408            let mut attrs = Attrs::with_capacity(1);
409            attrs.push("jid".to_string(), NodeValue::Jid(jid.clone()));
410            Node::new("iq", attrs, None)
411        }
412
413        fn encode_all(jid: &Jid) -> Vec<(&'static str, Vec<u8>)> {
414            let node = node_for(jid);
415            let r = node.as_node_ref();
416            vec![
417                ("marshal", marshal(&node).expect("marshal")),
418                ("marshal_exact", marshal_exact(&node).expect("exact")),
419                ("marshal_ref", marshal_ref(&r).expect("ref")),
420                (
421                    "marshal_ref_exact",
422                    marshal_ref_exact(&r).expect("ref exact"),
423                ),
424            ]
425        }
426
427        let base = Jid {
428            user: "123456789".into(),
429            server: Server::Interop,
430            agent: 0,
431            device: 7,
432            integrator: 300,
433        };
434
435        // The integrator reaches the bytes: change only it, and the encoding
436        // changes. Under JID_PAIR these were byte-identical.
437        let other = Jid {
438            integrator: 301,
439            ..base.clone()
440        };
441        for ((path, a), (_, b)) in encode_all(&base).into_iter().zip(encode_all(&other)) {
442            assert_ne!(a, b, "{path}: the integrator must reach the wire");
443            assert!(
444                a.contains(&crate::token::INTEROP_JID),
445                "{path}: must use the INTEROP_JID token"
446            );
447            // Big-endian device and integrator, adjacent, as WA Web writes them.
448            assert!(
449                a.windows(4).any(|w| w == [0x00, 0x07, 0x01, 0x2C]),
450                "{path}: device 7 and integrator 300 as u16 BE"
451            );
452        }
453
454        // Every path agrees byte for byte, so the exact-size plan matches the
455        // writer. When it does not, `marshal_exact` fails outright.
456        let encodings = encode_all(&base);
457        let (_, first) = &encodings[0];
458        for (path, bytes) in &encodings[1..] {
459            assert_eq!(bytes, first, "{path}: must agree with marshal");
460        }
461
462        // A zero-integrator interop JID keeps the JID_PAIR form we have always
463        // sent. That form carries user and server only — it drops the device —
464        // which is pre-existing and deliberately untouched here.
465        let plain = Jid {
466            integrator: 0,
467            ..base.clone()
468        };
469        let bytes = marshal(&node_for(&plain))?;
470        assert!(
471            !bytes.contains(&crate::token::INTEROP_JID),
472            "no integrator, no INTEROP_JID token"
473        );
474        let decoded = unmarshal_packed_ref(&bytes)?;
475        let back = decoded
476            .attrs
477            .iter()
478            .find(|(k, _)| &**k == "jid")
479            .and_then(|(_, v)| v.to_jid())
480            .expect("jid attr");
481        assert_eq!(back.server, Server::Interop);
482        assert_eq!(back.device, 0, "JID_PAIR carries no device");
483
484        Ok(())
485    }
486
487    /// The two round-trips real code performs — through the wire, and through the
488    /// store, which holds JIDs as text — have to agree: a JID that survives one
489    /// must equal a JID that survives the other, or `stored_jid == wire_jid`
490    /// silently flips depending on where each side came from.
491    #[test]
492    fn ad_jid_round_trips_equal_through_the_wire_and_through_text() -> TestResult {
493        use crate::jid::Server;
494        use std::str::FromStr;
495
496        for server in [Server::Pn, Server::Lid, Server::Hosted, Server::HostedLid] {
497            let original = Jid {
498                user: "123456789012345".into(),
499                server,
500                agent: 0,
501                device: 7,
502                integrator: 0,
503            };
504
505            let mut attrs = Attrs::with_capacity(1);
506            attrs.push("jid".to_string(), NodeValue::Jid(original.clone()));
507            let node = Node::new("iq", attrs, None);
508
509            let bytes = marshal(&node)?;
510            let decoded = unmarshal_packed_ref(&bytes)?;
511            let from_wire = decoded
512                .attrs
513                .iter()
514                .find(|(k, _)| &**k == "jid")
515                .and_then(|(_, v)| v.to_jid())
516                .expect("jid attr survives the round-trip");
517
518            assert_eq!(
519                from_wire, original,
520                "{server:?}: encode -> decode must be idempotent"
521            );
522
523            let from_text = Jid::from_str(&from_wire.to_string()).expect("renders parseably");
524            assert_eq!(
525                from_wire, from_text,
526                "{server:?}: a wire-decoded JID must equal the same JID read back as text"
527            );
528        }
529
530        Ok(())
531    }
532
533    fn fixture_node() -> Node {
534        let mut attrs = Attrs::with_capacity(4);
535        attrs.push("id".to_string(), "ABC123");
536        attrs.push("to".to_string(), "123456789@s.whatsapp.net");
537        attrs.push(
538            "participant".to_string(),
539            NodeValue::Jid("15551234567@s.whatsapp.net".parse::<Jid>().unwrap()),
540        );
541        attrs.push("hex".to_string(), "DEADBEEF");
542
543        let child = Node::new(
544            "item",
545            Attrs::new(),
546            Some(NodeContent::Bytes(vec![1, 2, 3, 4, 5, 6, 7, 8])),
547        );
548
549        Node::new(
550            "message",
551            attrs,
552            Some(NodeContent::Nodes(vec![
553                child,
554                Node::new(
555                    "text",
556                    Attrs::new(),
557                    Some(NodeContent::String("hello".repeat(40).into())),
558                ),
559            ])),
560        )
561    }
562
563    fn large_binary_fixture() -> Node {
564        Node::new(
565            "message",
566            Attrs::new(),
567            Some(NodeContent::Bytes(vec![
568                0xAB;
569                AUTO_RESERVE_SCALAR_THRESHOLD + 2048
570            ])),
571        )
572    }
573
574    #[test]
575    fn test_marshaled_node_size_matches_output() -> TestResult {
576        let node = fixture_node();
577        let plan = build_marshaled_node_plan(&node);
578        let payload = marshal(&node)?;
579        assert_eq!(payload.len(), plan.size);
580        Ok(())
581    }
582
583    // The exact path replays plan-recorded hints by traversal order, so it
584    // must produce byte-identical output to the hint-free vec path for every
585    // string shape (tokens, numerics, hex, JIDs with device/agent/empty user,
586    // long strings, bytes, nesting). A divergence in traversal order shows up
587    // here (and as a debug_assert in write_string) before it can corrupt the
588    // wire.
589    #[test]
590    fn test_exact_matches_plain_for_all_string_shapes() -> TestResult {
591        let mut attrs = Attrs::with_capacity(8);
592        attrs.push("to".to_string(), "15551234567@s.whatsapp.net");
593        attrs.push("from".to_string(), "15550000001:12@s.whatsapp.net");
594        attrs.push("participant".to_string(), "15550000002_1@lid");
595        attrs.push("broadcast".to_string(), "status@broadcast");
596        attrs.push("type".to_string(), "text");
597        attrs.push("count".to_string(), "12345");
598        attrs.push("hexish".to_string(), "0123ABCDEF");
599        attrs.push("plain".to_string(), "not_a_token_value");
600        // Empty-user JID: the one branch that skips a hint entirely.
601        attrs.push("empty_user".to_string(), "@s.whatsapp.net");
602        // Typed JID value: user/server hints with no wrapping string hint.
603        attrs.push(
604            "typed_jid".to_string(),
605            NodeValue::Jid("15550000003:7@s.whatsapp.net".parse::<Jid>().unwrap()),
606        );
607        let node = Node::new(
608            "iq",
609            attrs,
610            Some(NodeContent::Nodes(vec![
611                Node::new(
612                    "text",
613                    Attrs::new(),
614                    Some(NodeContent::String("x".repeat(300).into())),
615                ),
616                Node::new("empty", Attrs::new(), Some(NodeContent::String("".into()))),
617                Node::new(
618                    "bin",
619                    Attrs::new(),
620                    Some(NodeContent::Bytes(vec![0xAB; 64])),
621                ),
622                Node::new("leaf", Attrs::new(), None),
623            ])),
624        );
625
626        assert_eq!(marshal(&node)?, marshal_exact(&node)?);
627        let node_ref = node.as_node_ref();
628        assert_eq!(marshal_ref(&node_ref)?, marshal_ref_exact(&node_ref)?);
629        Ok(())
630    }
631
632    #[test]
633    fn test_marshaled_node_ref_size_matches_output() -> TestResult {
634        let node = fixture_node();
635        let node_ref = node.as_node_ref();
636        let plan = build_marshaled_node_ref_plan(&node_ref);
637        let payload = marshal_ref(&node_ref)?;
638        assert_eq!(payload.len(), plan.size);
639        Ok(())
640    }
641
642    #[test]
643    fn test_marshal_matches_marshal_to_bytes() -> TestResult {
644        let node = fixture_node();
645
646        let payload_alloc = marshal(&node)?;
647
648        let mut payload_writer = Vec::new();
649        marshal_to(&node, &mut payload_writer)?;
650
651        assert_eq!(payload_alloc, payload_writer);
652        Ok(())
653    }
654
655    #[test]
656    fn test_marshal_ref_matches_marshal_ref_to_bytes() -> TestResult {
657        let node = fixture_node();
658        let node_ref = node.as_node_ref();
659
660        let payload_alloc = marshal_ref(&node_ref)?;
661
662        let mut payload_writer = Vec::new();
663        marshal_ref_to(&node_ref, &mut payload_writer)?;
664
665        assert_eq!(payload_alloc, payload_writer);
666        Ok(())
667    }
668
669    #[test]
670    fn test_marshal_to_vec_matches_marshal_to() -> TestResult {
671        let node = fixture_node();
672
673        let mut payload_vec_writer = Vec::new();
674        marshal_to_vec(&node, &mut payload_vec_writer)?;
675
676        let mut payload_writer = Vec::new();
677        marshal_to(&node, &mut payload_writer)?;
678
679        assert_eq!(payload_vec_writer, payload_writer);
680        Ok(())
681    }
682
683    #[test]
684    fn test_marshal_ref_to_vec_matches_marshal_ref_to() -> TestResult {
685        let node = fixture_node();
686        let node_ref = node.as_node_ref();
687
688        let mut payload_vec_writer = Vec::new();
689        marshal_ref_to_vec(&node_ref, &mut payload_vec_writer)?;
690
691        let mut payload_writer = Vec::new();
692        marshal_ref_to(&node_ref, &mut payload_writer)?;
693
694        assert_eq!(payload_vec_writer, payload_writer);
695        Ok(())
696    }
697
698    #[test]
699    fn test_marshal_exact_matches_marshal_to_bytes() -> TestResult {
700        let node = fixture_node();
701
702        let payload_exact = marshal_exact(&node)?;
703
704        let mut payload_writer = Vec::new();
705        marshal_to(&node, &mut payload_writer)?;
706
707        assert_eq!(payload_exact, payload_writer);
708        Ok(())
709    }
710
711    /// The exact-size paths reserve their output instead of zero-filling it, so
712    /// nothing initializes the bytes the encoder does not reach: a plan that
713    /// overshoots can no longer leave a tail of zeros that happens to look like
714    /// a valid encoding, and one that undershoots grows the buffer instead of
715    /// erroring inside the writer. Both now surface only through the length
716    /// check, which the other exact tests exercise on a small fixture; this one
717    /// runs a payload past every growth step a `Vec` would take on the way to
718    /// it, where a divergence has room to show up as wrong bytes.
719    #[test]
720    fn exact_paths_match_the_streaming_writer_on_a_large_payload() -> TestResult {
721        let mut attrs = Attrs::with_capacity(2);
722        attrs.push("id".to_string(), "ABC123");
723        attrs.push(
724            "to".to_string(),
725            NodeValue::Jid("15551234567@s.whatsapp.net".parse::<Jid>().unwrap()),
726        );
727        let children: Vec<Node> = (0..512)
728            .map(|i| {
729                let mut child_attrs = Attrs::with_capacity(1);
730                child_attrs.push("i".to_string(), i.to_string());
731                Node::new(
732                    "item",
733                    child_attrs,
734                    Some(NodeContent::Bytes(vec![(i % 251) as u8; 64])),
735                )
736            })
737            .collect();
738        let node = Node::new("message", attrs, Some(NodeContent::Nodes(children)));
739        let node_ref = node.as_node_ref();
740
741        let mut streamed = Vec::new();
742        marshal_to(&node, &mut streamed)?;
743        assert!(
744            streamed.len() > 32 * 1024,
745            "fixture must outgrow the small-payload paths"
746        );
747
748        assert_eq!(marshal_exact(&node)?, streamed, "marshal_exact");
749        assert_eq!(marshal_ref_exact(&node_ref)?, streamed, "marshal_ref_exact");
750        Ok(())
751    }
752
753    #[test]
754    fn test_marshal_ref_exact_matches_marshal_ref_to_bytes() -> TestResult {
755        let node = fixture_node();
756        let node_ref = node.as_node_ref();
757
758        let payload_exact = marshal_ref_exact(&node_ref)?;
759
760        let mut payload_writer = Vec::new();
761        marshal_ref_to(&node_ref, &mut payload_writer)?;
762
763        assert_eq!(payload_exact, payload_writer);
764        Ok(())
765    }
766
767    #[test]
768    fn test_marshal_auto_matches_marshal_to_bytes() -> TestResult {
769        let node = fixture_node();
770        let payload_auto = marshal_auto(&node)?;
771
772        let mut payload_writer = Vec::new();
773        marshal_to(&node, &mut payload_writer)?;
774
775        assert_eq!(payload_auto, payload_writer);
776        Ok(())
777    }
778
779    #[test]
780    fn test_marshal_ref_auto_matches_marshal_ref_to_bytes() -> TestResult {
781        let node = fixture_node();
782        let node_ref = node.as_node_ref();
783        let payload_auto = marshal_ref_auto(&node_ref)?;
784
785        let mut payload_writer = Vec::new();
786        marshal_ref_to(&node_ref, &mut payload_writer)?;
787
788        assert_eq!(payload_auto, payload_writer);
789        Ok(())
790    }
791
792    #[test]
793    fn test_marshal_auto_large_binary_matches_marshal_to_bytes() -> TestResult {
794        let node = large_binary_fixture();
795        let payload_auto = marshal_auto(&node)?;
796
797        let mut payload_writer = Vec::new();
798        marshal_to(&node, &mut payload_writer)?;
799
800        assert_eq!(payload_auto, payload_writer);
801        Ok(())
802    }
803
804    #[test]
805    fn test_marshal_ref_auto_large_binary_matches_marshal_ref_to_bytes() -> TestResult {
806        let node = large_binary_fixture();
807        let node_ref = node.as_node_ref();
808        let payload_auto = marshal_ref_auto(&node_ref)?;
809
810        let mut payload_writer = Vec::new();
811        marshal_ref_to(&node_ref, &mut payload_writer)?;
812
813        assert_eq!(payload_auto, payload_writer);
814        Ok(())
815    }
816}