Skip to main content

wacore_binary/
encoder.rs

1use std::io::Write;
2
3use crate::error::{BinaryError, Result};
4use crate::jid::{self, Jid, JidRef};
5use crate::node::{Node, NodeContent, NodeContentRef, NodeRef, NodeValue, ValueRef};
6use crate::token;
7
8/// Marks a byte no packed encoding accepts. `validate_hex`/`validate_nibble`
9/// gate every caller, so a hit means the caller skipped that check.
10const PACK_INVALID: u8 = 0xFF;
11
12/// ASCII to nibble, the inverse of the decoder's `HEX_PAIRS`. Index 0 maps to
13/// 15 because that is the pad an odd-length string writes as its second half.
14static HEX_ENC: [u8; 256] = {
15    let mut table = [PACK_INVALID; 256];
16    let mut c = b'0';
17    while c <= b'9' {
18        table[c as usize] = c - b'0';
19        c += 1;
20    }
21    let mut c = b'A';
22    while c <= b'F' {
23        table[c as usize] = 10 + (c - b'A');
24        c += 1;
25    }
26    table[0] = 15;
27    table
28};
29
30/// ASCII to nibble for `NIBBLE_8`: digits plus the two punctuation characters
31/// a phone number can carry.
32static NIBBLE_ENC: [u8; 256] = {
33    let mut table = [PACK_INVALID; 256];
34    let mut c = b'0';
35    while c <= b'9' {
36        table[c as usize] = c - b'0';
37        c += 1;
38    }
39    table[b'-' as usize] = 10;
40    table[b'.' as usize] = 11;
41    table[0] = 15;
42    table
43};
44
45pub trait ByteWriter {
46    fn write_u8(&mut self, value: u8) -> Result<()>;
47    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()>;
48}
49
50pub(crate) struct IoByteWriter<W: Write> {
51    writer: W,
52}
53
54impl<W: Write> IoByteWriter<W> {
55    fn new(writer: W) -> Self {
56        Self { writer }
57    }
58}
59
60impl<W: Write> ByteWriter for IoByteWriter<W> {
61    #[inline]
62    fn write_u8(&mut self, value: u8) -> Result<()> {
63        self.writer.write_all(&[value])?;
64        Ok(())
65    }
66
67    #[inline]
68    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
69        self.writer.write_all(bytes)?;
70        Ok(())
71    }
72}
73
74pub struct VecByteWriter<'a> {
75    buffer: &'a mut Vec<u8>,
76}
77
78impl<'a> VecByteWriter<'a> {
79    fn new(buffer: &'a mut Vec<u8>) -> Self {
80        Self { buffer }
81    }
82}
83
84impl ByteWriter for VecByteWriter<'_> {
85    #[inline]
86    fn write_u8(&mut self, value: u8) -> Result<()> {
87        self.buffer.push(value);
88        Ok(())
89    }
90
91    #[inline]
92    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
93        self.buffer.extend_from_slice(bytes);
94        Ok(())
95    }
96}
97
98/// Trait for encoding node structures (both owned Node and borrowed NodeRef).
99/// All encoding logic lives in the trait implementation, keeping
100/// the Encoder simple and focused on low-level byte writing.
101pub trait EncodeNode {
102    fn tag(&self) -> &str;
103    fn attrs_len(&self) -> usize;
104    fn has_content(&self) -> bool;
105
106    /// Encode all attributes to the encoder
107    fn encode_attrs<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()>;
108
109    /// Encode content (string, bytes, or child nodes) to the encoder
110    fn encode_content<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()>;
111}
112
113impl EncodeNode for Node {
114    fn tag(&self) -> &str {
115        &self.tag
116    }
117
118    fn attrs_len(&self) -> usize {
119        self.attrs.len()
120    }
121
122    fn has_content(&self) -> bool {
123        self.content.is_some()
124    }
125
126    fn encode_attrs<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()> {
127        for (k, v) in &self.attrs {
128            encoder.write_string(k)?;
129            match v {
130                NodeValue::String(s) => encoder.write_string(s)?,
131                NodeValue::Jid(jid) => encoder.write_jid_owned(jid)?,
132            }
133        }
134        Ok(())
135    }
136
137    fn encode_content<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()> {
138        if let Some(content) = &self.content {
139            match content {
140                NodeContent::String(s) => encoder.write_string(s)?,
141                NodeContent::Bytes(b) => encoder.write_bytes_with_len(b)?,
142                NodeContent::Nodes(nodes) => {
143                    encoder.write_list_start(nodes.len())?;
144                    for node in nodes {
145                        encoder.write_node(node)?;
146                    }
147                }
148            }
149        }
150        Ok(())
151    }
152}
153
154impl EncodeNode for NodeRef<'_> {
155    fn tag(&self) -> &str {
156        &self.tag
157    }
158
159    fn attrs_len(&self) -> usize {
160        self.attrs.len()
161    }
162
163    fn has_content(&self) -> bool {
164        self.content.is_some()
165    }
166
167    fn encode_attrs<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()> {
168        for (k, v) in self.attrs.iter() {
169            encoder.write_string(k)?;
170            match v {
171                ValueRef::String(s) => encoder.write_string(s)?,
172                ValueRef::Jid(jid) => encoder.write_jid_ref(jid)?,
173            }
174        }
175        Ok(())
176    }
177
178    fn encode_content<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()> {
179        if let Some(content) = self.content.as_ref() {
180            match content {
181                NodeContentRef::String(s) => encoder.write_string(s)?,
182                NodeContentRef::Bytes(b) => encoder.write_bytes_with_len(b)?,
183                NodeContentRef::Nodes(nodes) => {
184                    encoder.write_list_start(nodes.len())?;
185                    for node in nodes.iter() {
186                        encoder.write_node(node)?;
187                    }
188                }
189            }
190        }
191        Ok(())
192    }
193}
194
195// u8 offsets keep StringHint small — the hint tape stores one per string —
196// and always fit: classify_string_hint only treats strings <= 48 bytes as
197// JID candidates. The tape is one hint per string of the whole node, so a
198// byte added here is a byte times every string in the payload: keep the
199// resolved server and derive everything derivable from it.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201struct ParsedJidMeta {
202    user_end: u8,
203    server_start: u8,
204    device: Option<u8>,
205    /// The resolved server, when the suffix is one we know. `JID_PAIR` writes
206    /// this rather than the caller's substring, so a string-valued attribute
207    /// (`.attr("to", "…@c.us")`) is spelled on the wire exactly as the
208    /// equivalent `Jid` would be. `None` keeps an unknown suffix verbatim,
209    /// which is the only way it can survive the round trip.
210    server: Option<jid::Server>,
211}
212
213impl ParsedJidMeta {
214    /// The AD_JID domain byte, from the resolved server rather than a second
215    /// stored copy of the same fact — `device` is `Some` only for the servers
216    /// [`server_supports_ad_jid`] accepts, which are exactly the ones
217    /// [`server_to_domain_type`] maps.
218    #[inline]
219    fn domain_type(self) -> u8 {
220        self.server.map_or(0, server_to_domain_type)
221    }
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225enum StringHint {
226    Empty,
227    SingleToken(u8),
228    DoubleToken { dict: u8, token: u8 },
229    PackedNibble,
230    PackedHex,
231    Jid(ParsedJidMeta),
232    RawBytes,
233}
234
235/// Replay tape: sound only while plan and encode visit strings in the same
236/// (`write_node`) order — `write_string` debug-asserts each replayed hint to
237/// catch divergence. 32 inline keeps a typical stanza off the heap.
238#[derive(Debug, Default)]
239pub(crate) struct StringHintCache {
240    hints: smallvec::SmallVec<[StringHint; 32]>,
241    cursor: std::cell::Cell<usize>,
242}
243
244impl StringHintCache {
245    /// Plan side: classify once and append to the tape.
246    #[inline]
247    fn record(&mut self, s: &str) -> StringHint {
248        // Strings longer than PACKED_MAX (127) can't be protocol tokens
249        // (max 48), packed nibble/hex, or JIDs — skip classification.
250        let hint = if s.len() > token::PACKED_MAX as usize {
251            StringHint::RawBytes
252        } else {
253            classify_string_hint(s)
254        };
255        self.hints.push(hint);
256        hint
257    }
258
259    /// Encode side: consume the next recorded hint.
260    #[inline]
261    fn next(&self) -> Option<StringHint> {
262        let i = self.cursor.get();
263        let hint = self.hints.get(i).copied();
264        if hint.is_some() {
265            self.cursor.set(i + 1);
266        }
267        hint
268    }
269
270    /// The exact-marshal fns require this after encoding: a leftover hint
271    /// means plan and encode diverged, and the output can't be trusted.
272    /// (Reusing an exhausted tape for a second encode is merely slow, not
273    /// wrong — `next` returns None and `write_string` classifies inline.)
274    #[inline]
275    pub(crate) fn fully_consumed(&self) -> bool {
276        self.cursor.get() == self.hints.len()
277    }
278}
279
280#[derive(Debug)]
281pub(crate) struct MarshaledSizePlan {
282    pub(crate) size: usize,
283    pub(crate) hints: StringHintCache,
284}
285
286fn parse_jid_meta(input: &str) -> Option<ParsedJidMeta> {
287    let sep_idx = input.find('@')?;
288    let server_start = sep_idx + 1;
289    let server = &input[server_start..];
290    let user_combined = &input[..sep_idx];
291
292    let (user_agent, device) = if let Some(colon_idx) = user_combined.find(':')
293        && let Ok(parsed_device) = user_combined[colon_idx + 1..].parse::<u8>()
294    {
295        (&user_combined[..colon_idx], Some(parsed_device))
296    } else {
297        (user_combined, None)
298    };
299
300    let mut user_end = if let Some(underscore_idx) = user_agent.find('_')
301        && user_agent[underscore_idx + 1..].parse::<u8>().is_ok()
302    {
303        underscore_idx
304    } else {
305        user_agent.len()
306    };
307
308    let server_kind = jid::Server::parse_known(server);
309    // A dotted agent is inert on the phone and hosted namespaces, so a parsed
310    // `Jid` drops it from the rendered form (`renders_agent`). Drop it here too,
311    // or the two public attribute paths address different users: `read_jid_pair`
312    // takes the user verbatim and never reads a `.2` back as an agent. `@lid`
313    // is excluded because a dot there is part of the user, and the servers that
314    // do render an agent keep it for the same reason -- it is theirs.
315    if matches!(
316        server_kind,
317        Some(jid::Server::Pn | jid::Server::Hosted | jid::Server::HostedLid)
318    ) && let Some(dot_idx) = user_agent[..user_end].rfind('.')
319        && user_agent[dot_idx + 1..user_end].parse::<u8>().is_ok()
320    {
321        user_end = dot_idx;
322    }
323
324    // Single source of truth: only servers whose domain byte the decoder
325    // round-trips back can use AD_JID. For everyone else drop the device
326    // and fall through to JID_PAIR (which preserves the server name).
327    let device = server_kind
328        .filter(|s| server_supports_ad_jid(*s))
329        .and(device);
330
331    Some(ParsedJidMeta {
332        server: server_kind,
333        user_end: u8::try_from(user_end).ok()?,
334        server_start: u8::try_from(server_start).ok()?,
335        device,
336    })
337}
338
339#[inline]
340fn split_jid_from_meta(input: &str, meta: ParsedJidMeta) -> (&str, &str) {
341    (
342        &input[..meta.user_end as usize],
343        &input[meta.server_start as usize..],
344    )
345}
346
347/// Map a JID server string to the AD_JID domain_type byte.
348///
349/// The AD_JID binary encoding uses a single byte to identify the server:
350///   0 = s.whatsapp.net (default)
351///   1 = lid
352///   128 = hosted
353///   129 = hosted.lid
354///
355/// WARNING: This must stay in sync with the inverse mapping in
356/// `decoder.rs read_ad_jid`. The string path no longer keeps its own copy of
357/// this mapping — `ParsedJidMeta::domain_type` calls this. Writing `jid.agent`
358/// unconditionally here (instead of only as a fallback) was the root cause of a
359/// regression where LID group messages were silently rejected by the server
360/// (error 421).
361#[inline]
362fn server_to_domain_type(server: jid::Server) -> u8 {
363    match server {
364        jid::Server::Pn => 0,
365        jid::Server::Lid => 1,
366        jid::Server::Hosted => 128,
367        jid::Server::HostedLid => 129,
368        _ => 0,
369    }
370}
371
372/// Whether this JID needs the dedicated `INTEROP_JID` token to survive the
373/// round-trip.
374///
375/// An interop JID carries an `integrator` that no other wire form has a field
376/// for: `JID_PAIR` writes only user and server, so encoding one that way silently
377/// drops it. WA Web has a matching branch (`WA/Wap.js`, the `JID_INTEROP` arm of
378/// its JID writer) and its decoder reads the field back, as does ours.
379///
380/// Restricted to a non-zero integrator on purpose. An interop JID without one
381/// loses nothing through `JID_PAIR`, and that is the form we have always sent —
382/// this fixes the case that was lossy without changing the bytes for the case
383/// that was not.
384#[inline]
385fn needs_interop_jid(server: jid::Server, integrator: u16) -> bool {
386    server == jid::Server::Interop && integrator != 0
387}
388
389/// AD_JID round-trips back to a server via `domain_type` only for the four
390/// servers the decoder explicitly maps. For everything else (bot, group,
391/// broadcast, newsletter, call, interop, msgr, legacy) no valid AD_JID domain
392/// type exists. Writers must check this and emit JID_PAIR for non-AD-capable
393/// servers even when `device > 0`.
394/// Matches whatsmeow `writeJID` and WA Web `WAWap.De`.
395#[inline]
396fn server_supports_ad_jid(server: jid::Server) -> bool {
397    matches!(
398        server,
399        jid::Server::Pn | jid::Server::Lid | jid::Server::Hosted | jid::Server::HostedLid
400    )
401}
402
403#[inline]
404fn classify_string_hint(s: &str) -> StringHint {
405    if s.is_empty() {
406        return StringHint::Empty;
407    }
408
409    let is_likely_jid = s.len() <= 48;
410
411    if let Some(kind) = token::index_of_token(s) {
412        return match kind {
413            token::TokenKind::Single(token) => StringHint::SingleToken(token),
414            token::TokenKind::Double(dict, token) => StringHint::DoubleToken { dict, token },
415        };
416    }
417
418    if validate_nibble(s) {
419        StringHint::PackedNibble
420    } else if validate_hex(s) {
421        StringHint::PackedHex
422    } else if is_likely_jid {
423        parse_jid_meta(s).map_or(StringHint::RawBytes, StringHint::Jid)
424    } else {
425        StringHint::RawBytes
426    }
427}
428
429pub(crate) fn build_marshaled_node_plan(node: &Node) -> MarshaledSizePlan {
430    let mut hints = StringHintCache::default();
431    let size = 1 + node_encoded_size_with_cache(node, &mut hints);
432    MarshaledSizePlan { size, hints }
433}
434
435pub(crate) fn build_marshaled_node_ref_plan(node: &NodeRef<'_>) -> MarshaledSizePlan {
436    let mut hints = StringHintCache::default();
437    let size = 1 + node_ref_encoded_size_with_cache(node, &mut hints);
438    MarshaledSizePlan { size, hints }
439}
440
441#[inline]
442fn list_start_encoded_size(len: usize) -> usize {
443    if len == 0 {
444        1
445    } else if len < 256 {
446        2
447    } else {
448        3
449    }
450}
451
452#[inline]
453fn binary_len_prefix_size(len: usize) -> usize {
454    if len < 256 {
455        2
456    } else if len < (1 << 20) {
457        4
458    } else {
459        5
460    }
461}
462
463#[inline]
464fn bytes_with_len_encoded_size(len: usize) -> usize {
465    binary_len_prefix_size(len) + len
466}
467
468#[inline]
469fn packed_encoded_size(value_len: usize) -> usize {
470    2 + value_len.div_ceil(2)
471}
472
473// Statement order below matters: hints are recorded for replay, so strings
474// must be visited exactly as write_node emits them — tag, then each attr's
475// key then value, then content.
476fn node_encoded_size_with_cache(node: &Node, hints: &mut StringHintCache) -> usize {
477    let content_len = usize::from(node.content.is_some());
478    let list_len = 1 + (node.attrs.len() * 2) + content_len;
479
480    let mut size =
481        list_start_encoded_size(list_len) + string_encoded_size_with_cache(&node.tag, hints);
482
483    for (k, v) in &node.attrs {
484        size += string_encoded_size_with_cache(k, hints);
485        size += match v {
486            NodeValue::String(s) => string_encoded_size_with_cache(s, hints),
487            NodeValue::Jid(jid) => owned_jid_encoded_size_with_cache(jid, hints),
488        };
489    }
490
491    size += match &node.content {
492        Some(NodeContent::String(s)) => string_encoded_size_with_cache(s, hints),
493        Some(NodeContent::Bytes(b)) => bytes_with_len_encoded_size(b.len()),
494        Some(NodeContent::Nodes(nodes)) => {
495            list_start_encoded_size(nodes.len())
496                + nodes
497                    .iter()
498                    .map(|child| node_encoded_size_with_cache(child, hints))
499                    .sum::<usize>()
500        }
501        None => 0,
502    };
503    size
504}
505
506// Same statement-order constraint as node_encoded_size_with_cache.
507fn node_ref_encoded_size_with_cache(node: &NodeRef<'_>, hints: &mut StringHintCache) -> usize {
508    let content_len = usize::from(node.content.is_some());
509    let list_len = 1 + (node.attrs.len() * 2) + content_len;
510
511    let mut size = list_start_encoded_size(list_len)
512        + string_encoded_size_with_cache(node.tag.as_ref(), hints);
513
514    for (k, v) in node.attrs.iter() {
515        size += string_encoded_size_with_cache(k, hints);
516        size += match v {
517            ValueRef::String(s) => string_encoded_size_with_cache(s, hints),
518            ValueRef::Jid(jid) => jid_ref_encoded_size_with_cache(jid, hints),
519        };
520    }
521
522    size += match node.content.as_ref() {
523        Some(NodeContentRef::String(s)) => string_encoded_size_with_cache(s, hints),
524        Some(NodeContentRef::Bytes(b)) => bytes_with_len_encoded_size(b.len()),
525        Some(NodeContentRef::Nodes(nodes)) => {
526            list_start_encoded_size(nodes.len())
527                + nodes
528                    .iter()
529                    .map(|child| node_ref_encoded_size_with_cache(child, hints))
530                    .sum::<usize>()
531        }
532        None => 0,
533    };
534    size
535}
536
537#[inline]
538fn string_encoded_size_with_cache(s: &str, hints: &mut StringHintCache) -> usize {
539    let hint = hints.record(s);
540    string_encoded_size_from_hint_with_cache(s, hint, hints)
541}
542
543#[inline]
544fn string_encoded_size_from_hint_with_cache(
545    s: &str,
546    hint: StringHint,
547    hints: &mut StringHintCache,
548) -> usize {
549    match hint {
550        StringHint::Empty => 2,
551        StringHint::SingleToken(_) => 1,
552        StringHint::DoubleToken { .. } => 2,
553        StringHint::PackedNibble | StringHint::PackedHex => packed_encoded_size(s.len()),
554        StringHint::RawBytes => bytes_with_len_encoded_size(s.len()),
555        StringHint::Jid(meta) => parsed_jid_encoded_size_with_cache(s, meta, hints),
556    }
557}
558
559#[inline]
560fn parsed_jid_encoded_size_with_cache(
561    jid: &str,
562    meta: ParsedJidMeta,
563    hints: &mut StringHintCache,
564) -> usize {
565    let (user, raw_server) = split_jid_from_meta(jid, meta);
566    // The same canonicalisation `write_jid_from_meta` applies. Sizing the
567    // caller's substring while the writer emits the resolved spelling is not a
568    // bad estimate, it is an `UnexpectedEof` on the send.
569    let server = meta.server.map_or(raw_server, |s| s.as_str());
570    if meta.device.is_some() {
571        3 + string_encoded_size_with_cache(user, hints)
572    } else {
573        let user_size = if user.is_empty() {
574            1
575        } else {
576            string_encoded_size_with_cache(user, hints)
577        };
578        1 + user_size + string_encoded_size_with_cache(server, hints)
579    }
580}
581
582/// Byte count for one encoded JID.
583///
584/// Must mirror `write_jid_ref`/`write_jid_owned` branch for branch: the exact
585/// marshal sizes its output slice from this and then writes into it, so a plan
586/// that disagrees with the writer is not a bad estimate — it is an
587/// `UnexpectedEof` on a send. Both JID flavours route through here so the two
588/// cannot drift apart.
589#[inline]
590fn jid_encoded_size_with_cache(
591    user: &str,
592    server: jid::Server,
593    device: u16,
594    integrator: u16,
595    hints: &mut StringHintCache,
596) -> usize {
597    if needs_interop_jid(server, integrator) {
598        // token + user + u16 device + u16 integrator; no server, see
599        // `write_interop_jid`.
600        return 1 + string_encoded_size_with_cache(user, hints) + 2 + 2;
601    }
602    if device > 0 && server_supports_ad_jid(server) {
603        return 3 + string_encoded_size_with_cache(user, hints);
604    }
605    let user_size = if user.is_empty() {
606        1
607    } else {
608        string_encoded_size_with_cache(user, hints)
609    };
610    1 + user_size + string_encoded_size_with_cache(server.as_str(), hints)
611}
612
613#[inline]
614fn owned_jid_encoded_size_with_cache(jid: &Jid, hints: &mut StringHintCache) -> usize {
615    jid_encoded_size_with_cache(&jid.user, jid.server, jid.device, jid.integrator, hints)
616}
617
618#[inline]
619fn jid_ref_encoded_size_with_cache(jid: &JidRef<'_>, hints: &mut StringHintCache) -> usize {
620    jid_encoded_size_with_cache(&jid.user, jid.server, jid.device, jid.integrator, hints)
621}
622
623#[inline]
624fn validate_nibble(value: &str) -> bool {
625    if value.len() > token::PACKED_MAX as usize {
626        return false;
627    }
628    value
629        .as_bytes()
630        .iter()
631        .all(|&b| b.is_ascii_digit() || b == b'-' || b == b'.')
632}
633
634#[inline]
635fn validate_hex(value: &str) -> bool {
636    if value.len() > token::PACKED_MAX as usize {
637        return false;
638    }
639    value
640        .as_bytes()
641        .iter()
642        .all(|&b| b.is_ascii_digit() || (b'A'..=b'F').contains(&b))
643}
644
645pub struct Encoder<'a, W: ByteWriter> {
646    writer: W,
647    string_hints: Option<&'a StringHintCache>,
648}
649
650impl<W: Write> Encoder<'static, IoByteWriter<W>> {
651    pub fn new(writer: W) -> Result<Self> {
652        let mut enc = Self {
653            writer: IoByteWriter::new(writer),
654            string_hints: None,
655        };
656        enc.write_u8(crate::util::FORMAT_PLAIN)?;
657        Ok(enc)
658    }
659}
660
661impl<'v> Encoder<'static, VecByteWriter<'v>> {
662    pub fn new_vec(buffer: &'v mut Vec<u8>) -> Result<Self> {
663        Self::new_vec_with_hints(buffer, None)
664    }
665}
666
667impl<'a, 'v> Encoder<'a, VecByteWriter<'v>> {
668    /// Append into `buffer`, replaying a plan's string hints.
669    ///
670    /// The exact-size marshallers reach for this rather than writing into a
671    /// pre-sized `&mut [u8]` so their output buffer can be reserved instead of
672    /// zero-filled: a `Vec` only ever grown by writes needs no initial value
673    /// for the bytes the encoder is about to overwrite, while a slice has to
674    /// be fully initialized before the encoder can borrow it. The exact-size
675    /// invariant is enforced the same way either side, by comparing the
676    /// written length against the plan.
677    pub(crate) fn new_vec_with_hints(
678        buffer: &'v mut Vec<u8>,
679        string_hints: Option<&'a StringHintCache>,
680    ) -> Result<Self> {
681        buffer.clear();
682        let mut enc = Self {
683            writer: VecByteWriter::new(buffer),
684            string_hints,
685        };
686        enc.write_u8(crate::util::FORMAT_PLAIN)?;
687        Ok(enc)
688    }
689}
690
691impl<'a, W: ByteWriter> Encoder<'a, W> {
692    #[inline(always)]
693    fn write_u8(&mut self, val: u8) -> Result<()> {
694        self.writer.write_u8(val)
695    }
696
697    #[inline(always)]
698    fn write_u16_be(&mut self, val: u16) -> Result<()> {
699        self.writer.write_bytes(&val.to_be_bytes())
700    }
701
702    #[inline(always)]
703    fn write_u32_be(&mut self, val: u32) -> Result<()> {
704        self.writer.write_bytes(&val.to_be_bytes())
705    }
706
707    #[inline(always)]
708    fn write_u20_be(&mut self, value: u32) -> Result<()> {
709        let bytes = [
710            ((value >> 16) & 0x0F) as u8,
711            ((value >> 8) & 0xFF) as u8,
712            (value & 0xFF) as u8,
713        ];
714        self.writer.write_bytes(&bytes)
715    }
716
717    #[inline(always)]
718    fn write_raw_bytes(&mut self, bytes: &[u8]) -> Result<()> {
719        self.writer.write_bytes(bytes)
720    }
721
722    #[inline(always)]
723    pub fn write_bytes_with_len(&mut self, bytes: &[u8]) -> Result<()> {
724        let len = bytes.len();
725        if len < 256 {
726            self.write_u8(token::BINARY_8)?;
727            self.write_u8(len as u8)?;
728        } else if len < (1 << 20) {
729            self.write_u8(token::BINARY_20)?;
730            self.write_u20_be(len as u32)?;
731        } else {
732            self.write_u8(token::BINARY_32)?;
733            self.write_u32_be(len as u32)?;
734        }
735        self.write_raw_bytes(bytes)
736    }
737
738    #[inline(always)]
739    pub fn write_string(&mut self, s: &str) -> Result<()> {
740        if let Some(string_hints) = self.string_hints
741            && let Some(hint) = string_hints.next()
742        {
743            debug_assert_eq!(
744                hint,
745                if s.len() > token::PACKED_MAX as usize {
746                    StringHint::RawBytes
747                } else {
748                    classify_string_hint(s)
749                },
750                "hint tape misaligned at {s:?}: plan and encode no longer \
751                 traverse strings in the same order"
752            );
753            return self.write_string_with_hint(s, hint);
754        }
755        self.write_string_uncached(s)
756    }
757
758    #[inline(always)]
759    fn write_string_uncached(&mut self, s: &str) -> Result<()> {
760        // Strings longer than PACKED_MAX (127) can't be protocol tokens (max 48),
761        // packed nibble/hex, or JIDs — emit as raw bytes without classification.
762        if s.len() > token::PACKED_MAX as usize {
763            return self.write_bytes_with_len(s.as_bytes());
764        }
765        self.write_string_with_hint(s, classify_string_hint(s))
766    }
767
768    #[inline(always)]
769    fn write_string_with_hint(&mut self, s: &str, hint: StringHint) -> Result<()> {
770        match hint {
771            StringHint::Empty => {
772                self.write_u8(token::BINARY_8)?;
773                self.write_u8(0)?;
774            }
775            StringHint::SingleToken(token) => self.write_u8(token)?,
776            StringHint::DoubleToken { dict, token } => {
777                self.write_u8(token::DICTIONARY_0 + dict)?;
778                self.write_u8(token)?;
779            }
780            StringHint::PackedNibble => self.write_packed_bytes(s, token::NIBBLE_8)?,
781            StringHint::PackedHex => self.write_packed_bytes(s, token::HEX_8)?,
782            StringHint::Jid(meta) => self.write_jid_from_meta(s, meta)?,
783            StringHint::RawBytes => self.write_bytes_with_len(s.as_bytes())?,
784        }
785        Ok(())
786    }
787
788    #[inline(always)]
789    fn write_jid_from_meta(&mut self, jid: &str, meta: ParsedJidMeta) -> Result<()> {
790        let (user, raw_server) = split_jid_from_meta(jid, meta);
791        let server = meta.server.map_or(raw_server, |s| s.as_str());
792        if let Some(device) = meta.device {
793            self.write_u8(token::AD_JID)?;
794            self.write_u8(meta.domain_type())?;
795            self.write_u8(device)?;
796            self.write_string(user)?;
797        } else {
798            self.write_u8(token::JID_PAIR)?;
799            if user.is_empty() {
800                self.write_u8(token::LIST_EMPTY)?;
801            } else {
802                self.write_string(user)?;
803            }
804            self.write_string(server)?;
805        }
806        Ok(())
807    }
808
809    /// Write a JidRef directly without converting to string first.
810    /// This avoids the allocation that would occur with `jid.to_string()`.
811    /// `INTEROP_JID`: token, user, `u16` device, `u16` integrator — and no server.
812    ///
813    /// Mirrors WA Web's outbound writer (`WA/Wap.js`, the `JID_INTEROP` arm):
814    /// `writeUint8(S), te(user), writeUint16(device), writeUint16(integrator)`.
815    ///
816    /// Its inbound decoder reads a fourth value after those — the server — and so
817    /// does ours. That asymmetry is deliberate here rather than a bug being
818    /// copied: the fourth read describes what the *server sends us*, not what it
819    /// accepts from us, and the writer above is what actually runs against the
820    /// real server. Emitting a server the server does not expect would not merely
821    /// mis-parse the JID: the extra token would be read as the next value in the
822    /// stanza, desynchronising everything after it.
823    ///
824    /// The consequence is that this output does not round-trip through our own
825    /// `read_interop_jid`. That is a property of the protocol's two directions,
826    /// not a defect to fix by making both ends agree locally.
827    fn write_interop_jid(&mut self, user: &str, device: u16, integrator: u16) -> Result<()> {
828        self.write_u8(token::INTEROP_JID)?;
829        self.write_string(user)?;
830        self.write_u16_be(device)?;
831        self.write_u16_be(integrator)
832    }
833
834    pub fn write_jid_ref(&mut self, jid: &JidRef<'_>) -> Result<()> {
835        if needs_interop_jid(jid.server, jid.integrator) {
836            return self.write_interop_jid(&jid.user, jid.device, jid.integrator);
837        }
838        if jid.device > 0 && server_supports_ad_jid(jid.server) {
839            // AD_JID format: domain_type, device, user
840            let device = u8::try_from(jid.device).map_err(|_| {
841                BinaryError::AttrParse(format!("AD_JID device id out of range: {}", jid.device))
842            })?;
843            self.write_u8(token::AD_JID)?;
844            self.write_u8(server_to_domain_type(jid.server))?;
845            self.write_u8(device)?;
846            self.write_string(&jid.user)?;
847        } else {
848            // JID_PAIR format: user, server
849            self.write_u8(token::JID_PAIR)?;
850            if jid.user.is_empty() {
851                self.write_u8(token::LIST_EMPTY)?;
852            } else {
853                self.write_string(&jid.user)?;
854            }
855            self.write_string(jid.server.as_str())?;
856        }
857        Ok(())
858    }
859
860    /// Write an owned Jid directly without converting to string first.
861    /// This avoids the allocation that would occur with `jid.to_string()`.
862    pub fn write_jid_owned(&mut self, jid: &Jid) -> Result<()> {
863        if needs_interop_jid(jid.server, jid.integrator) {
864            return self.write_interop_jid(&jid.user, jid.device, jid.integrator);
865        }
866        if jid.device > 0 && server_supports_ad_jid(jid.server) {
867            // AD_JID format: domain_type, device, user
868            let device = u8::try_from(jid.device).map_err(|_| {
869                BinaryError::AttrParse(format!("AD_JID device id out of range: {}", jid.device))
870            })?;
871            self.write_u8(token::AD_JID)?;
872            self.write_u8(server_to_domain_type(jid.server))?;
873            self.write_u8(device)?;
874            self.write_string(&jid.user)?;
875        } else {
876            // JID_PAIR format: user, server
877            self.write_u8(token::JID_PAIR)?;
878            if jid.user.is_empty() {
879                self.write_u8(token::LIST_EMPTY)?;
880            } else {
881                self.write_string(&jid.user)?;
882            }
883            self.write_string(jid.server.as_str())?;
884        }
885        Ok(())
886    }
887
888    fn write_packed_bytes(&mut self, value: &str, data_type: u8) -> Result<()> {
889        if value.len() > token::PACKED_MAX as usize {
890            panic!("String too long to be packed: {}", value.len());
891        }
892
893        self.write_u8(data_type)?;
894
895        let mut rounded_len = value.len().div_ceil(2) as u8;
896        if !value.len().is_multiple_of(2) {
897            rounded_len |= 0x80;
898        }
899        self.write_u8(rounded_len)?;
900
901        let input_bytes = value.as_bytes();
902        let table = if data_type == token::NIBBLE_8 {
903            &NIBBLE_ENC
904        } else {
905            &HEX_ENC
906        };
907
908        // Whole pairs first, so the common even-length case carries no
909        // per-iteration "is there a second half" branch. `PACKED_MAX` is 127,
910        // so the buffer covers any string that reaches here.
911        let mut packed = [0u8; 64];
912        let (pairs, tail) = input_bytes.as_chunks::<2>();
913
914        // The validity test is an OR accumulator checked once below, not a
915        // branch per pair. Legal table entries are 0..=15 and `PACK_INVALID`
916        // is 0xFF, so a set high nibble in `seen` means some character was
917        // rejected. Keeping the branch out is what lets LLVM unroll this.
918        let mut seen = 0u8;
919        for (slot, pair) in packed.iter_mut().zip(pairs) {
920            let hi = table[pair[0] as usize];
921            let lo = table[pair[1] as usize];
922            seen |= hi | lo;
923            *slot = (hi << 4) | lo;
924        }
925
926        // Odd length: the low nibble is the 0 pad, which both tables map to 15.
927        let odd = if let [last] = tail {
928            let hi = table[*last as usize];
929            let lo = table[0];
930            seen |= hi | lo;
931            Some((hi << 4) | lo)
932        } else {
933            None
934        };
935
936        // Checked before anything reaches the writer. `validate_hex` and
937        // `validate_nibble` gate every caller, so this is the same unreachable
938        // case the `match` ladders this replaced used to panic on.
939        assert!(seen & 0xF0 == 0, "invalid char for packing");
940
941        self.write_raw_bytes(&packed[..pairs.len()])?;
942        if let Some(byte) = odd {
943            self.write_u8(byte)?;
944        }
945        Ok(())
946    }
947
948    pub fn write_list_start(&mut self, len: usize) -> Result<()> {
949        if len == 0 {
950            self.write_u8(token::LIST_EMPTY)?;
951        } else if len < 256 {
952            self.write_u8(248)?;
953            self.write_u8(len as u8)?;
954        } else if len <= u16::MAX as usize {
955            self.write_u8(249)?;
956            self.write_u16_be(len as u16)?;
957        } else {
958            return Err(BinaryError::InvalidNode);
959        }
960        Ok(())
961    }
962
963    /// Write any node type (owned or borrowed) using the EncodeNode trait.
964    pub fn write_node<N: EncodeNode>(&mut self, node: &N) -> Result<()> {
965        let content_len = if node.has_content() { 1 } else { 0 };
966        let list_len = 1 + (node.attrs_len() * 2) + content_len;
967
968        self.write_list_start(list_len)?;
969        self.write_string(node.tag())?;
970        node.encode_attrs(self)?;
971        node.encode_content(self)?;
972        Ok(())
973    }
974}
975
976#[cfg(test)]
977mod tests {
978    use super::*;
979    use crate::builder::NodeBuilder;
980    use crate::node::Attrs;
981    use std::io::Cursor;
982
983    type TestResult = Result<()>;
984
985    /// The `match` ladders `HEX_ENC`/`NIBBLE_ENC` replaced, kept here as the
986    /// specification they are checked against. `None` is the case the old code
987    /// panicked on and the tables mark with `PACK_INVALID`.
988    fn reference_hex(value: u8) -> Option<u8> {
989        match value {
990            c if c.is_ascii_digit() => Some(c - b'0'),
991            c if (b'A'..=b'F').contains(&c) => Some(10 + (c - b'A')),
992            0 => Some(15),
993            _ => None,
994        }
995    }
996
997    fn reference_nibble(value: u8) -> Option<u8> {
998        match value {
999            b'-' => Some(10),
1000            b'.' => Some(11),
1001            0 => Some(15),
1002            c if c.is_ascii_digit() => Some(c - b'0'),
1003            _ => None,
1004        }
1005    }
1006
1007    /// Exhaustive over the byte domain, so the tables cannot drift from the
1008    /// ladders they were derived from: same accepted set, same nibble for
1009    /// every accepted byte, same rejected set.
1010    #[test]
1011    fn encode_tables_match_the_ladders_they_replaced() {
1012        for byte in 0u8..=255 {
1013            let i = byte as usize;
1014            assert_eq!(
1015                reference_hex(byte),
1016                (HEX_ENC[i] != PACK_INVALID).then_some(HEX_ENC[i]),
1017                "hex table disagrees at {byte:#04x}"
1018            );
1019            assert_eq!(
1020                reference_nibble(byte),
1021                (NIBBLE_ENC[i] != PACK_INVALID).then_some(NIBBLE_ENC[i]),
1022                "nibble table disagrees at {byte:#04x}"
1023            );
1024        }
1025    }
1026
1027    /// The hint tape holds one `StringHint` per string in the payload, so its
1028    /// width is multiplied by every tag, attribute key, attribute value and
1029    /// string content of the node: a 2048-child stanza records ~12k hints, and
1030    /// one byte added here is 16 KiB of peak allocation once the `SmallVec`
1031    /// rounds up. Adding a field that duplicates something already derivable
1032    /// (the AD_JID domain byte, from the resolved server) cost exactly that
1033    /// before it was derived instead. Pinned so the next field has to justify
1034    /// itself. Budget: at most five bytes per string on the tape, so a
1035    /// repack that shrinks an entry is fine and only growth fails.
1036    /// Rebaseline per
1037    /// [layout asserts](../../../agent_docs/testing.md).
1038    #[test]
1039    fn the_hint_tape_stays_five_bytes_wide() {
1040        assert!(
1041            size_of::<StringHint>() <= 5,
1042            "StringHint got wider than 5 B (now {} B); the tape is one per string, so this is \
1043             peak memory times every string in the payload",
1044            size_of::<StringHint>()
1045        );
1046        assert!(
1047            size_of::<ParsedJidMeta>() <= 5,
1048            "ParsedJidMeta got wider than 5 B (now {} B)",
1049            size_of::<ParsedJidMeta>()
1050        );
1051    }
1052
1053    /// The legacy spelling must not reach the wire by any encoding path, not
1054    /// just the message send. `write_jid_owned`/`write_jid_ref` write
1055    /// `server.as_str()` for a JID_PAIR with no guard, and `c.us` is not in the
1056    /// token dictionary (`s.whatsapp.net` is), so emitting it would put a raw
1057    /// string on the wire where WA Web sends a token -- and a server spelling
1058    /// WA Web never sends at all, since its whole JID layer (`WAJids`) knows
1059    /// only `s.whatsapp.net`. There is no guard because there is nothing left
1060    /// to guard against: no `Server` renders it. This holds the bytes to that.
1061    #[test]
1062    fn the_legacy_spelling_never_reaches_the_wire() -> TestResult {
1063        use crate::jid::{Jid, parse_jid_ref};
1064
1065        fn encode(jid: &Jid) -> Result<Vec<u8>> {
1066            let mut buffer = Vec::new();
1067            let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1068            encoder.write_jid_owned(jid)?;
1069            Ok(buffer)
1070        }
1071
1072        for (raw, modern) in [
1073            ("5511999998888@c.us", "5511999998888@s.whatsapp.net"),
1074            // AD_JID form: same domain byte, so the bytes match there too.
1075            ("5511999998888:3@c.us", "5511999998888:3@s.whatsapp.net"),
1076            // A dotted agent is inert on a phone user and encodes nothing.
1077            ("5511999998888.2@c.us", "5511999998888@s.whatsapp.net"),
1078        ] {
1079            let legacy: Jid = raw.parse().unwrap();
1080            let modern: Jid = modern.parse().unwrap();
1081            let bytes = encode(&legacy)?;
1082            assert_eq!(bytes, encode(&modern)?, "{raw} must encode as {modern}");
1083            assert!(
1084                !bytes.windows(4).any(|w| w == b"c.us"),
1085                "{raw} put the legacy spelling on the wire: {bytes:?}"
1086            );
1087
1088            // The string path: a caller that hands a JID as a node attribute
1089            // (`.attr("to", "…@c.us")`) never builds a `Jid`, and the JID_PAIR
1090            // branch there writes the server substring straight out of the
1091            // input.
1092            let mut buffer = Vec::new();
1093            let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1094            encoder.write_string(raw)?;
1095            assert!(
1096                !buffer.windows(4).any(|w| w == b"c.us"),
1097                "the string path leaked the legacy spelling of {raw}: {buffer:?}"
1098            );
1099
1100            // A dotted agent in a string attribute must drop out the same way
1101            // it does for a parsed `Jid`, or the two public paths address
1102            // different users: `read_jid_pair` reads the user verbatim and
1103            // never parses a `.2` back into an agent.
1104            let dotted = format!("{}.2@c.us", legacy.user);
1105            let mut buffer = Vec::new();
1106            let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1107            encoder.write_string(&dotted)?;
1108            assert_eq!(
1109                buffer,
1110                encode(&modern.to_non_ad())?,
1111                "{dotted} must encode as the bare user, like the parsed Jid does"
1112            );
1113
1114            // Plan and write must agree on the canonical spelling too: the
1115            // exact marshal sizes its buffer from the estimator and then writes
1116            // into it, so a mismatch is an `UnexpectedEof`, not a loose bound.
1117            let node = NodeBuilder::new("message").attr("to", raw).build();
1118            let exact = crate::marshal::marshal_exact(&node)?;
1119            assert_eq!(
1120                exact,
1121                crate::marshal::marshal(&node)?,
1122                "plan and writer disagree for {raw}"
1123            );
1124            assert!(
1125                !exact.windows(4).any(|w| w == b"c.us"),
1126                "a string-valued attribute leaked the legacy spelling of {raw}"
1127            );
1128
1129            // The borrowed writer is a separate copy of the same branch.
1130            let rendered = legacy.to_string();
1131            let borrowed = parse_jid_ref(&rendered).unwrap();
1132            let mut buffer = Vec::new();
1133            let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1134            encoder.write_jid_ref(&borrowed)?;
1135            assert_eq!(buffer, bytes);
1136        }
1137        Ok(())
1138    }
1139
1140    #[test]
1141    fn test_encode_node() -> TestResult {
1142        let node = Node::new(
1143            "message",
1144            Attrs::new(),
1145            Some(NodeContent::String("receipt".into())),
1146        );
1147
1148        let mut buffer = Vec::new();
1149        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1150        encoder.write_node(&node)?;
1151
1152        let expected = vec![0, 248, 2, 19, 7];
1153        assert_eq!(buffer, expected);
1154        assert_eq!(buffer.len(), 5);
1155        Ok(())
1156    }
1157
1158    #[test]
1159    fn test_nibble_packing() -> TestResult {
1160        // Test string with nibble characters: '-', '.', '0'-'9'
1161        let test_str = "-.0123456789";
1162        let node = Node::new(
1163            "test",
1164            Attrs::new(),
1165            Some(NodeContent::String(test_str.into())),
1166        );
1167
1168        let mut buffer = Vec::new();
1169        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1170        encoder.write_node(&node)?;
1171
1172        let expected = vec![
1173            0, 248, 2, 252, 4, 116, 101, 115, 116, 255, 6, 171, 1, 35, 69, 103, 137,
1174        ];
1175        assert_eq!(buffer, expected);
1176        assert_eq!(buffer.len(), 17);
1177        Ok(())
1178    }
1179
1180    /// Test LIST_8 boundary (length 255)
1181    #[test]
1182    fn test_list_size_list8_boundary() -> TestResult {
1183        let mut buffer = Vec::new();
1184        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1185
1186        // LIST_8 should be used for lengths 1-255
1187        encoder.write_list_start(255)?;
1188
1189        // Expected: LIST_8 (248), then length 255
1190        assert_eq!(buffer[1], token::LIST_8);
1191        assert_eq!(buffer[2], 255);
1192        Ok(())
1193    }
1194
1195    /// Test LIST_16 boundary (length 256)
1196    #[test]
1197    fn test_list_size_list16_boundary() -> TestResult {
1198        let mut buffer = Vec::new();
1199        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1200
1201        // LIST_16 should be used for lengths 256+
1202        encoder.write_list_start(256)?;
1203
1204        // Expected: LIST_16 (249), then length as u16 big-endian
1205        assert_eq!(buffer[1], token::LIST_16);
1206        assert_eq!(buffer[2], 0x01); // 256 >> 8
1207        assert_eq!(buffer[3], 0x00); // 256 & 0xFF
1208        Ok(())
1209    }
1210
1211    /// Test empty list encoding
1212    #[test]
1213    fn test_list_size_empty() -> TestResult {
1214        let mut buffer = Vec::new();
1215        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1216
1217        encoder.write_list_start(0)?;
1218
1219        // Empty list uses LIST_EMPTY token
1220        assert_eq!(buffer[1], token::LIST_EMPTY);
1221        Ok(())
1222    }
1223
1224    /// Test hex packing validation
1225    #[test]
1226    fn test_hex_validation() {
1227        // Valid hex strings (uppercase A-F, digits 0-9)
1228        assert!(validate_hex("0123456789ABCDEF"));
1229        assert!(validate_hex("DEADBEEF"));
1230        assert!(validate_hex("1234"));
1231
1232        // Invalid: lowercase letters
1233        assert!(!validate_hex("abcdef"));
1234        assert!(!validate_hex("DeadBeef"));
1235
1236        // Invalid: special characters
1237        assert!(!validate_hex("-"));
1238        assert!(!validate_hex("."));
1239        assert!(!validate_hex(" "));
1240
1241        // Empty string is valid (but will be encoded as regular string)
1242        assert!(validate_hex(""));
1243    }
1244
1245    /// Test nibble packing validation
1246    #[test]
1247    fn test_nibble_validation() {
1248        // Valid nibble strings: digits, dash, dot
1249        assert!(validate_nibble("0123456789"));
1250        assert!(validate_nibble("-"));
1251        assert!(validate_nibble("."));
1252        assert!(validate_nibble("123-456.789"));
1253
1254        // Invalid: letters
1255        assert!(!validate_nibble("abc"));
1256        assert!(!validate_nibble("123abc"));
1257
1258        // Invalid: uppercase letters
1259        assert!(!validate_nibble("ABC"));
1260
1261        // Invalid: special characters other than - and .
1262        assert!(!validate_nibble("123!456"));
1263        assert!(!validate_nibble("@"));
1264    }
1265
1266    /// Test BINARY_8, BINARY_20, BINARY_32 boundary transitions
1267    #[test]
1268    fn test_binary_length_boundaries() -> TestResult {
1269        // BINARY_8: length < 256
1270        let short_data = vec![0x42; 255];
1271        let mut buffer = Vec::new();
1272        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1273        encoder.write_bytes_with_len(&short_data)?;
1274        assert_eq!(buffer[1], token::BINARY_8);
1275        assert_eq!(buffer[2], 255);
1276
1277        // BINARY_20: 256 <= length < 2^20
1278        let medium_data = vec![0x42; 256];
1279        let mut buffer = Vec::new();
1280        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1281        encoder.write_bytes_with_len(&medium_data)?;
1282        assert_eq!(buffer[1], token::BINARY_20);
1283        // 256 in u20 big-endian: 0x00, 0x01, 0x00
1284        assert_eq!(buffer[2], 0x00);
1285        assert_eq!(buffer[3], 0x01);
1286        assert_eq!(buffer[4], 0x00);
1287
1288        Ok(())
1289    }
1290
1291    /// Test node with many children uses correct list encoding
1292    #[test]
1293    fn test_node_with_255_children() -> TestResult {
1294        let children: Vec<Node> = (0..255)
1295            .map(|_| Node::new("child", Attrs::new(), None))
1296            .collect();
1297
1298        let parent = Node::new("parent", Attrs::new(), Some(NodeContent::Nodes(children)));
1299
1300        let mut buffer = Vec::new();
1301        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1302        encoder.write_node(&parent)?;
1303
1304        // Should encode successfully with LIST_8 for children
1305        assert!(!buffer.is_empty());
1306        Ok(())
1307    }
1308
1309    /// Test node with 256 children uses LIST_16
1310    #[test]
1311    fn test_node_with_256_children() -> TestResult {
1312        let children: Vec<Node> = (0..256)
1313            .map(|_| Node::new("x", Attrs::new(), None))
1314            .collect();
1315
1316        let parent = Node::new("parent", Attrs::new(), Some(NodeContent::Nodes(children)));
1317
1318        let mut buffer = Vec::new();
1319        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1320        encoder.write_node(&parent)?;
1321
1322        // Should encode successfully with LIST_16 for children
1323        assert!(!buffer.is_empty());
1324        Ok(())
1325    }
1326
1327    /// Test string at PACKED_MAX boundary (127 chars)
1328    #[test]
1329    fn test_packed_max_boundary() {
1330        // Exactly PACKED_MAX characters should be valid for packing
1331        let max_nibble = "0".repeat(token::PACKED_MAX as usize);
1332        assert!(validate_nibble(&max_nibble));
1333
1334        // One more than PACKED_MAX should NOT be packed
1335        let over_max = "0".repeat(token::PACKED_MAX as usize + 1);
1336        assert!(!validate_nibble(&over_max));
1337    }
1338
1339    /// Test empty string encoding - should be BINARY_8 + 0, not just 0
1340    #[test]
1341    fn test_empty_string_encoding() -> TestResult {
1342        let mut buffer = Vec::new();
1343        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1344        encoder.write_string("")?;
1345
1346        // According to WhatsApp web protocol:
1347        // Empty string should be encoded as BINARY_8 (252) + 0
1348        // NOT as token 0 (LIST_EMPTY)
1349        println!("Empty string encoding: {:?}", &buffer[1..]);
1350        assert_eq!(
1351            buffer.len(),
1352            3,
1353            "Empty string should encode to 2 bytes (plus leading 0)"
1354        );
1355        assert_eq!(
1356            buffer[1],
1357            token::BINARY_8,
1358            "First byte should be BINARY_8 (252)"
1359        );
1360        assert_eq!(buffer[2], 0, "Second byte should be 0 (length)");
1361        Ok(())
1362    }
1363
1364    /// Test encode/decode round-trip for empty string in node attributes
1365    #[test]
1366    fn test_empty_string_roundtrip() -> TestResult {
1367        use crate::decoder::Decoder;
1368
1369        let mut attrs = Attrs::new();
1370        attrs.insert("key", ""); // Empty value
1371        attrs.insert("", "value"); // Empty key
1372
1373        let node = Node::new("test", attrs, Some(NodeContent::String("".into())));
1374
1375        let mut buffer = Vec::new();
1376        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1377        encoder.write_node(&node)?;
1378
1379        let mut decoder = Decoder::new(&buffer[1..]);
1380        let decoded = decoder.read_node_ref()?.to_owned();
1381
1382        assert_eq!(decoded.tag, "test");
1383        assert_eq!(
1384            decoded.attrs.get("key"),
1385            Some(&NodeValue::String("".into()))
1386        );
1387        assert_eq!(
1388            decoded.attrs.get(""),
1389            Some(&NodeValue::String("value".into()))
1390        );
1391
1392        // Empty strings are encoded as BINARY_8 + 0, which decodes as empty bytes
1393        match &decoded.content {
1394            Some(NodeContent::Bytes(b)) => assert!(b.is_empty(), "Content should be empty bytes"),
1395            other => panic!("Expected empty bytes, got {:?}", other),
1396        }
1397        Ok(())
1398    }
1399
1400    /// Test the JID parsing optimization: short JIDs should still be parsed,
1401    /// while long strings should be encoded as raw bytes.
1402    #[test]
1403    fn test_jid_length_heuristic() -> TestResult {
1404        use crate::decoder::Decoder;
1405        use crate::token;
1406
1407        // Short JID: should be encoded as a JID token (48 bytes or less)
1408        let short_jid = "user@s.whatsapp.net";
1409        let mut buffer = Vec::new();
1410        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1411        encoder.write_string(short_jid)?;
1412
1413        // JID_PAIR token indicates JID encoding was used
1414        assert_eq!(
1415            buffer[1],
1416            token::JID_PAIR,
1417            "Short JID should be encoded as JID_PAIR token"
1418        );
1419
1420        // Long string (> 48 chars): should be encoded as raw bytes, not as JID
1421        let long_text = "x".repeat(300) + "@s.whatsapp.net";
1422        let mut buffer = Vec::new();
1423        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1424        encoder.write_string(&long_text)?;
1425
1426        // BINARY_20 token indicates raw bytes encoding (length > 255)
1427        assert_eq!(
1428            buffer[1],
1429            token::BINARY_20,
1430            "Long string should be encoded as BINARY_20, not as JID"
1431        );
1432
1433        // Verify round-trip for long string
1434        let node = Node::new(
1435            "msg",
1436            Attrs::new(),
1437            Some(NodeContent::String(long_text.as_str().into())),
1438        );
1439        let mut buffer = Vec::new();
1440        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1441        encoder.write_node(&node)?;
1442
1443        let mut decoder = Decoder::new(&buffer[1..]);
1444        let decoded = decoder.read_node_ref()?.to_owned();
1445        match &decoded.content {
1446            Some(NodeContent::Bytes(b)) => {
1447                assert_eq!(
1448                    String::from_utf8_lossy(b),
1449                    long_text,
1450                    "Long string should round-trip correctly"
1451                );
1452            }
1453            other => panic!("Expected bytes content, got {:?}", other),
1454        }
1455
1456        Ok(())
1457    }
1458
1459    #[test]
1460    fn test_jid_parser_preserves_non_numeric_device_suffix() -> TestResult {
1461        use crate::decoder::Decoder;
1462
1463        let value = "foo:bar@s.whatsapp.net";
1464        let node = Node::new("msg", Attrs::new(), Some(NodeContent::String(value.into())));
1465
1466        let mut buffer = Vec::new();
1467        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1468        encoder.write_node(&node)?;
1469
1470        let mut decoder = Decoder::new(&buffer[1..]);
1471        let decoded = decoder.read_node_ref()?.to_owned();
1472        match decoded.content {
1473            Some(NodeContent::String(s)) => assert_eq!(s, value),
1474            other => panic!("Expected string content, got {:?}", other),
1475        }
1476        Ok(())
1477    }
1478
1479    #[test]
1480    fn test_jid_parser_preserves_non_numeric_agent_suffix() -> TestResult {
1481        use crate::decoder::Decoder;
1482
1483        let value = "hello_world@s.whatsapp.net";
1484        let node = Node::new("msg", Attrs::new(), Some(NodeContent::String(value.into())));
1485
1486        let mut buffer = Vec::new();
1487        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1488        encoder.write_node(&node)?;
1489
1490        let mut decoder = Decoder::new(&buffer[1..]);
1491        let decoded = decoder.read_node_ref()?.to_owned();
1492        match decoded.content {
1493            Some(NodeContent::String(s)) => assert_eq!(s, value),
1494            other => panic!("Expected string content, got {:?}", other),
1495        }
1496        Ok(())
1497    }
1498
1499    /// Regression test: AD_JID domain_type must be derived from the server field,
1500    /// not from jid.agent.
1501    ///
1502    /// The binary AD_JID format is: [0xF7] [domain_type] [device] [user_string]
1503    /// where domain_type encodes the server: 0=s.whatsapp.net, 1=lid, 128=hosted.
1504    ///
1505    /// A previous bug wrote `jid.agent` (always 0) instead of the domain_type,
1506    /// causing LID JIDs to be encoded as s.whatsapp.net JIDs. The real WhatsApp
1507    /// server rejected these with error 421, while our mock server accepted them
1508    /// because it doesn't validate domain_type — hence e2e tests didn't catch it.
1509    #[test]
1510    fn test_ad_jid_domain_type_lid() -> TestResult {
1511        // Encode a LID device JID as a node attribute
1512        let lid_jid = Jid::lid_device("236395184570386", 39);
1513        let node = NodeBuilder::new("to").attr("jid", lid_jid).build();
1514
1515        let mut buffer = Vec::new();
1516        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1517        encoder.write_node(&node)?;
1518
1519        // Find the AD_JID marker (0xF7 = 247) in the encoded bytes
1520        let ad_jid_pos = buffer
1521            .iter()
1522            .position(|&b| b == token::AD_JID)
1523            .expect("AD_JID token (0xF7) must be present for device JID");
1524
1525        // Byte after AD_JID is domain_type: must be 1 for "lid"
1526        let domain_type = buffer[ad_jid_pos + 1];
1527        assert_eq!(
1528            domain_type, 1,
1529            "LID JID must encode domain_type=1 (lid), got {domain_type} (0=whatsapp, 128=hosted)"
1530        );
1531
1532        // Byte after domain_type is device
1533        let device = buffer[ad_jid_pos + 2];
1534        assert_eq!(device, 39, "Device byte must be 39");
1535
1536        Ok(())
1537    }
1538
1539    #[test]
1540    fn test_ad_jid_domain_type_whatsapp() -> TestResult {
1541        let pn_jid = Jid::pn_device("551199887766", 33);
1542        let node = NodeBuilder::new("to").attr("jid", pn_jid).build();
1543
1544        let mut buffer = Vec::new();
1545        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1546        encoder.write_node(&node)?;
1547
1548        let ad_jid_pos = buffer
1549            .iter()
1550            .position(|&b| b == token::AD_JID)
1551            .expect("AD_JID token must be present for device JID");
1552
1553        let domain_type = buffer[ad_jid_pos + 1];
1554        assert_eq!(
1555            domain_type, 0,
1556            "s.whatsapp.net JID must encode domain_type=0, got {domain_type}"
1557        );
1558
1559        Ok(())
1560    }
1561
1562    #[test]
1563    fn test_ad_jid_domain_type_whatsapp_ignores_hidden_agent() -> TestResult {
1564        use crate::decoder::Decoder;
1565
1566        let mut pn_jid = Jid::pn_device("551199887766", 33);
1567        pn_jid.agent = 2;
1568        let node = NodeBuilder::new("to").attr("jid", pn_jid.clone()).build();
1569
1570        let mut buffer = Vec::new();
1571        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1572        encoder.write_node(&node)?;
1573
1574        let ad_jid_pos = buffer
1575            .iter()
1576            .position(|&b| b == token::AD_JID)
1577            .expect("AD_JID token must be present for device JID");
1578
1579        assert_eq!(
1580            buffer[ad_jid_pos + 1],
1581            0,
1582            "PN JID must encode the WA Web domain_type=0 even if a hidden agent is present"
1583        );
1584
1585        let decoded = Decoder::new(&buffer[1..]).read_node_ref()?.to_owned();
1586        let decoded_jid = decoded
1587            .attrs()
1588            .optional_jid("jid")
1589            .expect("jid attr must decode");
1590        assert!(pn_jid.is_same_chat_as(&decoded_jid));
1591        assert_eq!(decoded_jid.agent, 0);
1592
1593        Ok(())
1594    }
1595
1596    /// Verify that string-encoded JIDs and direct Jid-encoded JIDs produce
1597    /// identical bytes AND decode back to the same JID. This catches any
1598    /// divergence between the two encoding paths (root cause of the domain_type
1599    /// bug) and ensures encode→decode round-trip fidelity for all server types.
1600    #[test]
1601    fn test_jid_string_vs_direct_encoding_matches() -> TestResult {
1602        use crate::decoder::Decoder;
1603
1604        let test_cases: Vec<Jid> = vec![
1605            Jid::lid_device("236395184570386", 39),     // LID with device
1606            Jid::pn_device("551199887766", 33),         // PN with device
1607            Jid::lid("236395184570386"),                // LID primary (device 0)
1608            Jid::pn("551199887766"),                    // PN primary (device 0)
1609            "5511999887766:99@hosted".parse().unwrap(), // HOSTED device
1610            "100000012345678:99@hosted.lid".parse().unwrap(), // HOSTED_LID device
1611        ];
1612
1613        for jid in test_cases {
1614            // Path 1: string encoding (known correct — uses parse_jid_meta)
1615            let node_str = NodeBuilder::new("to").attr("jid", jid.to_string()).build();
1616
1617            // Path 2: direct Jid encoding (uses write_jid_owned)
1618            let node_jid = NodeBuilder::new("to").attr("jid", jid.clone()).build();
1619
1620            let mut buf_str = Vec::new();
1621            Encoder::new(Cursor::new(&mut buf_str))?.write_node(&node_str)?;
1622
1623            let mut buf_jid = Vec::new();
1624            Encoder::new(Cursor::new(&mut buf_jid))?.write_node(&node_jid)?;
1625
1626            assert_eq!(
1627                buf_str, buf_jid,
1628                "String vs direct Jid encoding must produce identical bytes for {jid}"
1629            );
1630
1631            // Round-trip: decode the encoded bytes and verify the JID is preserved.
1632            // Skip version byte (first byte) then decode.
1633            let mut decoder = Decoder::new(&buf_jid[1..]);
1634            let decoded_node = decoder.read_node_ref()?.to_owned();
1635            let decoded_jid: Jid = decoded_node
1636                .attrs()
1637                .optional_jid("jid")
1638                .expect("jid attr must round-trip as JID");
1639
1640            assert_eq!(
1641                jid.user, decoded_jid.user,
1642                "Round-trip user mismatch for {jid}"
1643            );
1644            assert_eq!(
1645                jid.device, decoded_jid.device,
1646                "Round-trip device mismatch for {jid}"
1647            );
1648            assert_eq!(
1649                jid.server, decoded_jid.server,
1650                "Round-trip server mismatch for {jid}"
1651            );
1652        }
1653
1654        Ok(())
1655    }
1656
1657    /// Pin domain_type for direct-constructed Hosted/HostedLid JIDs (default
1658    /// `agent=0`); pre-#391 these encoded as `0` instead of `128`/`129`.
1659    #[test]
1660    fn test_direct_constructed_hosted_encodes_correct_domain_type() -> TestResult {
1661        let mut hosted = Jid::new("100000000000001", jid::Server::Hosted);
1662        hosted.device = 99;
1663        assert_eq!(
1664            hosted.agent, 0,
1665            "default agent for direct construction is 0"
1666        );
1667
1668        let mut hosted_lid = Jid::new("100000000000002", jid::Server::HostedLid);
1669        hosted_lid.device = 99;
1670        assert_eq!(hosted_lid.agent, 0);
1671
1672        for (jid, expected) in [(&hosted, 128u8), (&hosted_lid, 129u8)] {
1673            let node = NodeBuilder::new("to").attr("jid", jid.clone()).build();
1674            let mut buf = Vec::new();
1675            Encoder::new(Cursor::new(&mut buf))?.write_node(&node)?;
1676
1677            let pos = buf
1678                .iter()
1679                .position(|&b| b == token::AD_JID)
1680                .expect("AD_JID marker present");
1681            assert_eq!(
1682                buf[pos + 1],
1683                expected,
1684                "direct-constructed {jid} must emit domain_type {expected} \
1685                 (pre-#391 would have emitted agent=0)"
1686            );
1687        }
1688        Ok(())
1689    }
1690
1691    /// Regression test: strings at the PACKED_MAX boundary must be classified
1692    /// normally, while strings above it must be emitted as raw bytes (skipping
1693    /// SipHash/PHF classification entirely).
1694    #[test]
1695    fn test_long_string_skips_classification() -> TestResult {
1696        use crate::decoder::Decoder;
1697        use crate::marshal::marshal;
1698
1699        let at_boundary = "0".repeat(token::PACKED_MAX as usize); // 127 nibble chars
1700        let over_boundary = "0".repeat(token::PACKED_MAX as usize + 1); // 128 chars
1701
1702        // 127-char all-digit string is nibble-packable
1703        let node_at = Node::new(
1704            "test",
1705            Attrs::new(),
1706            Some(NodeContent::String(at_boundary.as_str().into())),
1707        );
1708        let encoded_at = marshal(&node_at)?;
1709
1710        // 128-char string must be emitted as raw bytes (BINARY_8 + length)
1711        let node_over = Node::new(
1712            "test",
1713            Attrs::new(),
1714            Some(NodeContent::String(over_boundary.as_str().into())),
1715        );
1716        let encoded_over = marshal(&node_over)?;
1717
1718        // The 127-char string should be packed (shorter encoding than raw)
1719        assert!(
1720            encoded_at.len() < encoded_over.len(),
1721            "127-char nibble string should pack smaller than 128-char raw: {} vs {}",
1722            encoded_at.len(),
1723            encoded_over.len(),
1724        );
1725
1726        // The 128-char content must be encoded as BINARY_8 + 128 (raw bytes).
1727        // Find the [BINARY_8, 128] pair — the first BINARY_8 is for the tag "test".
1728        let has_raw_128 = encoded_over
1729            .windows(2)
1730            .any(|w| w[0] == token::BINARY_8 && w[1] == 128);
1731        assert!(
1732            has_raw_128,
1733            "128-char string must contain BINARY_8 + length=128 sequence"
1734        );
1735
1736        // Both must round-trip correctly (skip version byte at [0])
1737        let decoded_at = Decoder::new(&encoded_at[1..]).read_node_ref()?.to_owned();
1738        let decoded_over = Decoder::new(&encoded_over[1..]).read_node_ref()?.to_owned();
1739
1740        match &decoded_at.content {
1741            Some(NodeContent::String(s)) => assert_eq!(s.as_str(), at_boundary),
1742            Some(NodeContent::Bytes(b)) => {
1743                assert_eq!(std::str::from_utf8(b).unwrap(), at_boundary)
1744            }
1745            other => panic!("Expected string/bytes content, got {:?}", other),
1746        }
1747        match &decoded_over.content {
1748            Some(NodeContent::Bytes(b)) => {
1749                assert_eq!(std::str::from_utf8(b).unwrap(), over_boundary)
1750            }
1751            other => panic!(
1752                "Expected bytes content for 128-char string, got {:?}",
1753                other
1754            ),
1755        }
1756
1757        Ok(())
1758    }
1759
1760    /// Regression: AD_JID only round-trips for the 4 servers whose domain_type
1761    /// the decoder maps back (Pn/Lid/Hosted/HostedLid). Anything else
1762    /// (bot/group/broadcast/newsletter/...) must go through JID_PAIR so the
1763    /// server string survives. Matches whatsmeow `writeJID` and WA Web
1764    /// `WAWap.De` (`WapJid.create` for non-AD-capable servers).
1765    #[test]
1766    fn test_bot_jid_with_device_round_trips_via_jid_pair() -> TestResult {
1767        use crate::decoder::Decoder;
1768
1769        for value in [
1770            "867051314767696@bot",
1771            "867051314767696:0@bot",
1772            "120363021033254949@g.us",
1773            "12345@broadcast",
1774            "12345@newsletter",
1775        ] {
1776            let node = NodeBuilder::new("msg").attr("from", value).build();
1777
1778            let mut buffer = Vec::new();
1779            let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1780            encoder.write_node(&node)?;
1781
1782            // AD_JID (0xF7) must NOT appear for any of these — they use JID_PAIR
1783            // (0xF8) or raw bytes.
1784            assert!(
1785                !buffer.contains(&token::AD_JID),
1786                "AD_JID must not be emitted for {value} (would lose the server)"
1787            );
1788
1789            let decoded = Decoder::new(&buffer[1..]).read_node_ref()?.to_owned();
1790            let from_attr = decoded
1791                .attrs
1792                .get("from")
1793                .expect("from attr must survive the round-trip");
1794            let got = from_attr.to_string();
1795            // device :0 is equivalent to no device for these servers; either
1796            // form is acceptable as long as the server is preserved.
1797            let expected_user_server = value.split(':').next().unwrap_or(value);
1798            let expected_server = value.split('@').nth(1).unwrap();
1799            assert!(
1800                got.ends_with(&format!("@{expected_server}")),
1801                "round-trip lost the server for {value}: got {got}",
1802            );
1803            assert!(
1804                got.starts_with(expected_user_server.split('@').next().unwrap())
1805                    || got.starts_with(value.split('@').next().unwrap()),
1806                "round-trip lost the user for {value}: got {got}",
1807            );
1808        }
1809        Ok(())
1810    }
1811
1812    /// `@call` must round-trip via JID_PAIR instead of failing the whole node decode.
1813    #[test]
1814    fn test_call_jid_round_trips_via_jid_pair() -> TestResult {
1815        use crate::decoder::Decoder;
1816
1817        let node = NodeBuilder::new("call").attr("from", "12345@call").build();
1818        let mut buffer = Vec::new();
1819        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1820        encoder.write_node(&node)?;
1821        assert!(
1822            !buffer.contains(&token::AD_JID),
1823            "AD_JID must not be emitted for @call (would lose the server)"
1824        );
1825
1826        let decoded = Decoder::new(&buffer[1..]).read_node_ref()?.to_owned();
1827        let from = decoded
1828            .attrs
1829            .get("from")
1830            .expect("from attr must survive the round-trip");
1831        assert_eq!(from.to_string(), "12345@call");
1832        Ok(())
1833    }
1834
1835    /// The AD form spends a single byte on the device, so a PN/LID device past
1836    /// 255 has nowhere to go and the encoder says so instead of truncating it
1837    /// into a different device. Interop carries its own `u16` device field and
1838    /// is unaffected, which is why the limit cannot live on `Jid` itself.
1839    #[test]
1840    fn ad_jid_device_is_one_byte_wide_unlike_interop() -> TestResult {
1841        let encode = |jid: Jid| -> Result<()> {
1842            let node = NodeBuilder::new("msg").attr("from", jid).build();
1843            let mut buffer = Vec::new();
1844            let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1845            encoder.write_node(&node)
1846        };
1847
1848        encode(Jid::pn_device("5511987650001", 255)).expect("255 is the widest AD device");
1849        let err = encode(Jid::pn_device("5511987650001", 256))
1850            .expect_err("256 does not fit the AD device byte");
1851        assert!(
1852            err.to_string().contains("out of range"),
1853            "the error must name the device, got {err}"
1854        );
1855
1856        let interop = Jid {
1857            user: "5511987650001".into(),
1858            server: jid::Server::Interop,
1859            agent: 0,
1860            device: 65535,
1861            integrator: 7,
1862        };
1863        encode(interop).expect("interop spends a full u16 on the device");
1864        Ok(())
1865    }
1866
1867    /// Same invariant as above but exercised through the typed
1868    /// `NodeValue::Jid` path (write_jid_owned + size estimators), which
1869    /// previously ignored the server check and emitted AD_JID for any
1870    /// device > 0 — silently mapping the server back to Pn on decode.
1871    #[test]
1872    fn test_typed_non_ad_jid_with_device_round_trips_via_jid_pair() -> TestResult {
1873        use crate::decoder::Decoder;
1874        use std::str::FromStr;
1875
1876        for value in [
1877            // Bot devices, broadcast/newsletter with explicit device — all
1878            // non-AD-capable servers. The decoder cannot recover the server
1879            // from the AD_JID domain_type, so the encoder must avoid AD_JID.
1880            "867051314767696:0@bot",
1881            "12345:5@broadcast",
1882            "67890:9@newsletter",
1883        ] {
1884            let jid = Jid::from_str(value)?;
1885            let node = NodeBuilder::new("msg").attr("from", jid.clone()).build();
1886
1887            let mut buffer = Vec::new();
1888            let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
1889            encoder.write_node(&node)?;
1890
1891            assert!(
1892                !buffer.contains(&token::AD_JID),
1893                "typed JID {value} must NOT emit AD_JID (decoder would drop the server)"
1894            );
1895
1896            let decoded = Decoder::new(&buffer[1..]).read_node_ref()?.to_owned();
1897            let from = decoded
1898                .attrs
1899                .get("from")
1900                .expect("from attr must survive round-trip")
1901                .to_jid()
1902                .expect("from attr decodes back to a Jid");
1903            assert_eq!(
1904                from.server, jid.server,
1905                "round-trip lost the server for typed {value}"
1906            );
1907            assert_eq!(
1908                from.user, jid.user,
1909                "round-trip lost the user for typed {value}"
1910            );
1911        }
1912        Ok(())
1913    }
1914}