Repository navigation
Expand file tree
/
Copy pathnode.rs
More file actions
1200 lines (1044 loc) · 36 KB
/
Copy pathnode.rs
File metadata and controls
1200 lines (1044 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::attrs::{AttrParser, AttrParserRef};
use crate::jid::{Jid, JidRef};
use crate::token;
use bytes::Bytes;
use compact_str::CompactString;
use stable_deref_trait::StableDeref;
use std::borrow::Cow;
/// Borrowed-or-inline string for decoded nodes. Short owned values (≤24 bytes)
/// are stored inline via `CompactString`, avoiding heap allocation.
#[derive(Clone, yoke::Yokeable)]
pub enum NodeStr<'a> {
Borrowed(&'a str),
Owned(CompactString),
}
impl NodeStr<'_> {
/// Clone-preserving conversion. Avoids re-parsing the inner CompactString
/// when converting owned NodeStr values in `to_owned()` paths.
#[inline]
pub fn to_compact_string(&self) -> CompactString {
match self {
NodeStr::Borrowed(s) => CompactString::from(*s),
NodeStr::Owned(cs) => cs.clone(),
}
}
}
impl Default for NodeStr<'_> {
#[inline]
fn default() -> Self {
NodeStr::Borrowed("")
}
}
impl std::ops::Deref for NodeStr<'_> {
type Target = str;
#[inline(always)]
fn deref(&self) -> &str {
match self {
NodeStr::Borrowed(s) => s,
NodeStr::Owned(cs) => cs.as_str(),
}
}
}
impl AsRef<str> for NodeStr<'_> {
#[inline(always)]
fn as_ref(&self) -> &str {
self
}
}
impl fmt::Debug for NodeStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl fmt::Display for NodeStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for NodeStr<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self)
}
}
impl PartialEq for NodeStr<'_> {
#[inline]
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl Eq for NodeStr<'_> {}
impl std::hash::Hash for NodeStr<'_> {
#[inline]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(**self).hash(state)
}
}
impl PartialEq<str> for NodeStr<'_> {
#[inline]
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
impl PartialEq<&str> for NodeStr<'_> {
#[inline]
fn eq(&self, other: &&str) -> bool {
&**self == *other
}
}
impl<'a> From<&'a str> for NodeStr<'a> {
#[inline]
fn from(s: &'a str) -> Self {
NodeStr::Borrowed(s)
}
}
impl From<CompactString> for NodeStr<'_> {
#[inline]
fn from(s: CompactString) -> Self {
NodeStr::Owned(s)
}
}
/// Intern a string as a `Cow::Borrowed(&'static str)` if it matches a known token,
/// otherwise allocate a `Cow::Owned(String)`. This avoids heap allocations for the
/// vast majority of tag names and attribute keys which are protocol tokens.
#[inline]
fn intern_cow(s: &str) -> Cow<'static, str> {
if let Some(kind) = token::index_of_token(s) {
let interned = match kind {
token::TokenKind::Single(idx) => token::get_single_token(idx),
token::TokenKind::Double(dict, idx) => token::get_double_token(dict, idx),
};
if let Some(token) = interned {
return Cow::Borrowed(token);
}
}
Cow::Owned(s.to_string())
}
/// An owned attribute value that can be either a string or a structured JID.
/// This avoids string allocation for JID attributes by storing the JID directly,
/// eliminating format/parse overhead when routing logic needs the JID.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum NodeValue {
String(CompactString),
Jid(Jid),
}
impl Default for NodeValue {
fn default() -> Self {
NodeValue::String(CompactString::default())
}
}
impl NodeValue {
/// String view of the value. Works for both variants.
/// - String variant: Cow::Borrowed(&str) — zero copy
/// - Jid variant: Cow::Owned(formatted) — allocates only when needed
#[inline]
pub fn as_str(&self) -> Cow<'_, str> {
match self {
NodeValue::String(s) => Cow::Borrowed(s.as_str()),
NodeValue::Jid(j) => Cow::Owned(j.to_string()),
}
}
/// Convert to an owned Jid, parsing from string if necessary.
#[inline]
pub fn to_jid(&self) -> Option<Jid> {
match self {
NodeValue::Jid(j) => Some(j.clone()),
NodeValue::String(s) => s.parse().ok(),
}
}
}
use std::fmt;
impl fmt::Display for NodeValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NodeValue::String(s) => write!(f, "{}", s),
NodeValue::Jid(j) => write!(f, "{}", j),
}
}
}
impl PartialEq<str> for NodeValue {
fn eq(&self, other: &str) -> bool {
match self {
NodeValue::String(s) => s == other,
NodeValue::Jid(j) => j.display_eq(other),
}
}
}
impl PartialEq<&str> for NodeValue {
fn eq(&self, other: &&str) -> bool {
self == *other
}
}
impl PartialEq<String> for NodeValue {
fn eq(&self, other: &String) -> bool {
self == other.as_str()
}
}
impl From<String> for NodeValue {
#[inline]
fn from(s: String) -> Self {
NodeValue::String(CompactString::from(s))
}
}
impl From<&str> for NodeValue {
#[inline]
fn from(s: &str) -> Self {
NodeValue::String(CompactString::from(s))
}
}
impl From<&String> for NodeValue {
#[inline]
fn from(s: &String) -> Self {
NodeValue::String(CompactString::from(s.as_str()))
}
}
impl From<CompactString> for NodeValue {
#[inline]
fn from(s: CompactString) -> Self {
NodeValue::String(s)
}
}
impl From<Jid> for NodeValue {
#[inline]
fn from(jid: Jid) -> Self {
NodeValue::Jid(jid)
}
}
impl From<&Jid> for NodeValue {
#[inline]
fn from(jid: &Jid) -> Self {
NodeValue::Jid(jid.clone())
}
}
macro_rules! impl_from_integer_for_nodevalue {
($($t:ty),* $(,)?) => {
$(
impl From<$t> for NodeValue {
#[inline]
fn from(n: $t) -> Self {
let mut buf = itoa::Buffer::new();
NodeValue::String(CompactString::from(buf.format(n)))
}
}
)*
};
}
impl_from_integer_for_nodevalue!(
u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize
);
impl From<bool> for NodeValue {
#[inline]
fn from(b: bool) -> Self {
NodeValue::String(CompactString::from(if b { "true" } else { "false" }))
}
}
/// Inline backing store for [`Attrs`]. A plain `Vec` paid one heap allocation
/// per node on the encode hot path just for the backing buffer. Capacity 2 is
/// the measured sweet spot: the per-recipient fanout nodes (`to`, `enc`) carry
/// 1-2 attributes and stay inline, while stanza roots with 3+ attrs spill once
/// per stanza. A larger inline array (4) grows `Node` enough that moving it
/// through children Vecs costs more than the spared spills save.
pub type AttrsVec = smallvec::SmallVec<[(Cow<'static, str>, NodeValue); 2]>;
/// A collection of node attributes stored as key-value pairs.
/// Stored inline for small attribute counts (typically 3-6) for cache locality
/// and to avoid a per-node heap allocation; see [`AttrsVec`].
/// Values can be either strings or JIDs, avoiding stringification overhead for JID attributes.
/// Keys use `Cow<'static, str>` to avoid heap allocation for compile-time-known strings
/// (e.g., "type", "id", "to") which are the vast majority of attribute keys.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Attrs(pub AttrsVec);
impl Attrs {
#[inline]
pub fn new() -> Self {
Self(AttrsVec::new())
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self(AttrsVec::with_capacity(capacity))
}
/// Get a reference to the NodeValue for a key, or None if not found.
/// Uses linear search which is efficient for small attribute counts.
#[inline]
pub fn get(&self, key: &str) -> Option<&NodeValue> {
self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
/// Check if a key exists.
#[inline]
pub fn contains_key(&self, key: &str) -> bool {
self.0.iter().any(|(k, _)| k == key)
}
/// Insert a key-value pair. If the key already exists, update the value.
#[inline]
pub fn insert(&mut self, key: impl Into<Cow<'static, str>>, value: impl Into<NodeValue>) {
let key = key.into();
let value = value.into();
if let Some(pos) = self.0.iter().position(|(k, _)| k == &key) {
self.0[pos].1 = value;
} else {
self.0.push((key, value));
}
}
#[inline]
pub fn len(&self) -> usize {
self.0.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Iterate over key-value pairs.
#[inline]
pub fn iter(&self) -> impl Iterator<Item = (&Cow<'static, str>, &NodeValue)> {
self.0.iter().map(|(k, v)| (k, v))
}
/// Push a key-value pair without checking for duplicates.
/// Use this when building from a known-unique source (e.g., decoding).
#[inline]
pub fn push(&mut self, key: impl Into<Cow<'static, str>>, value: impl Into<NodeValue>) {
self.0.push((key.into(), value.into()));
}
/// Push a NodeValue directly without conversion.
/// Slightly more efficient when you already have a NodeValue.
#[inline]
pub fn push_value(&mut self, key: impl Into<Cow<'static, str>>, value: NodeValue) {
self.0.push((key.into(), value));
}
/// Iterate over keys only.
#[inline]
pub fn keys(&self) -> impl Iterator<Item = &Cow<'static, str>> {
self.0.iter().map(|(k, _)| k)
}
}
/// Owned iterator implementation (consuming).
impl IntoIterator for Attrs {
type Item = (Cow<'static, str>, NodeValue);
type IntoIter = smallvec::IntoIter<[(Cow<'static, str>, NodeValue); 2]>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
/// Borrowed iterator implementation.
impl<'a> IntoIterator for &'a Attrs {
type Item = (&'a Cow<'static, str>, &'a NodeValue);
type IntoIter = std::iter::Map<
std::slice::Iter<'a, (Cow<'static, str>, NodeValue)>,
fn(&'a (Cow<'static, str>, NodeValue)) -> (&'a Cow<'static, str>, &'a NodeValue),
>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter().map(|(k, v)| (k, v))
}
}
impl FromIterator<(Cow<'static, str>, NodeValue)> for Attrs {
fn from_iter<I: IntoIterator<Item = (Cow<'static, str>, NodeValue)>>(iter: I) -> Self {
Self(iter.into_iter().collect())
}
}
/// Covariant attribute container for decoded nodes.
///
/// Uses `Box<[T]>` (16 bytes: ptr + len) instead of `Vec<T>` (24 bytes: ptr + len + cap)
/// or inline storage (which inflated NodeRef size). Zero-attr nodes skip allocation
/// entirely. The boxed slice is allocated once with exact size from the decoder.
///
/// Covariant in `'a` (both Box and slices are covariant), compatible with yoke::Yokeable.
#[derive(Debug, Clone)]
pub enum AttrsRef<'a> {
Empty,
Slice(Box<[(NodeStr<'a>, ValueRef<'a>)]>),
}
impl PartialEq for AttrsRef<'_> {
fn eq(&self, other: &Self) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<'a> AttrsRef<'a> {
/// Build from a pre-filled Vec. Preferred path from the decoder which
/// knows the exact attr count upfront.
pub fn from_vec(v: Vec<(NodeStr<'a>, ValueRef<'a>)>) -> Self {
if v.is_empty() {
Self::Empty
} else {
Self::Slice(v.into_boxed_slice())
}
}
#[inline]
pub fn len(&self) -> usize {
match self {
Self::Empty => 0,
Self::Slice(s) => s.len(),
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.as_slice().is_empty()
}
#[inline]
pub fn as_slice(&self) -> &[(NodeStr<'a>, ValueRef<'a>)] {
match self {
Self::Empty => &[],
Self::Slice(s) => s,
}
}
#[inline]
pub fn iter(&self) -> impl Iterator<Item = &(NodeStr<'a>, ValueRef<'a>)> {
self.as_slice().iter()
}
}
impl<'a> FromIterator<(NodeStr<'a>, ValueRef<'a>)> for AttrsRef<'a> {
fn from_iter<I: IntoIterator<Item = (NodeStr<'a>, ValueRef<'a>)>>(iter: I) -> Self {
Self::from_vec(iter.into_iter().collect())
}
}
// Compile-time covariance check: if AttrsRef ever becomes invariant
// (e.g. by adding a Cell or &mut), this function will fail to compile.
fn _assert_attrs_ref_covariant<'short, 'long: 'short>(x: AttrsRef<'long>) -> AttrsRef<'short> {
x
}
// Safety: AttrsRef<'a> is covariant in 'a because:
// - Empty carries no lifetime
// - Slice(Box<[(NodeStr<'a>, ValueRef<'a>)]>): Box<[T]> is covariant in T,
// and (NodeStr<'a>, ValueRef<'a>) is covariant in 'a
// The _assert_attrs_ref_covariant function above enforces this at compile time.
unsafe impl<'a> yoke::Yokeable<'a> for AttrsRef<'static> {
type Output = AttrsRef<'a>;
fn transform(&'a self) -> &'a Self::Output {
self
}
fn transform_owned(self) -> Self::Output {
self
}
unsafe fn make(from: Self::Output) -> Self {
unsafe { std::mem::transmute(from) }
}
fn transform_mut<F>(&'a mut self, f: F)
where
F: 'static + for<'b> FnOnce(&'b mut Self::Output),
{
unsafe { f(std::mem::transmute::<&mut Self, &mut Self::Output>(self)) }
}
}
/// A decoded attribute value that can be either a string or a structured JID.
/// This avoids string allocation when decoding JID tokens - the JidRef is returned
/// directly and only converted to a string when actually needed.
#[derive(Debug, Clone, PartialEq, yoke::Yokeable)]
pub enum ValueRef<'a> {
String(NodeStr<'a>),
Jid(JidRef<'a>),
}
#[cfg(feature = "serde")]
impl serde::Serialize for ValueRef<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
ValueRef::String(s) => {
serializer.serialize_newtype_variant("NodeValue", 0, "String", &**s)
}
ValueRef::Jid(j) => serializer.serialize_newtype_variant("NodeValue", 1, "Jid", j),
}
}
}
impl<'a> ValueRef<'a> {
/// Encode this value directly to the binary encoder.
pub fn encode_value<W: crate::encoder::ByteWriter>(
&self,
encoder: &mut crate::encoder::Encoder<'_, W>,
) -> crate::error::Result<()> {
match self {
ValueRef::String(s) => encoder.write_string(s),
ValueRef::Jid(jid) => encoder.write_jid_ref(jid),
}
}
/// String view of the value. Borrows from `self`.
/// - String variant: borrows the inner str — zero copy
/// - Jid variant: Cow::Owned — allocates only when needed
pub fn as_str(&self) -> Cow<'_, str> {
match self {
ValueRef::String(s) => Cow::Borrowed(s),
ValueRef::Jid(j) => Cow::Owned(j.to_string()),
}
}
/// Get the value as a JidRef, if it's a JID variant.
pub fn as_jid(&self) -> Option<&JidRef<'a>> {
match self {
ValueRef::Jid(j) => Some(j),
ValueRef::String(_) => None,
}
}
/// Convert to an owned Jid, parsing from string if necessary.
pub fn to_jid(&self) -> Option<Jid> {
match self {
ValueRef::Jid(j) => Some(j.to_owned()),
ValueRef::String(s) => Jid::from_str(s.as_ref()).ok(),
}
}
/// Convert to an owned NodeValue, preserving the variant (JID stays JID).
pub fn to_node_value(&self) -> NodeValue {
match self {
ValueRef::String(s) => NodeValue::String(s.to_compact_string()),
ValueRef::Jid(j) => NodeValue::Jid(j.to_owned()),
}
}
}
impl PartialEq<str> for ValueRef<'_> {
#[inline]
fn eq(&self, other: &str) -> bool {
match self {
ValueRef::String(value) => value == other,
ValueRef::Jid(value) => value.display_eq(other),
}
}
}
impl PartialEq<&str> for ValueRef<'_> {
#[inline]
fn eq(&self, other: &&str) -> bool {
self == *other
}
}
impl PartialEq<String> for ValueRef<'_> {
#[inline]
fn eq(&self, other: &String) -> bool {
self == other.as_str()
}
}
use std::str::FromStr;
impl<'a> fmt::Display for ValueRef<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ValueRef::String(s) => write!(f, "{}", s),
ValueRef::Jid(j) => write!(f, "{}", j),
}
}
}
pub type NodeVec<'a> = Vec<NodeRef<'a>>;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum NodeContent {
Bytes(Vec<u8>),
String(CompactString),
Nodes(Vec<Node>),
}
#[derive(Debug, Clone, PartialEq, yoke::Yokeable)]
pub enum NodeContentRef<'a> {
Bytes(Cow<'a, [u8]>),
String(NodeStr<'a>),
Nodes(Box<[NodeRef<'a>]>),
}
#[cfg(feature = "serde")]
impl serde::Serialize for NodeContentRef<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
NodeContentRef::Bytes(b) => {
serializer.serialize_newtype_variant("NodeContent", 0, "Bytes", b.as_ref())
}
NodeContentRef::String(s) => {
serializer.serialize_newtype_variant("NodeContent", 1, "String", &**s)
}
NodeContentRef::Nodes(nodes) => {
serializer.serialize_newtype_variant("NodeContent", 2, "Nodes", &**nodes)
}
}
}
}
impl NodeContent {
/// Convert an owned NodeContent to a borrowed NodeContentRef.
pub fn as_content_ref(&self) -> NodeContentRef<'_> {
match self {
NodeContent::Bytes(b) => NodeContentRef::Bytes(Cow::Borrowed(b)),
NodeContent::String(s) => NodeContentRef::String(NodeStr::Borrowed(s.as_str())),
NodeContent::Nodes(nodes) => {
let v: Vec<_> = nodes.iter().map(|n| n.as_node_ref()).collect();
NodeContentRef::Nodes(v.into_boxed_slice())
}
}
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Node {
pub tag: Cow<'static, str>,
pub attrs: Attrs,
pub content: Option<NodeContent>,
}
#[derive(Debug, Clone, PartialEq, yoke::Yokeable)]
pub struct NodeRef<'a> {
pub tag: NodeStr<'a>,
pub attrs: AttrsRef<'a>,
pub content: Option<Box<NodeContentRef<'a>>>,
}
impl Node {
pub fn new(
tag: impl Into<Cow<'static, str>>,
attrs: Attrs,
content: Option<NodeContent>,
) -> Self {
Self {
tag: tag.into(),
attrs,
content,
}
}
/// Convert an owned Node to a borrowed NodeRef.
/// The returned NodeRef borrows from self.
pub fn as_node_ref(&self) -> NodeRef<'_> {
NodeRef {
tag: NodeStr::Borrowed(self.tag.as_ref()),
attrs: self
.attrs
.iter()
.map(|(k, v)| {
let value_ref = match v {
NodeValue::String(s) => ValueRef::String(NodeStr::Borrowed(s.as_str())),
NodeValue::Jid(j) => ValueRef::Jid(JidRef {
user: NodeStr::Borrowed(&j.user),
server: j.server,
agent: j.agent,
device: j.device,
integrator: j.integrator,
}),
};
(NodeStr::Borrowed(k.as_ref()), value_ref)
})
.collect(),
content: self.content.as_ref().map(|c| Box::new(c.as_content_ref())),
}
}
pub fn children(&self) -> Option<&[Node]> {
match &self.content {
Some(NodeContent::Nodes(nodes)) => Some(nodes),
_ => None,
}
}
pub fn attrs(&self) -> AttrParser<'_> {
AttrParser::new(self)
}
pub fn get_optional_child_by_tag<'a>(&'a self, tags: &[&str]) -> Option<&'a Node> {
let mut current_node = self;
for &tag in tags {
let children = current_node.children()?;
current_node = children.iter().find(|c| c.tag == tag)?;
}
Some(current_node)
}
pub fn get_children_by_tag<'a>(&'a self, tag: &'a str) -> impl Iterator<Item = &'a Node> {
self.children()
.into_iter()
.flatten()
.filter(move |c| c.tag == tag)
}
pub fn get_optional_child(&self, tag: &str) -> Option<&Node> {
self.children()
.and_then(|nodes| nodes.iter().find(|node| node.tag == tag))
}
/// Extract text content, handling both String and Bytes (lossy UTF-8).
pub fn content_as_string(&self) -> Option<CompactString> {
match &self.content {
Some(NodeContent::String(s)) => Some(s.clone()),
Some(NodeContent::Bytes(b)) => {
Some(CompactString::from(String::from_utf8_lossy(b).as_ref()))
}
_ => None,
}
}
}
/// Wrapper that serializes `AttrsRef` with the same newtype-struct framing
/// that serde's derive produces for `Attrs(Vec<...>)`. Without this, binary
/// formats (bincode, postcard, etc.) would see a bare sequence instead of a
/// newtype struct wrapper.
#[cfg(feature = "serde")]
struct AttrsRefWrapper<'a, 'b>(&'b AttrsRef<'a>);
#[cfg(feature = "serde")]
impl serde::Serialize for AttrsRefWrapper<'_, '_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_newtype_struct("Attrs", self.0.as_slice())
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for NodeRef<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut s = serializer.serialize_struct("Node", 3)?;
s.serialize_field("tag", &*self.tag)?;
s.serialize_field("attrs", &AttrsRefWrapper(&self.attrs))?;
s.serialize_field("content", &self.content)?;
s.end()
}
}
impl<'a> NodeRef<'a> {
pub fn new(tag: NodeStr<'a>, attrs: AttrsRef<'a>, content: Option<NodeContentRef<'a>>) -> Self {
Self {
tag,
attrs,
content: content.map(Box::new),
}
}
pub fn attrs(&self) -> AttrParserRef<'_> {
AttrParserRef::new(self)
}
pub fn children(&self) -> Option<&[NodeRef<'a>]> {
match self.content.as_deref() {
Some(NodeContentRef::Nodes(nodes)) => Some(nodes),
_ => None,
}
}
pub fn get_attr(&self, key: &str) -> Option<&ValueRef<'a>> {
self.attrs.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
pub fn attrs_iter(&self) -> impl Iterator<Item = (&NodeStr<'a>, &ValueRef<'a>)> {
self.attrs.iter().map(|(k, v)| (k, v))
}
pub fn get_optional_child_by_tag(&self, tags: &[&str]) -> Option<&NodeRef<'a>> {
let mut current_node = self;
for &tag in tags {
let children = current_node.children()?;
current_node = children.iter().find(|c| c.tag == tag)?;
}
Some(current_node)
}
pub fn get_children_by_tag<'b>(&'b self, tag: &'b str) -> impl Iterator<Item = &'b NodeRef<'a>>
where
'a: 'b,
{
self.children()
.into_iter()
.flatten()
.filter(move |c| c.tag == tag)
}
pub fn get_optional_child(&self, tag: &str) -> Option<&NodeRef<'a>> {
self.children()
.and_then(|nodes| nodes.iter().find(|node| node.tag == tag))
}
/// Extract text content, handling both String and Bytes (lossy UTF-8).
pub fn content_as_string(&self) -> Option<CompactString> {
match self.content.as_deref() {
Some(NodeContentRef::String(s)) => Some(s.to_compact_string()),
Some(NodeContentRef::Bytes(b)) => Some(CompactString::from(
String::from_utf8_lossy(b.as_ref()).as_ref(),
)),
_ => None,
}
}
/// Zero-copy byte content, if this node has Bytes content.
pub fn content_bytes(&self) -> Option<&[u8]> {
match self.content.as_deref() {
Some(NodeContentRef::Bytes(b)) => Some(b.as_ref()),
_ => None,
}
}
/// Zero-copy string content, if this node has String content.
pub fn content_str(&self) -> Option<&str> {
match self.content.as_deref() {
Some(NodeContentRef::String(s)) => Some(s.as_ref()),
_ => None,
}
}
/// Child nodes from content, if this node has Nodes content.
/// Alias for `children()`.
#[inline]
pub fn content_nodes(&self) -> Option<&[NodeRef<'a>]> {
self.children()
}
pub fn to_owned(&self) -> Node {
Node {
tag: intern_cow(&self.tag),
attrs: self
.attrs
.iter()
.map(|(k, v)| {
let value = match v {
ValueRef::String(s) => NodeValue::String(s.to_compact_string()),
ValueRef::Jid(j) => NodeValue::Jid(j.to_owned()),
};
(intern_cow(k), value)
})
.collect::<Attrs>(),
content: self.content.as_deref().map(|c| match c {
NodeContentRef::Bytes(b) => NodeContent::Bytes(b.to_vec()),
NodeContentRef::String(s) => NodeContent::String(s.to_compact_string()),
NodeContentRef::Nodes(nodes) => {
NodeContent::Nodes(nodes.iter().map(|n| n.to_owned()).collect())
}
}),
}
}
}
// ---------------------------------------------------------------------------
// OwnedNodeRef — self-referential zero-copy node via yoke
// ---------------------------------------------------------------------------
use yoke::Yoke;
#[derive(Clone)]
struct BytesCart(Bytes);
impl std::ops::Deref for BytesCart {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
// Safety: `Bytes` points to immutable backing storage whose deref target
// remains stable for the lifetime of the value, even when the wrapper moves.
unsafe impl StableDeref for BytesCart {}
/// A decoded node that owns its decompressed buffer. The inner `NodeRef`
/// borrows string/byte payloads directly from the buffer, avoiding copies.
/// Container allocations (attribute Vec, child Vec) still occur during decode.
///
/// Wrap in `Arc<OwnedNodeRef>` for cheap sharing across handlers.
pub struct OwnedNodeRef {
inner: Yoke<NodeRef<'static>, BytesCart>,
}
impl OwnedNodeRef {
/// Decode a node from an owned buffer. The buffer should be the raw
/// binary-protocol bytes (after decompression, without the leading
/// format byte which `unpack` already strips).
pub fn new(buffer: impl Into<Bytes>) -> crate::error::Result<Self> {
let inner = Yoke::try_attach_to_cart(BytesCart(buffer.into()), |buf| {
crate::marshal::unmarshal_ref(buf)
})?;
Ok(Self { inner })
}
/// Access the borrowed node.
#[inline]
pub fn get(&self) -> &NodeRef<'_> {
self.inner.get()
}
/// Convert to an owned `Node`, cloning all data out of the buffer.
/// Use sparingly — this is the allocation path that yoke is designed to avoid.
pub fn to_owned_node(&self) -> Node {
self.inner.get().to_owned()
}
/// Return a zero-copy `Bytes` sub-view for a slice that borrows from this
/// node's backing buffer. Panics if `slice` does not point within the buffer.
pub fn slice_bytes(&self, slice: &[u8]) -> Bytes {
let cart = &self.inner.backing_cart().0;
let base = cart.as_ptr() as usize;
let end = base + cart.len();
let ptr = slice.as_ptr() as usize;
assert!(
ptr >= base && ptr + slice.len() <= end,
"slice is not within the backing buffer"
);
let offset = ptr - base;
cart.slice(offset..offset + slice.len())
}
/// The tag name of this node.
#[inline]
pub fn tag(&self) -> &str {
&self.get().tag
}
/// Get an attribute parser for this node.
#[inline]
pub fn attrs(&self) -> AttrParserRef<'_> {
self.get().attrs()
}
/// Look up a single attribute by key.
#[inline]
pub fn get_attr(&self, key: &str) -> Option<&ValueRef<'_>> {
self.get().get_attr(key)
}
/// Get child nodes, if content is a node list.
#[inline]
pub fn children(&self) -> Option<&[NodeRef<'_>]> {
self.get().children()
}
/// Find a child node by tag.
#[inline]
pub fn get_optional_child(&self, tag: &str) -> Option<&NodeRef<'_>> {
self.get().get_optional_child(tag)
}
/// Find a child by traversing a path of tags.
#[inline]
pub fn get_optional_child_by_tag(&self, tags: &[&str]) -> Option<&NodeRef<'_>> {
self.get().get_optional_child_by_tag(tags)
}
/// Get children matching a tag.
#[inline]
pub fn get_children_by_tag<'b>(
&'b self,
tag: &'b str,
) -> impl Iterator<Item = &'b NodeRef<'b>> {
self.get().get_children_by_tag(tag)
}
/// Zero-copy byte content, if this node has Bytes content.
#[inline]
pub fn content_bytes(&self) -> Option<&[u8]> {
self.get().content_bytes()
}
/// Zero-copy string content, if this node has String content.
#[inline]
pub fn content_str(&self) -> Option<&str> {
self.get().content_str()
}
/// Child nodes from content, if this node has Nodes content.
#[inline]
pub fn content_nodes(&self) -> Option<&[NodeRef<'_>]> {