Skip to main content

wacore_binary/
node.rs

1use crate::attrs::{AttrParser, AttrParserRef};
2use crate::jid::{Jid, JidRef};
3use crate::token;
4use bytes::Bytes;
5use compact_str::CompactString;
6use stable_deref_trait::StableDeref;
7use std::borrow::Cow;
8
9/// Borrowed-or-inline string for decoded nodes. Short owned values (≤24 bytes)
10/// are stored inline via `CompactString`, avoiding heap allocation.
11#[derive(Clone, yoke_derive::Yokeable)]
12pub enum NodeStr<'a> {
13    Borrowed(&'a str),
14    Owned(CompactString),
15}
16
17impl NodeStr<'_> {
18    /// Clone-preserving conversion. Avoids re-parsing the inner CompactString
19    /// when converting owned NodeStr values in `to_owned()` paths.
20    #[inline]
21    pub fn to_compact_string(&self) -> CompactString {
22        match self {
23            NodeStr::Borrowed(s) => CompactString::from(*s),
24            NodeStr::Owned(cs) => cs.clone(),
25        }
26    }
27}
28
29impl Default for NodeStr<'_> {
30    #[inline]
31    fn default() -> Self {
32        NodeStr::Borrowed("")
33    }
34}
35
36impl std::ops::Deref for NodeStr<'_> {
37    type Target = str;
38    #[inline(always)]
39    fn deref(&self) -> &str {
40        match self {
41            NodeStr::Borrowed(s) => s,
42            NodeStr::Owned(cs) => cs.as_str(),
43        }
44    }
45}
46
47impl AsRef<str> for NodeStr<'_> {
48    #[inline(always)]
49    fn as_ref(&self) -> &str {
50        self
51    }
52}
53
54impl fmt::Debug for NodeStr<'_> {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        fmt::Debug::fmt(&**self, f)
57    }
58}
59
60impl fmt::Display for NodeStr<'_> {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str(self)
63    }
64}
65
66#[cfg(feature = "serde")]
67impl serde::Serialize for NodeStr<'_> {
68    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
69        serializer.serialize_str(self)
70    }
71}
72
73impl PartialEq for NodeStr<'_> {
74    #[inline]
75    fn eq(&self, other: &Self) -> bool {
76        **self == **other
77    }
78}
79
80impl Eq for NodeStr<'_> {}
81
82impl std::hash::Hash for NodeStr<'_> {
83    #[inline]
84    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
85        (**self).hash(state)
86    }
87}
88
89impl PartialEq<str> for NodeStr<'_> {
90    #[inline]
91    fn eq(&self, other: &str) -> bool {
92        &**self == other
93    }
94}
95
96impl PartialEq<&str> for NodeStr<'_> {
97    #[inline]
98    fn eq(&self, other: &&str) -> bool {
99        &**self == *other
100    }
101}
102
103impl<'a> From<&'a str> for NodeStr<'a> {
104    #[inline]
105    fn from(s: &'a str) -> Self {
106        NodeStr::Borrowed(s)
107    }
108}
109
110impl From<CompactString> for NodeStr<'_> {
111    #[inline]
112    fn from(s: CompactString) -> Self {
113        NodeStr::Owned(s)
114    }
115}
116
117/// Intern a string as a `Cow::Borrowed(&'static str)` if it matches a known token,
118/// otherwise allocate a `Cow::Owned(String)`. This avoids heap allocations for the
119/// vast majority of tag names and attribute keys which are protocol tokens.
120#[inline]
121fn intern_cow(s: &str) -> Cow<'static, str> {
122    if let Some(kind) = token::index_of_token(s) {
123        let interned = match kind {
124            token::TokenKind::Single(idx) => token::get_single_token(idx),
125            token::TokenKind::Double(dict, idx) => token::get_double_token(dict, idx),
126        };
127        if let Some(token) = interned {
128            return Cow::Borrowed(token);
129        }
130    }
131    Cow::Owned(s.to_string())
132}
133
134/// An owned attribute value that can be either a string or a structured JID.
135/// This avoids string allocation for JID attributes by storing the JID directly,
136/// eliminating format/parse overhead when routing logic needs the JID.
137#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
138#[derive(Debug, Clone, PartialEq)]
139pub enum NodeValue {
140    String(CompactString),
141    Jid(Jid),
142}
143
144impl Default for NodeValue {
145    fn default() -> Self {
146        NodeValue::String(CompactString::default())
147    }
148}
149
150impl NodeValue {
151    /// String view of the value. Works for both variants.
152    /// - String variant: Cow::Borrowed(&str) — zero copy
153    /// - Jid variant: Cow::Owned(formatted) — allocates only when needed
154    #[inline]
155    pub fn as_str(&self) -> Cow<'_, str> {
156        match self {
157            NodeValue::String(s) => Cow::Borrowed(s.as_str()),
158            NodeValue::Jid(j) => Cow::Owned(j.to_string()),
159        }
160    }
161
162    /// Convert to an owned Jid, parsing from string if necessary.
163    #[inline]
164    pub fn to_jid(&self) -> Option<Jid> {
165        match self {
166            NodeValue::Jid(j) => Some(j.clone()),
167            NodeValue::String(s) => s.parse().ok(),
168        }
169    }
170}
171
172use std::fmt;
173
174impl fmt::Display for NodeValue {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        match self {
177            NodeValue::String(s) => write!(f, "{}", s),
178            NodeValue::Jid(j) => write!(f, "{}", j),
179        }
180    }
181}
182
183impl PartialEq<str> for NodeValue {
184    fn eq(&self, other: &str) -> bool {
185        match self {
186            NodeValue::String(s) => s == other,
187            NodeValue::Jid(j) => j.display_eq(other),
188        }
189    }
190}
191
192impl PartialEq<&str> for NodeValue {
193    fn eq(&self, other: &&str) -> bool {
194        self == *other
195    }
196}
197
198impl PartialEq<String> for NodeValue {
199    fn eq(&self, other: &String) -> bool {
200        self == other.as_str()
201    }
202}
203
204impl From<String> for NodeValue {
205    #[inline]
206    fn from(s: String) -> Self {
207        NodeValue::String(CompactString::from(s))
208    }
209}
210
211impl From<&str> for NodeValue {
212    #[inline]
213    fn from(s: &str) -> Self {
214        NodeValue::String(CompactString::from(s))
215    }
216}
217
218impl From<&String> for NodeValue {
219    #[inline]
220    fn from(s: &String) -> Self {
221        NodeValue::String(CompactString::from(s.as_str()))
222    }
223}
224
225impl From<CompactString> for NodeValue {
226    #[inline]
227    fn from(s: CompactString) -> Self {
228        NodeValue::String(s)
229    }
230}
231
232impl From<&CompactString> for NodeValue {
233    #[inline]
234    fn from(s: &CompactString) -> Self {
235        NodeValue::String(s.clone())
236    }
237}
238
239impl From<Jid> for NodeValue {
240    #[inline]
241    fn from(jid: Jid) -> Self {
242        NodeValue::Jid(jid)
243    }
244}
245
246impl From<&Jid> for NodeValue {
247    #[inline]
248    fn from(jid: &Jid) -> Self {
249        NodeValue::Jid(jid.clone())
250    }
251}
252
253macro_rules! impl_from_integer_for_nodevalue {
254    ($($t:ty),* $(,)?) => {
255        $(
256            impl From<$t> for NodeValue {
257                #[inline]
258                fn from(n: $t) -> Self {
259                    let mut buf = itoa::Buffer::new();
260                    NodeValue::String(CompactString::from(buf.format(n)))
261                }
262            }
263        )*
264    };
265}
266
267impl_from_integer_for_nodevalue!(
268    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize
269);
270
271impl From<bool> for NodeValue {
272    #[inline]
273    fn from(b: bool) -> Self {
274        NodeValue::String(CompactString::from(if b { "true" } else { "false" }))
275    }
276}
277
278/// Inline backing store for [`Attrs`]. A plain `Vec` paid one heap allocation
279/// per node on the encode hot path just for the backing buffer. Capacity 3 is
280/// the measured optimum: it is the width of the `<enc>` fanout node (`v`,
281/// `type`, `mediatype`), the highest-multiplicity node in a send, so a 64-device
282/// fanout keeps it inline and drops a fifth of its allocations and a sixth of
283/// its live bytes. Capacity 4 spares almost no further spills but widens `Node`
284/// enough that moving it through the builder costs 8% more instructions.
285pub type AttrsVec = smallvec::SmallVec<[(Cow<'static, str>, NodeValue); 3]>;
286
287/// A collection of node attributes stored as key-value pairs.
288/// Stored inline for small attribute counts for cache locality and to avoid a
289/// per-node heap allocation; see [`AttrsVec`].
290/// Values can be either strings or JIDs, avoiding stringification overhead for JID attributes.
291/// Keys use `Cow<'static, str>` to avoid heap allocation for compile-time-known strings
292/// (e.g., "type", "id", "to") which are the vast majority of attribute keys.
293#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
294#[derive(Debug, Clone, PartialEq, Default)]
295pub struct Attrs(pub AttrsVec);
296
297impl Attrs {
298    #[inline]
299    pub fn new() -> Self {
300        Self(AttrsVec::new())
301    }
302
303    #[inline]
304    pub fn with_capacity(capacity: usize) -> Self {
305        Self(AttrsVec::with_capacity(capacity))
306    }
307
308    /// Get a reference to the NodeValue for a key, or None if not found.
309    /// Uses linear search which is efficient for small attribute counts.
310    #[inline]
311    pub fn get(&self, key: &str) -> Option<&NodeValue> {
312        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
313    }
314
315    /// Check if a key exists.
316    #[inline]
317    pub fn contains_key(&self, key: &str) -> bool {
318        self.0.iter().any(|(k, _)| k == key)
319    }
320
321    /// Insert a key-value pair. If the key already exists, update the value.
322    #[inline]
323    pub fn insert(&mut self, key: impl Into<Cow<'static, str>>, value: impl Into<NodeValue>) {
324        let key = key.into();
325        let value = value.into();
326        if let Some(pos) = self.0.iter().position(|(k, _)| k == &key) {
327            self.0[pos].1 = value;
328        } else {
329            self.0.push((key, value));
330        }
331    }
332
333    #[inline]
334    pub fn len(&self) -> usize {
335        self.0.len()
336    }
337
338    #[inline]
339    pub fn is_empty(&self) -> bool {
340        self.0.is_empty()
341    }
342
343    /// Iterate over key-value pairs.
344    #[inline]
345    pub fn iter(&self) -> impl Iterator<Item = (&Cow<'static, str>, &NodeValue)> {
346        self.0.iter().map(|(k, v)| (k, v))
347    }
348
349    /// Push a key-value pair without checking for duplicates.
350    /// Use this when building from a known-unique source (e.g., decoding).
351    #[inline]
352    pub fn push(&mut self, key: impl Into<Cow<'static, str>>, value: impl Into<NodeValue>) {
353        self.0.push((key.into(), value.into()));
354    }
355
356    /// Push a NodeValue directly without conversion.
357    /// Slightly more efficient when you already have a NodeValue.
358    #[inline]
359    pub fn push_value(&mut self, key: impl Into<Cow<'static, str>>, value: NodeValue) {
360        self.0.push((key.into(), value));
361    }
362
363    /// Iterate over keys only.
364    #[inline]
365    pub fn keys(&self) -> impl Iterator<Item = &Cow<'static, str>> {
366        self.0.iter().map(|(k, _)| k)
367    }
368}
369
370/// Owned iterator implementation (consuming).
371impl IntoIterator for Attrs {
372    type Item = (Cow<'static, str>, NodeValue);
373    type IntoIter = smallvec::IntoIter<[(Cow<'static, str>, NodeValue); 3]>;
374
375    fn into_iter(self) -> Self::IntoIter {
376        self.0.into_iter()
377    }
378}
379
380/// Borrowed iterator implementation.
381impl<'a> IntoIterator for &'a Attrs {
382    type Item = (&'a Cow<'static, str>, &'a NodeValue);
383    type IntoIter = std::iter::Map<
384        std::slice::Iter<'a, (Cow<'static, str>, NodeValue)>,
385        fn(&'a (Cow<'static, str>, NodeValue)) -> (&'a Cow<'static, str>, &'a NodeValue),
386    >;
387
388    fn into_iter(self) -> Self::IntoIter {
389        self.0.iter().map(|(k, v)| (k, v))
390    }
391}
392
393impl FromIterator<(Cow<'static, str>, NodeValue)> for Attrs {
394    fn from_iter<I: IntoIterator<Item = (Cow<'static, str>, NodeValue)>>(iter: I) -> Self {
395        Self(iter.into_iter().collect())
396    }
397}
398/// Covariant attribute container for decoded nodes.
399///
400/// Uses `Box<[T]>` (16 bytes: ptr + len) instead of `Vec<T>` (24 bytes: ptr + len + cap)
401/// or inline storage (which inflated NodeRef size). Zero-attr nodes skip allocation
402/// entirely. The boxed slice is allocated once with exact size from the decoder.
403///
404/// Covariant in `'a` (both Box and slices are covariant), compatible with yoke::Yokeable.
405#[derive(Debug, Clone, yoke_derive::Yokeable)]
406pub enum AttrsRef<'a> {
407    Empty,
408    Slice(Box<[(NodeStr<'a>, ValueRef<'a>)]>),
409}
410
411impl PartialEq for AttrsRef<'_> {
412    fn eq(&self, other: &Self) -> bool {
413        self.as_slice() == other.as_slice()
414    }
415}
416
417impl<'a> AttrsRef<'a> {
418    /// Build from a pre-filled Vec. Preferred path from the decoder which
419    /// knows the exact attr count upfront.
420    pub fn from_vec(v: Vec<(NodeStr<'a>, ValueRef<'a>)>) -> Self {
421        if v.is_empty() {
422            Self::Empty
423        } else {
424            Self::Slice(v.into_boxed_slice())
425        }
426    }
427
428    #[inline]
429    pub fn len(&self) -> usize {
430        match self {
431            Self::Empty => 0,
432            Self::Slice(s) => s.len(),
433        }
434    }
435
436    #[inline]
437    pub fn is_empty(&self) -> bool {
438        self.as_slice().is_empty()
439    }
440
441    #[inline]
442    pub fn as_slice(&self) -> &[(NodeStr<'a>, ValueRef<'a>)] {
443        match self {
444            Self::Empty => &[],
445            Self::Slice(s) => s,
446        }
447    }
448
449    #[inline]
450    pub fn iter(&self) -> impl Iterator<Item = &(NodeStr<'a>, ValueRef<'a>)> {
451        self.as_slice().iter()
452    }
453}
454
455impl<'a> FromIterator<(NodeStr<'a>, ValueRef<'a>)> for AttrsRef<'a> {
456    fn from_iter<I: IntoIterator<Item = (NodeStr<'a>, ValueRef<'a>)>>(iter: I) -> Self {
457        Self::from_vec(iter.into_iter().collect())
458    }
459}
460
461/// A decoded attribute value that can be either a string or a structured JID.
462/// This avoids string allocation when decoding JID tokens - the JidRef is returned
463/// directly and only converted to a string when actually needed.
464#[derive(Debug, Clone, PartialEq, yoke_derive::Yokeable)]
465pub enum ValueRef<'a> {
466    String(NodeStr<'a>),
467    Jid(JidRef<'a>),
468}
469
470#[cfg(feature = "serde")]
471impl serde::Serialize for ValueRef<'_> {
472    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
473        match self {
474            ValueRef::String(s) => {
475                serializer.serialize_newtype_variant("NodeValue", 0, "String", &**s)
476            }
477            ValueRef::Jid(j) => serializer.serialize_newtype_variant("NodeValue", 1, "Jid", j),
478        }
479    }
480}
481
482impl<'a> ValueRef<'a> {
483    /// Encode this value directly to the binary encoder.
484    pub fn encode_value<W: crate::encoder::ByteWriter>(
485        &self,
486        encoder: &mut crate::encoder::Encoder<'_, W>,
487    ) -> crate::error::Result<()> {
488        match self {
489            ValueRef::String(s) => encoder.write_string(s),
490            ValueRef::Jid(jid) => encoder.write_jid_ref(jid),
491        }
492    }
493
494    /// String view of the value. Borrows from `self`.
495    /// - String variant: borrows the inner str — zero copy
496    /// - Jid variant: Cow::Owned — allocates only when needed
497    pub fn as_str(&self) -> Cow<'_, str> {
498        match self {
499            ValueRef::String(s) => Cow::Borrowed(s),
500            ValueRef::Jid(j) => Cow::Owned(j.to_string()),
501        }
502    }
503
504    /// Get the value as a JidRef, if it's a JID variant.
505    pub fn as_jid(&self) -> Option<&JidRef<'a>> {
506        match self {
507            ValueRef::Jid(j) => Some(j),
508            ValueRef::String(_) => None,
509        }
510    }
511
512    /// Convert to an owned Jid, parsing from string if necessary.
513    pub fn to_jid(&self) -> Option<Jid> {
514        match self {
515            ValueRef::Jid(j) => Some(j.to_owned()),
516            ValueRef::String(s) => Jid::from_str(s.as_ref()).ok(),
517        }
518    }
519
520    /// Convert to an owned NodeValue, preserving the variant (JID stays JID).
521    pub fn to_node_value(&self) -> NodeValue {
522        match self {
523            ValueRef::String(s) => NodeValue::String(s.to_compact_string()),
524            ValueRef::Jid(j) => NodeValue::Jid(j.to_owned()),
525        }
526    }
527}
528
529impl PartialEq<str> for ValueRef<'_> {
530    #[inline]
531    fn eq(&self, other: &str) -> bool {
532        match self {
533            ValueRef::String(value) => value == other,
534            ValueRef::Jid(value) => value.display_eq(other),
535        }
536    }
537}
538
539impl PartialEq<&str> for ValueRef<'_> {
540    #[inline]
541    fn eq(&self, other: &&str) -> bool {
542        self == *other
543    }
544}
545
546impl PartialEq<String> for ValueRef<'_> {
547    #[inline]
548    fn eq(&self, other: &String) -> bool {
549        self == other.as_str()
550    }
551}
552
553use std::str::FromStr;
554
555impl<'a> fmt::Display for ValueRef<'a> {
556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
557        match self {
558            ValueRef::String(s) => write!(f, "{}", s),
559            ValueRef::Jid(j) => write!(f, "{}", j),
560        }
561    }
562}
563
564pub type NodeVec<'a> = Vec<NodeRef<'a>>;
565
566#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
567#[derive(Debug, Clone, PartialEq)]
568pub enum NodeContent {
569    Bytes(Vec<u8>),
570    String(CompactString),
571    Nodes(Vec<Node>),
572}
573
574#[derive(Debug, Clone, PartialEq, yoke_derive::Yokeable)]
575pub enum NodeContentRef<'a> {
576    Bytes(Cow<'a, [u8]>),
577    String(NodeStr<'a>),
578    Nodes(Box<[NodeRef<'a>]>),
579}
580
581#[cfg(feature = "serde")]
582impl serde::Serialize for NodeContentRef<'_> {
583    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
584        match self {
585            NodeContentRef::Bytes(b) => {
586                serializer.serialize_newtype_variant("NodeContent", 0, "Bytes", b.as_ref())
587            }
588            NodeContentRef::String(s) => {
589                serializer.serialize_newtype_variant("NodeContent", 1, "String", &**s)
590            }
591            NodeContentRef::Nodes(nodes) => {
592                serializer.serialize_newtype_variant("NodeContent", 2, "Nodes", &**nodes)
593            }
594        }
595    }
596}
597
598impl NodeContent {
599    /// Convert an owned NodeContent to a borrowed NodeContentRef.
600    pub fn as_content_ref(&self) -> NodeContentRef<'_> {
601        match self {
602            NodeContent::Bytes(b) => NodeContentRef::Bytes(Cow::Borrowed(b)),
603            NodeContent::String(s) => NodeContentRef::String(NodeStr::Borrowed(s.as_str())),
604            NodeContent::Nodes(nodes) => {
605                let v: Vec<_> = nodes.iter().map(|n| n.as_node_ref()).collect();
606                NodeContentRef::Nodes(v.into_boxed_slice())
607            }
608        }
609    }
610}
611
612#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
613#[derive(Debug, Clone, PartialEq, Default)]
614pub struct Node {
615    pub tag: Cow<'static, str>,
616    pub attrs: Attrs,
617    pub content: Option<NodeContent>,
618}
619
620#[derive(Debug, Clone, PartialEq, yoke_derive::Yokeable)]
621pub struct NodeRef<'a> {
622    pub tag: NodeStr<'a>,
623    pub attrs: AttrsRef<'a>,
624    pub content: Option<NodeContentRef<'a>>,
625}
626
627impl Node {
628    pub fn new(
629        tag: impl Into<Cow<'static, str>>,
630        attrs: Attrs,
631        content: Option<NodeContent>,
632    ) -> Self {
633        Self {
634            tag: tag.into(),
635            attrs,
636            content,
637        }
638    }
639
640    /// Convert an owned Node to a borrowed NodeRef.
641    /// The returned NodeRef borrows from self.
642    pub fn as_node_ref(&self) -> NodeRef<'_> {
643        NodeRef {
644            tag: NodeStr::Borrowed(self.tag.as_ref()),
645            attrs: self
646                .attrs
647                .iter()
648                .map(|(k, v)| {
649                    let value_ref = match v {
650                        NodeValue::String(s) => ValueRef::String(NodeStr::Borrowed(s.as_str())),
651                        NodeValue::Jid(j) => ValueRef::Jid(JidRef {
652                            user: NodeStr::Borrowed(&j.user),
653                            server: j.server,
654                            agent: j.agent,
655                            device: j.device,
656                            integrator: j.integrator,
657                        }),
658                    };
659                    (NodeStr::Borrowed(k.as_ref()), value_ref)
660                })
661                .collect(),
662            content: self.content.as_ref().map(|c| c.as_content_ref()),
663        }
664    }
665
666    pub fn children(&self) -> Option<&[Node]> {
667        match &self.content {
668            Some(NodeContent::Nodes(nodes)) => Some(nodes),
669            _ => None,
670        }
671    }
672
673    pub fn attrs(&self) -> AttrParser<'_> {
674        AttrParser::new(self)
675    }
676
677    pub fn get_optional_child_by_tag<'a>(&'a self, tags: &[&str]) -> Option<&'a Node> {
678        let mut current_node = self;
679        for &tag in tags {
680            let children = current_node.children()?;
681            current_node = children.iter().find(|c| c.tag == tag)?;
682        }
683        Some(current_node)
684    }
685
686    pub fn get_children_by_tag<'a>(&'a self, tag: &'a str) -> impl Iterator<Item = &'a Node> {
687        // `unwrap_or_default` and not `into_iter().flatten()`: the absent case is
688        // already an empty slice, so flattening only buys a nested iterator whose
689        // state machine LLVM does not fold away on this hot traversal.
690        self.children()
691            .unwrap_or_default()
692            .iter()
693            .filter(move |c| c.tag == tag)
694    }
695
696    pub fn get_optional_child(&self, tag: &str) -> Option<&Node> {
697        self.children()
698            .and_then(|nodes| nodes.iter().find(|node| node.tag == tag))
699    }
700
701    /// Extract text content, handling both String and Bytes (lossy UTF-8).
702    pub fn content_as_string(&self) -> Option<CompactString> {
703        match &self.content {
704            Some(NodeContent::String(s)) => Some(s.clone()),
705            Some(NodeContent::Bytes(b)) => {
706                Some(CompactString::from(String::from_utf8_lossy(b).as_ref()))
707            }
708            _ => None,
709        }
710    }
711}
712
713/// Wrapper that serializes `AttrsRef` with the same newtype-struct framing
714/// that serde's derive produces for `Attrs(Vec<...>)`. Without this, binary
715/// formats (bincode, postcard, etc.) would see a bare sequence instead of a
716/// newtype struct wrapper.
717#[cfg(feature = "serde")]
718struct AttrsRefWrapper<'a, 'b>(&'b AttrsRef<'a>);
719
720#[cfg(feature = "serde")]
721impl serde::Serialize for AttrsRefWrapper<'_, '_> {
722    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
723        serializer.serialize_newtype_struct("Attrs", self.0.as_slice())
724    }
725}
726
727#[cfg(feature = "serde")]
728impl serde::Serialize for NodeRef<'_> {
729    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
730        use serde::ser::SerializeStruct;
731        let mut s = serializer.serialize_struct("Node", 3)?;
732        s.serialize_field("tag", &*self.tag)?;
733        s.serialize_field("attrs", &AttrsRefWrapper(&self.attrs))?;
734        s.serialize_field("content", &self.content)?;
735        s.end()
736    }
737}
738
739impl<'a> NodeRef<'a> {
740    /// Returns the node's tag.
741    #[inline]
742    pub fn tag(&self) -> &str {
743        self.tag.as_ref()
744    }
745
746    pub fn new(tag: NodeStr<'a>, attrs: AttrsRef<'a>, content: Option<NodeContentRef<'a>>) -> Self {
747        Self {
748            tag,
749            attrs,
750            content,
751        }
752    }
753
754    pub fn attrs(&self) -> AttrParserRef<'_> {
755        AttrParserRef::new(self)
756    }
757
758    pub fn children(&self) -> Option<&[NodeRef<'a>]> {
759        match self.content.as_ref() {
760            Some(NodeContentRef::Nodes(nodes)) => Some(nodes),
761            _ => None,
762        }
763    }
764
765    pub fn get_attr(&self, key: &str) -> Option<&ValueRef<'a>> {
766        self.attrs.iter().find(|(k, _)| k == key).map(|(_, v)| v)
767    }
768
769    pub fn attrs_iter(&self) -> impl Iterator<Item = (&NodeStr<'a>, &ValueRef<'a>)> {
770        self.attrs.iter().map(|(k, v)| (k, v))
771    }
772
773    pub fn get_optional_child_by_tag(&self, tags: &[&str]) -> Option<&NodeRef<'a>> {
774        let mut current_node = self;
775        for &tag in tags {
776            let children = current_node.children()?;
777            current_node = children.iter().find(|c| c.tag == tag)?;
778        }
779        Some(current_node)
780    }
781
782    pub fn get_children_by_tag<'b>(&'b self, tag: &'b str) -> impl Iterator<Item = &'b NodeRef<'a>>
783    where
784        'a: 'b,
785    {
786        self.children()
787            .unwrap_or_default()
788            .iter()
789            .filter(move |c| c.tag == tag)
790    }
791
792    pub fn get_optional_child(&self, tag: &str) -> Option<&NodeRef<'a>> {
793        self.children()
794            .and_then(|nodes| nodes.iter().find(|node| node.tag == tag))
795    }
796
797    /// Extract text content, handling both String and Bytes (lossy UTF-8).
798    pub fn content_as_string(&self) -> Option<CompactString> {
799        match self.content.as_ref() {
800            Some(NodeContentRef::String(s)) => Some(s.to_compact_string()),
801            Some(NodeContentRef::Bytes(b)) => Some(CompactString::from(
802                String::from_utf8_lossy(b.as_ref()).as_ref(),
803            )),
804            _ => None,
805        }
806    }
807
808    /// Zero-copy byte content, if this node has Bytes content.
809    pub fn content_bytes(&self) -> Option<&[u8]> {
810        match self.content.as_ref() {
811            Some(NodeContentRef::Bytes(b)) => Some(b.as_ref()),
812            _ => None,
813        }
814    }
815
816    /// Zero-copy string content, if this node has String content.
817    pub fn content_str(&self) -> Option<&str> {
818        match self.content.as_ref() {
819            Some(NodeContentRef::String(s)) => Some(s.as_ref()),
820            _ => None,
821        }
822    }
823
824    /// Child nodes from content, if this node has Nodes content.
825    /// Alias for `children()`.
826    #[inline]
827    pub fn content_nodes(&self) -> Option<&[NodeRef<'a>]> {
828        self.children()
829    }
830
831    pub fn to_owned(&self) -> Node {
832        Node {
833            tag: intern_cow(&self.tag),
834            attrs: self
835                .attrs
836                .iter()
837                .map(|(k, v)| {
838                    let value = match v {
839                        ValueRef::String(s) => NodeValue::String(s.to_compact_string()),
840                        ValueRef::Jid(j) => NodeValue::Jid(j.to_owned()),
841                    };
842                    (intern_cow(k), value)
843                })
844                .collect::<Attrs>(),
845            content: self.content.as_ref().map(|c| match c {
846                NodeContentRef::Bytes(b) => NodeContent::Bytes(b.to_vec()),
847                NodeContentRef::String(s) => NodeContent::String(s.to_compact_string()),
848                NodeContentRef::Nodes(nodes) => {
849                    NodeContent::Nodes(nodes.iter().map(|n| n.to_owned()).collect())
850                }
851            }),
852        }
853    }
854}
855
856// ---------------------------------------------------------------------------
857// OwnedNodeRef — self-referential zero-copy node via yoke
858// ---------------------------------------------------------------------------
859
860use yoke::Yoke;
861
862#[derive(Clone)]
863struct BytesCart(Bytes);
864
865impl std::ops::Deref for BytesCart {
866    type Target = [u8];
867
868    fn deref(&self) -> &Self::Target {
869        self.0.as_ref()
870    }
871}
872
873// SAFETY: `Bytes` points to immutable backing storage whose deref target
874// remains stable for the lifetime of the value, even when the wrapper moves.
875// Yoke requires this guarantee to retain decoded borrows while the cart moves.
876unsafe impl StableDeref for BytesCart {}
877
878/// A decoded node that owns its decompressed buffer. The inner `NodeRef`
879/// borrows string/byte payloads directly from the buffer, avoiding copies.
880/// Container allocations (attribute Vec, child Vec) still occur during decode.
881///
882/// Wrap in `Arc<OwnedNodeRef>` for cheap sharing across handlers.
883pub struct OwnedNodeRef {
884    inner: Yoke<NodeRef<'static>, BytesCart>,
885}
886
887impl OwnedNodeRef {
888    /// Decode a node from an owned buffer of node bytes: after decompression and
889    /// without the format byte, which [`unpack`](crate::util::unpack) strips.
890    /// A buffer that still carries it goes through `unpack` first.
891    pub fn new(buffer: impl Into<Bytes>) -> crate::error::Result<Self> {
892        let inner = Yoke::try_attach_to_cart(BytesCart(buffer.into()), |buf| {
893            crate::marshal::unmarshal_ref(buf)
894        })?;
895        Ok(Self { inner })
896    }
897
898    /// Access the borrowed node.
899    #[inline]
900    pub fn get(&self) -> &NodeRef<'_> {
901        self.inner.get()
902    }
903
904    /// Convert to an owned `Node`, cloning all data out of the buffer.
905    /// Use sparingly — this is the allocation path that yoke is designed to avoid.
906    pub fn to_owned_node(&self) -> Node {
907        self.inner.get().to_owned()
908    }
909
910    /// The whole backing buffer, verbatim: exactly what [`Self::new`] consumed.
911    ///
912    /// A refcount bump, not a copy — the yoke already retains this buffer, and
913    /// [`Self::slice_bytes`] hands out views into the same allocation.
914    ///
915    /// These are node bytes, so they are **not** a sendable frame: send paths
916    /// take a packed payload, one format byte in front of the node bytes, which
917    /// [`unpack`](crate::util::unpack) stripped on the way in. Put it back with
918    /// [`pack`](crate::util::pack) before forwarding these bytes anywhere that
919    /// expects marshal output.
920    ///
921    /// Re-encoding through [`marshal_ref`] is the alternative and a worse one
922    /// for anything that forwards a stanza onward — to another process, a
923    /// recording, a replay harness. Re-encoding costs a second pass and is only
924    /// faithful while the token dictionaries match the ones that decoded it;
925    /// these bytes stay true whatever the dictionaries do.
926    ///
927    /// [`marshal_ref`]: crate::marshal::marshal_ref
928    pub fn backing_bytes(&self) -> Bytes {
929        self.inner.backing_cart().0.clone()
930    }
931
932    /// Return a zero-copy `Bytes` sub-view for a slice that borrows from this
933    /// node's backing buffer. Panics if `slice` does not point within the buffer.
934    pub fn slice_bytes(&self, slice: &[u8]) -> Bytes {
935        if slice.is_empty() {
936            return Bytes::new();
937        }
938        let cart = &self.inner.backing_cart().0;
939        let base = cart.as_ptr() as usize;
940        let end = base + cart.len();
941        let ptr = slice.as_ptr() as usize;
942        assert!(
943            ptr >= base && ptr + slice.len() <= end,
944            "slice is not within the backing buffer"
945        );
946        let offset = ptr - base;
947        cart.slice(offset..offset + slice.len())
948    }
949
950    /// The tag name of this node.
951    #[inline]
952    pub fn tag(&self) -> &str {
953        &self.get().tag
954    }
955
956    /// Get an attribute parser for this node.
957    #[inline]
958    pub fn attrs(&self) -> AttrParserRef<'_> {
959        self.get().attrs()
960    }
961
962    /// Look up a single attribute by key.
963    #[inline]
964    pub fn get_attr(&self, key: &str) -> Option<&ValueRef<'_>> {
965        self.get().get_attr(key)
966    }
967
968    /// Get child nodes, if content is a node list.
969    #[inline]
970    pub fn children(&self) -> Option<&[NodeRef<'_>]> {
971        self.get().children()
972    }
973
974    /// Find a child node by tag.
975    #[inline]
976    pub fn get_optional_child(&self, tag: &str) -> Option<&NodeRef<'_>> {
977        self.get().get_optional_child(tag)
978    }
979
980    /// Find a child by traversing a path of tags.
981    #[inline]
982    pub fn get_optional_child_by_tag(&self, tags: &[&str]) -> Option<&NodeRef<'_>> {
983        self.get().get_optional_child_by_tag(tags)
984    }
985
986    /// Get children matching a tag.
987    #[inline]
988    pub fn get_children_by_tag<'b>(
989        &'b self,
990        tag: &'b str,
991    ) -> impl Iterator<Item = &'b NodeRef<'b>> {
992        self.get().get_children_by_tag(tag)
993    }
994
995    /// Zero-copy byte content, if this node has Bytes content.
996    #[inline]
997    pub fn content_bytes(&self) -> Option<&[u8]> {
998        self.get().content_bytes()
999    }
1000
1001    /// Zero-copy string content, if this node has String content.
1002    #[inline]
1003    pub fn content_str(&self) -> Option<&str> {
1004        self.get().content_str()
1005    }
1006
1007    /// Child nodes from content, if this node has Nodes content.
1008    #[inline]
1009    pub fn content_nodes(&self) -> Option<&[NodeRef<'_>]> {
1010        self.get().content_nodes()
1011    }
1012
1013    /// Extract text content, handling both String and Bytes (lossy UTF-8).
1014    #[inline]
1015    pub fn content_as_string(&self) -> Option<CompactString> {
1016        self.get().content_as_string()
1017    }
1018}
1019
1020#[cfg(test)]
1021mod attrs_capacity_tests {
1022    use super::*;
1023
1024    #[test]
1025    fn node_ref_tag_accessor_handles_borrowed_and_owned_tags() {
1026        let borrowed = NodeRef::new(NodeStr::Borrowed("body"), AttrsRef::Empty, None);
1027        let owned = NodeRef::new(NodeStr::Owned("body".into()), AttrsRef::Empty, None);
1028        assert_eq!(borrowed.tag(), "body");
1029        assert_eq!(owned.tag(), "body");
1030    }
1031
1032    fn node_with(n: usize) -> Node {
1033        const KEYS: [&str; 8] = ["to", "id", "type", "t", "edit", "phash", "count", "offline"];
1034        let mut attrs = Attrs::new();
1035        for (i, key) in KEYS.iter().take(n).enumerate() {
1036            attrs.push(
1037                Cow::Borrowed(*key),
1038                NodeValue::String(format!("v{i}").into()),
1039            );
1040        }
1041        Node::new("message", attrs, Some(NodeContent::String("body".into())))
1042    }
1043
1044    /// Capacity is invisible to the wire: every attribute count decodes back to
1045    /// what it was encoded from, on both sides of the inline/heap transition.
1046    #[test]
1047    fn every_attribute_count_survives_a_round_trip() {
1048        for n in 0..=8 {
1049            let node = node_with(n);
1050            let bytes = crate::marshal::marshal(&node).unwrap();
1051            let decoded = crate::marshal::unmarshal_ref(&bytes[1..])
1052                .unwrap()
1053                .to_owned();
1054            assert_eq!(decoded, node, "{n} attributes did not round-trip");
1055        }
1056    }
1057
1058    /// The inline/heap boundary, where an off-by-one in the capacity hides.
1059    #[test]
1060    fn the_inline_boundary_is_where_the_declaration_says_it_is() {
1061        assert!(!node_with(3).attrs.0.spilled(), "3 attrs must stay inline");
1062        assert!(node_with(4).attrs.0.spilled(), "4 attrs must spill");
1063    }
1064}
1065
1066#[cfg(test)]
1067mod value_ref_compare_tests {
1068    use super::*;
1069    use crate::jid::Server;
1070    use std::str::FromStr;
1071
1072    /// Callers compare a `ValueRef` against a literal to decide whether a
1073    /// stanza came from the server, so `v == needle` has to answer exactly what
1074    /// `v.as_str() == needle` answered — including for the server-only shape
1075    /// (`s.whatsapp.net`, no user), which is the one those checks actually use.
1076    #[test]
1077    fn comparing_a_jid_value_matches_comparing_its_rendered_form() {
1078        let jids = [
1079            "s.whatsapp.net",
1080            "5511999998888@s.whatsapp.net",
1081            "5511999998888:7@s.whatsapp.net",
1082            "5511999998888.2@s.whatsapp.net",
1083            "120363012345678901@g.us",
1084            "123456789012345@lid",
1085            "123456789012345:9@lid",
1086            "123456789.4:17@interop",
1087            "status@broadcast",
1088            "12345.6@hosted.lid",
1089        ];
1090        let needles = [
1091            "s.whatsapp.net",
1092            "5511999998888@s.whatsapp.net",
1093            "5511999998888:7@s.whatsapp.net",
1094            "123456789012345@lid",
1095            "",
1096            "not-a-jid",
1097        ];
1098
1099        for raw in jids {
1100            let owned = Jid::from_str(raw).unwrap_or_else(|e| panic!("{raw}: {e}"));
1101            let borrowed = ValueRef::Jid(JidRef {
1102                user: NodeStr::Borrowed(&owned.user),
1103                server: owned.server,
1104                agent: owned.agent,
1105                device: owned.device,
1106                integrator: owned.integrator,
1107            });
1108            let as_string = ValueRef::String(NodeStr::Borrowed(raw));
1109
1110            for needle in needles {
1111                assert_eq!(
1112                    borrowed.as_str() == needle,
1113                    borrowed == needle,
1114                    "jid value {raw:?} vs {needle:?}"
1115                );
1116                assert_eq!(
1117                    as_string.as_str() == needle,
1118                    as_string == needle,
1119                    "string value {raw:?} vs {needle:?}"
1120                );
1121            }
1122        }
1123
1124        // The server-only shape is the one the server checks compare against.
1125        let server_only = ValueRef::Jid(JidRef {
1126            user: NodeStr::Borrowed(""),
1127            server: Server::Pn,
1128            agent: 0,
1129            device: 0,
1130            integrator: 0,
1131        });
1132        assert!(server_only == "s.whatsapp.net");
1133        assert!(server_only != "5511999998888@s.whatsapp.net");
1134    }
1135}
1136
1137#[cfg(test)]
1138mod owned_node_ref_tests {
1139    use super::*;
1140
1141    /// Node bytes, as `OwnedNodeRef::new` wants them: marshal output with the
1142    /// format byte taken off, the way the receive path gets them.
1143    fn encoded(node: &Node) -> Bytes {
1144        let packed = crate::marshal::marshal(node).unwrap();
1145        Bytes::from(crate::util::unpack(&packed).unwrap().into_owned())
1146    }
1147
1148    fn sample() -> Node {
1149        Node::new(
1150            "iq",
1151            Attrs(vec![(Cow::Borrowed("id"), NodeValue::String("abc".into()))].into()),
1152            Some(NodeContent::Bytes(b"payload".to_vec())),
1153        )
1154    }
1155
1156    #[test]
1157    fn borrowed_payloads_survive_moving_the_cart() {
1158        let node = sample();
1159        let owned = OwnedNodeRef::new(encoded(&node)).unwrap();
1160
1161        // Move the value twice — through a Box and into a Vec — before reading
1162        // anything back. That is the whole `StableDeref` claim: the yoked
1163        // `NodeRef` keeps pointing at live bytes even though the wrapper it
1164        // borrows from has moved. Nothing but an interpreter notices when it
1165        // stops being true, which is why this test exists separately from the
1166        // serde one it used to be a side effect of.
1167        let mut moved = vec![*Box::new(owned)];
1168        let owned = moved.pop().unwrap();
1169
1170        assert_eq!(owned.tag(), "iq");
1171        assert!(owned.get_attr("id").unwrap() == "abc");
1172        assert_eq!(owned.content_bytes(), Some(&b"payload"[..]));
1173        assert_eq!(owned.to_owned_node(), node);
1174    }
1175
1176    #[test]
1177    fn yoked_attrs_ref_survives_make_transform_and_mutation() {
1178        // A heap-backed cart makes Miri observe the allocation's lifetime;
1179        // static bytes would hide a dangling borrow after premature cart release.
1180        let cart = BytesCart(Bytes::copy_from_slice(b"idabc"));
1181        let mut yoke: Yoke<AttrsRef<'static>, BytesCart> = Yoke::attach_to_cart(cart, |buf| {
1182            // Borrowed from the cart, which is what makes the transmutes load-bearing.
1183            let (key, value) = buf.split_at(2);
1184            AttrsRef::from_vec(vec![(
1185                NodeStr::Borrowed(std::str::from_utf8(key).expect("ascii")),
1186                ValueRef::String(NodeStr::Borrowed(
1187                    std::str::from_utf8(value).expect("ascii"),
1188                )),
1189            )])
1190        });
1191
1192        let (key, value) = &yoke.get().as_slice()[0];
1193        assert!(*key == "id");
1194        assert!(*value == "abc");
1195
1196        yoke.with_mut(|attrs| {
1197            if let AttrsRef::Slice(values) = attrs {
1198                values[0].0 = NodeStr::Owned("k".into());
1199            }
1200        });
1201        assert!(yoke.get().as_slice()[0].0 == "k");
1202        assert!(yoke.get().as_slice()[0].1 == "abc");
1203
1204        // Replacement also exercises dropping borrowed attributes before the cart.
1205        yoke.with_mut(|attrs| {
1206            *attrs = AttrsRef::from_vec(vec![(
1207                NodeStr::Owned("k".into()),
1208                ValueRef::String(NodeStr::Owned("v".into())),
1209            )]);
1210        });
1211        assert!(yoke.get().as_slice()[0].1 == "v");
1212    }
1213
1214    #[test]
1215    fn slice_bytes_views_the_backing_buffer_without_copying() {
1216        let owned = OwnedNodeRef::new(encoded(&sample())).unwrap();
1217        let content = owned.content_bytes().unwrap();
1218
1219        let view = owned.slice_bytes(content);
1220
1221        assert_eq!(view.as_ref(), b"payload");
1222        assert_eq!(view.as_ptr(), content.as_ptr(), "slice_bytes copied");
1223    }
1224
1225    #[test]
1226    fn backing_bytes_returns_what_was_decoded_verbatim() {
1227        let encoded = encoded(&sample());
1228        let owned = OwnedNodeRef::new(encoded.clone()).unwrap();
1229
1230        let backing = owned.backing_bytes();
1231
1232        assert_eq!(backing.as_ref(), encoded.as_ref());
1233        // Decoding the returned bytes reproduces the same node, which is what
1234        // lets an observer forward a stanza instead of re-encoding it.
1235        let reparsed = OwnedNodeRef::new(backing).unwrap();
1236        assert_eq!(reparsed.to_owned_node(), owned.to_owned_node());
1237    }
1238
1239    #[test]
1240    fn backing_bytes_shares_the_allocation_rather_than_copying() {
1241        let owned = OwnedNodeRef::new(encoded(&sample())).unwrap();
1242        let content = owned.content_bytes().unwrap();
1243
1244        let backing = owned.backing_bytes();
1245
1246        // `slice_bytes` views into this same buffer, so a payload borrowed from
1247        // the node is a subrange of what `backing_bytes` returns.
1248        assert_eq!(owned.slice_bytes(content).as_ptr(), content.as_ptr());
1249        let offset = content.as_ptr() as usize - backing.as_ptr() as usize;
1250        assert_eq!(&backing[offset..offset + content.len()], content);
1251    }
1252}
1253
1254#[cfg(feature = "serde")]
1255impl serde::Serialize for OwnedNodeRef {
1256    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1257        self.get().serialize(serializer)
1258    }
1259}
1260
1261impl fmt::Debug for OwnedNodeRef {
1262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1263        self.inner.get().fmt(f)
1264    }
1265}
1266
1267#[cfg(test)]
1268mod value_ref_tests {
1269    use super::*;
1270    use crate::jid::Server;
1271
1272    #[test]
1273    fn value_ref_compares_string_and_jid_display_without_conversion() {
1274        let string = ValueRef::String(NodeStr::Borrowed("encrypt"));
1275        assert!(string == "encrypt");
1276        assert!(string != "other");
1277
1278        let jid = ValueRef::Jid(JidRef {
1279            user: NodeStr::Borrowed("12025550111"),
1280            server: Server::Pn,
1281            agent: 0,
1282            device: 7,
1283            integrator: 0,
1284        });
1285        assert!(jid == "12025550111:7@s.whatsapp.net");
1286        assert!(jid != "12025550111@s.whatsapp.net");
1287    }
1288}
1289
1290#[cfg(test)]
1291#[cfg(feature = "serde")]
1292mod serde_tests {
1293    use super::*;
1294    use crate::jid::{Jid, Server};
1295
1296    #[test]
1297    fn node_ref_serializes_same_as_node() {
1298        let node = Node::new(
1299            Cow::Borrowed("message"),
1300            Attrs(
1301                vec![
1302                    (Cow::Borrowed("type"), NodeValue::String("text".into())),
1303                    (Cow::Borrowed("from"), NodeValue::Jid(Jid::pn("5550199999"))),
1304                ]
1305                .into(),
1306            ),
1307            Some(NodeContent::String("hello".into())),
1308        );
1309        let node_ref = node.as_node_ref();
1310
1311        let owned_json = serde_json::to_value(&node).unwrap();
1312        let ref_json = serde_json::to_value(&node_ref).unwrap();
1313        assert_eq!(owned_json, ref_json);
1314    }
1315
1316    #[test]
1317    fn nested_nodes_serialize_same() {
1318        let child = Node::new(Cow::Borrowed("item"), Attrs::new(), None);
1319        let parent = Node::new(
1320            Cow::Borrowed("list"),
1321            Attrs::new(),
1322            Some(NodeContent::Nodes(vec![child])),
1323        );
1324        let parent_ref = parent.as_node_ref();
1325
1326        assert_eq!(
1327            serde_json::to_value(&parent).unwrap(),
1328            serde_json::to_value(&parent_ref).unwrap(),
1329        );
1330    }
1331
1332    #[test]
1333    fn bytes_content_serializes_same() {
1334        let node = Node::new(
1335            Cow::Borrowed("iq"),
1336            Attrs(vec![(Cow::Borrowed("id"), NodeValue::String("1".into()))].into()),
1337            Some(NodeContent::Bytes(vec![0xDE, 0xAD])),
1338        );
1339        let node_ref = node.as_node_ref();
1340
1341        let owned_json = serde_json::to_value(&node).unwrap();
1342        let ref_json = serde_json::to_value(&node_ref).unwrap();
1343        assert_eq!(owned_json, ref_json);
1344    }
1345
1346    #[test]
1347    fn value_ref_matches_node_value() {
1348        let string_val = NodeValue::String("hello".into());
1349        let string_ref = ValueRef::String(NodeStr::Borrowed("hello"));
1350        assert_eq!(
1351            serde_json::to_value(&string_val).unwrap(),
1352            serde_json::to_value(&string_ref).unwrap(),
1353        );
1354
1355        let jid = Jid {
1356            user: "5550199999".into(),
1357            server: Server::Group,
1358            agent: 1,
1359            device: 2,
1360            integrator: 3,
1361        };
1362        let jid_val = NodeValue::Jid(jid.clone());
1363        let jid_ref_val = ValueRef::Jid(JidRef {
1364            user: NodeStr::Borrowed("5550199999"),
1365            server: Server::Group,
1366            agent: 1,
1367            device: 2,
1368            integrator: 3,
1369        });
1370        assert_eq!(
1371            serde_json::to_value(&jid_val).unwrap(),
1372            serde_json::to_value(&jid_ref_val).unwrap(),
1373        );
1374    }
1375
1376    #[test]
1377    fn owned_node_ref_serializes_same_as_owned() {
1378        let node = Node::new(
1379            Cow::Borrowed("iq"),
1380            Attrs(vec![(Cow::Borrowed("id"), NodeValue::String("abc".into()))].into()),
1381            Some(NodeContent::String("payload".into())),
1382        );
1383
1384        let packed = crate::marshal::marshal(&node).unwrap();
1385        let node_bytes = crate::util::unpack(&packed).unwrap().into_owned();
1386        let owned_ref = OwnedNodeRef::new(Bytes::from(node_bytes)).unwrap();
1387
1388        let from_ref = serde_json::to_value(&owned_ref).unwrap();
1389        let from_owned = serde_json::to_value(owned_ref.to_owned_node()).unwrap();
1390        assert_eq!(from_ref, from_owned);
1391    }
1392
1393    #[test]
1394    fn slice_bytes_empty_slice_returns_empty_bytes() {
1395        let node = Node::new(Cow::Borrowed("iq"), Attrs::new(), None);
1396        let packed = crate::marshal::marshal(&node).unwrap();
1397        let node_bytes = crate::util::unpack(&packed).unwrap().into_owned();
1398        let owned_ref = OwnedNodeRef::new(Bytes::from(node_bytes)).unwrap();
1399
1400        let empty = owned_ref.slice_bytes(&[]);
1401        assert!(empty.is_empty());
1402    }
1403}