wacore-binary 0.5.0

Binary data and constants for WhatsApp protocol
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
use std::io::Write;

#[cfg(feature = "simd")]
use core::simd::Select;
#[cfg(feature = "simd")]
use core::simd::prelude::*;
#[cfg(feature = "simd")]
use core::simd::{Simd, u8x16};

use crate::error::{BinaryError, Result};
use crate::jid::{self, Jid, JidRef};
use crate::node::{Node, NodeContent, NodeContentRef, NodeRef, NodeValue, ValueRef};
use crate::token;

pub(crate) trait ByteWriter {
    fn write_u8(&mut self, value: u8) -> Result<()>;
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()>;
}

pub(crate) struct IoByteWriter<W: Write> {
    writer: W,
}

impl<W: Write> IoByteWriter<W> {
    fn new(writer: W) -> Self {
        Self { writer }
    }
}

impl<W: Write> ByteWriter for IoByteWriter<W> {
    #[inline]
    fn write_u8(&mut self, value: u8) -> Result<()> {
        self.writer.write_all(&[value])?;
        Ok(())
    }

    #[inline]
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
        self.writer.write_all(bytes)?;
        Ok(())
    }
}

pub(crate) struct VecByteWriter<'a> {
    buffer: &'a mut Vec<u8>,
}

impl<'a> VecByteWriter<'a> {
    fn new(buffer: &'a mut Vec<u8>) -> Self {
        Self { buffer }
    }
}

impl ByteWriter for VecByteWriter<'_> {
    #[inline]
    fn write_u8(&mut self, value: u8) -> Result<()> {
        self.buffer.push(value);
        Ok(())
    }

    #[inline]
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
        self.buffer.extend_from_slice(bytes);
        Ok(())
    }
}

pub(crate) struct SliceByteWriter<'a> {
    buffer: &'a mut [u8],
    position: usize,
}

impl<'a> SliceByteWriter<'a> {
    fn new(buffer: &'a mut [u8]) -> Self {
        Self {
            buffer,
            position: 0,
        }
    }

    #[inline]
    fn bytes_written(&self) -> usize {
        self.position
    }
}

impl ByteWriter for SliceByteWriter<'_> {
    #[inline]
    fn write_u8(&mut self, value: u8) -> Result<()> {
        if self.position >= self.buffer.len() {
            return Err(BinaryError::UnexpectedEof);
        }
        self.buffer[self.position] = value;
        self.position += 1;
        Ok(())
    }

    #[inline]
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
        let end = self.position + bytes.len();
        if end > self.buffer.len() {
            return Err(BinaryError::UnexpectedEof);
        }
        self.buffer[self.position..end].copy_from_slice(bytes);
        self.position = end;
        Ok(())
    }
}

/// Trait for encoding node structures (both owned Node and borrowed NodeRef).
/// All encoding logic lives in the trait implementation, keeping
/// the Encoder simple and focused on low-level byte writing.
pub(crate) trait EncodeNode {
    fn tag(&self) -> &str;
    fn attrs_len(&self) -> usize;
    fn has_content(&self) -> bool;

    /// Encode all attributes to the encoder
    fn encode_attrs<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()>;

    /// Encode content (string, bytes, or child nodes) to the encoder
    fn encode_content<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()>;
}

impl EncodeNode for Node {
    fn tag(&self) -> &str {
        &self.tag
    }

    fn attrs_len(&self) -> usize {
        self.attrs.len()
    }

    fn has_content(&self) -> bool {
        self.content.is_some()
    }

    fn encode_attrs<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()> {
        for (k, v) in &self.attrs {
            encoder.write_string(k)?;
            match v {
                NodeValue::String(s) => encoder.write_string(s)?,
                NodeValue::Jid(jid) => encoder.write_jid_owned(jid)?,
            }
        }
        Ok(())
    }

    fn encode_content<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()> {
        if let Some(content) = &self.content {
            match content {
                NodeContent::String(s) => encoder.write_string(s)?,
                NodeContent::Bytes(b) => encoder.write_bytes_with_len(b)?,
                NodeContent::Nodes(nodes) => {
                    encoder.write_list_start(nodes.len())?;
                    for node in nodes {
                        encoder.write_node(node)?;
                    }
                }
            }
        }
        Ok(())
    }
}

impl EncodeNode for NodeRef<'_> {
    fn tag(&self) -> &str {
        &self.tag
    }

    fn attrs_len(&self) -> usize {
        self.attrs.len()
    }

    fn has_content(&self) -> bool {
        self.content.is_some()
    }

    fn encode_attrs<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()> {
        for (k, v) in &self.attrs {
            encoder.write_string(k)?;
            match v {
                ValueRef::String(s) => encoder.write_string(s)?,
                ValueRef::Jid(jid) => encoder.write_jid_ref(jid)?,
            }
        }
        Ok(())
    }

    fn encode_content<'a, W: ByteWriter>(&self, encoder: &mut Encoder<'a, W>) -> Result<()> {
        if let Some(content) = self.content.as_deref() {
            match content {
                NodeContentRef::String(s) => encoder.write_string(s)?,
                NodeContentRef::Bytes(b) => encoder.write_bytes_with_len(b)?,
                NodeContentRef::Nodes(nodes) => {
                    encoder.write_list_start(nodes.len())?;
                    for node in nodes.iter() {
                        encoder.write_node(node)?;
                    }
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ParsedJidMeta {
    user_end: usize,
    server_start: usize,
    domain_type: u8,
    device: Option<u8>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct StrKey {
    ptr: usize,
    len: usize,
}

impl StrKey {
    #[inline]
    fn from_str(s: &str) -> Self {
        Self {
            ptr: s.as_ptr() as usize,
            len: s.len(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StringHint {
    Empty,
    SingleToken(u8),
    DoubleToken { dict: u8, token: u8 },
    PackedNibble,
    PackedHex,
    Jid(ParsedJidMeta),
    RawBytes,
}

#[derive(Debug)]
pub(crate) struct StringHintCache {
    // Keys use (ptr, len) identity, so this cache is only valid while encoding
    // the same immutable node/strings it was built from.
    hints: Vec<(StrKey, StringHint)>,
}

impl Default for StringHintCache {
    fn default() -> Self {
        Self {
            hints: Vec::with_capacity(32),
        }
    }
}

impl StringHintCache {
    const MAX_HINT_ENTRIES: usize = 96;

    #[inline]
    fn hint_for(&self, s: &str) -> Option<StringHint> {
        let key = StrKey::from_str(s);
        self.hints
            .iter()
            .find_map(|(cached_key, hint)| (*cached_key == key).then_some(*hint))
    }

    #[inline]
    fn hint_or_insert(&mut self, s: &str) -> StringHint {
        let key = StrKey::from_str(s);
        if let Some(existing) = self
            .hints
            .iter()
            .find_map(|(cached_key, hint)| (*cached_key == key).then_some(*hint))
        {
            existing
        } else {
            let hint = classify_string_hint(s);
            if self.hints.len() < Self::MAX_HINT_ENTRIES {
                self.hints.push((key, hint));
            }
            hint
        }
    }
}

#[derive(Debug)]
pub(crate) struct MarshaledSizePlan {
    pub(crate) size: usize,
    pub(crate) hints: StringHintCache,
}

fn parse_jid_meta(input: &str) -> Option<ParsedJidMeta> {
    let sep_idx = input.find('@')?;
    let server_start = sep_idx + 1;
    let server = &input[server_start..];
    let user_combined = &input[..sep_idx];

    let (user_agent, device) = if let Some(colon_idx) = user_combined.find(':') {
        let device_part = &user_combined[colon_idx + 1..];
        if let Ok(parsed_device) = device_part.parse::<u8>() {
            (&user_combined[..colon_idx], Some(parsed_device))
        } else {
            (user_combined, None)
        }
    } else {
        (user_combined, None)
    };

    let (user_end, agent_override) = if let Some(underscore_idx) = user_agent.find('_') {
        let agent_part = &user_agent[underscore_idx + 1..];
        if let Ok(parsed_agent) = agent_part.parse::<u8>() {
            (underscore_idx, Some(parsed_agent))
        } else {
            (user_agent.len(), None)
        }
    } else {
        (user_agent.len(), None)
    };

    let agent_byte = agent_override.unwrap_or(0);
    let domain_type = if server == jid::HIDDEN_USER_SERVER {
        1
    } else if server == jid::HOSTED_SERVER {
        128
    } else if server == jid::HOSTED_LID_SERVER {
        129
    } else {
        agent_byte
    };

    Some(ParsedJidMeta {
        user_end,
        server_start,
        domain_type,
        device,
    })
}

#[inline]
fn split_jid_from_meta(input: &str, meta: ParsedJidMeta) -> (&str, &str) {
    (&input[..meta.user_end], &input[meta.server_start..])
}

/// Map a JID server string to the AD_JID domain_type byte.
///
/// The AD_JID binary encoding uses a single byte to identify the server:
///   0 = s.whatsapp.net (default)
///   1 = lid
///   128 = hosted
///   129 = hosted.lid
///
/// For unmapped servers, falls back to `agent` to match the string-path
/// behavior in `parse_jid_meta` (which uses `agent_byte` as the default).
///
/// WARNING: This must stay in sync with the string-path mapping in
/// `classify_string_hint` / `parse_jid_meta` and the inverse mapping in
/// `decoder.rs read_ad_jid`. Writing `jid.agent` unconditionally here
/// (instead of only as a fallback) was the root cause of a regression
/// where LID group messages were silently rejected by the server (error 421).
#[inline]
fn server_to_domain_type(server: &str, agent: u8) -> u8 {
    match server {
        jid::HIDDEN_USER_SERVER => 1,  // "lid"
        jid::HOSTED_SERVER => 128,     // "hosted"
        jid::HOSTED_LID_SERVER => 129, // "hosted.lid"
        _ => agent,                    // s.whatsapp.net (0) and exotic servers
    }
}

#[inline]
fn classify_string_hint(s: &str) -> StringHint {
    if s.is_empty() {
        return StringHint::Empty;
    }

    let is_likely_jid = s.len() <= 48;

    if let Some(token) = token::index_of_single_token(s) {
        StringHint::SingleToken(token)
    } else if let Some((dict, token)) = token::index_of_double_byte_token(s) {
        StringHint::DoubleToken { dict, token }
    } else if validate_nibble(s) {
        StringHint::PackedNibble
    } else if validate_hex(s) {
        StringHint::PackedHex
    } else if is_likely_jid {
        parse_jid_meta(s).map_or(StringHint::RawBytes, StringHint::Jid)
    } else {
        StringHint::RawBytes
    }
}

pub(crate) fn build_marshaled_node_plan(node: &Node) -> MarshaledSizePlan {
    let mut hints = StringHintCache::default();
    let size = 1 + node_encoded_size_with_cache(node, &mut hints);
    MarshaledSizePlan { size, hints }
}

pub(crate) fn build_marshaled_node_ref_plan(node: &NodeRef<'_>) -> MarshaledSizePlan {
    let mut hints = StringHintCache::default();
    let size = 1 + node_ref_encoded_size_with_cache(node, &mut hints);
    MarshaledSizePlan { size, hints }
}

#[inline]
fn list_start_encoded_size(len: usize) -> usize {
    if len == 0 {
        1
    } else if len < 256 {
        2
    } else {
        3
    }
}

#[inline]
fn binary_len_prefix_size(len: usize) -> usize {
    if len < 256 {
        2
    } else if len < (1 << 20) {
        4
    } else {
        5
    }
}

#[inline]
fn bytes_with_len_encoded_size(len: usize) -> usize {
    binary_len_prefix_size(len) + len
}

#[inline]
fn packed_encoded_size(value_len: usize) -> usize {
    2 + value_len.div_ceil(2)
}

fn node_encoded_size_with_cache(node: &Node, hints: &mut StringHintCache) -> usize {
    let content_len = usize::from(node.content.is_some());
    let list_len = 1 + (node.attrs.len() * 2) + content_len;

    let attrs_size: usize = node
        .attrs
        .iter()
        .map(|(k, v)| {
            let value_size = match v {
                NodeValue::String(s) => string_encoded_size_with_cache(s, hints),
                NodeValue::Jid(jid) => owned_jid_encoded_size_with_cache(jid, hints),
            };
            string_encoded_size_with_cache(k, hints) + value_size
        })
        .sum();

    let content_size = match &node.content {
        Some(NodeContent::String(s)) => string_encoded_size_with_cache(s, hints),
        Some(NodeContent::Bytes(b)) => bytes_with_len_encoded_size(b.len()),
        Some(NodeContent::Nodes(nodes)) => {
            list_start_encoded_size(nodes.len())
                + nodes
                    .iter()
                    .map(|child| node_encoded_size_with_cache(child, hints))
                    .sum::<usize>()
        }
        None => 0,
    };

    list_start_encoded_size(list_len)
        + string_encoded_size_with_cache(&node.tag, hints)
        + attrs_size
        + content_size
}

fn node_ref_encoded_size_with_cache(node: &NodeRef<'_>, hints: &mut StringHintCache) -> usize {
    let content_len = usize::from(node.content.is_some());
    let list_len = 1 + (node.attrs.len() * 2) + content_len;

    let attrs_size: usize = node
        .attrs
        .iter()
        .map(|(k, v)| {
            let value_size = match v {
                ValueRef::String(s) => string_encoded_size_with_cache(s, hints),
                ValueRef::Jid(jid) => jid_ref_encoded_size_with_cache(jid, hints),
            };
            string_encoded_size_with_cache(k, hints) + value_size
        })
        .sum();

    let content_size = match node.content.as_deref() {
        Some(NodeContentRef::String(s)) => string_encoded_size_with_cache(s, hints),
        Some(NodeContentRef::Bytes(b)) => bytes_with_len_encoded_size(b.len()),
        Some(NodeContentRef::Nodes(nodes)) => {
            list_start_encoded_size(nodes.len())
                + nodes
                    .iter()
                    .map(|child| node_ref_encoded_size_with_cache(child, hints))
                    .sum::<usize>()
        }
        None => 0,
    };

    list_start_encoded_size(list_len)
        + string_encoded_size_with_cache(node.tag.as_ref(), hints)
        + attrs_size
        + content_size
}

#[inline]
fn string_encoded_size_with_cache(s: &str, hints: &mut StringHintCache) -> usize {
    let hint = hints.hint_or_insert(s);
    string_encoded_size_from_hint_with_cache(s, hint, hints)
}

#[inline]
fn string_encoded_size_from_hint_with_cache(
    s: &str,
    hint: StringHint,
    hints: &mut StringHintCache,
) -> usize {
    match hint {
        StringHint::Empty => 2,
        StringHint::SingleToken(_) => 1,
        StringHint::DoubleToken { .. } => 2,
        StringHint::PackedNibble | StringHint::PackedHex => packed_encoded_size(s.len()),
        StringHint::RawBytes => bytes_with_len_encoded_size(s.len()),
        StringHint::Jid(meta) => parsed_jid_encoded_size_with_cache(s, meta, hints),
    }
}

#[inline]
fn parsed_jid_encoded_size_with_cache(
    jid: &str,
    meta: ParsedJidMeta,
    hints: &mut StringHintCache,
) -> usize {
    let (user, server) = split_jid_from_meta(jid, meta);
    if meta.device.is_some() {
        3 + string_encoded_size_with_cache(user, hints)
    } else {
        let user_size = if user.is_empty() {
            1
        } else {
            string_encoded_size_with_cache(user, hints)
        };
        1 + user_size + string_encoded_size_with_cache(server, hints)
    }
}

#[inline]
fn owned_jid_encoded_size_with_cache(jid: &Jid, hints: &mut StringHintCache) -> usize {
    if jid.device > 0 {
        3 + string_encoded_size_with_cache(&jid.user, hints)
    } else {
        let user_size = if jid.user.is_empty() {
            1
        } else {
            string_encoded_size_with_cache(&jid.user, hints)
        };
        1 + user_size + string_encoded_size_with_cache(&jid.server, hints)
    }
}

#[inline]
fn jid_ref_encoded_size_with_cache(jid: &JidRef<'_>, hints: &mut StringHintCache) -> usize {
    if jid.device > 0 {
        3 + string_encoded_size_with_cache(&jid.user, hints)
    } else {
        let user_size = if jid.user.is_empty() {
            1
        } else {
            string_encoded_size_with_cache(&jid.user, hints)
        };
        1 + user_size + string_encoded_size_with_cache(&jid.server, hints)
    }
}

#[inline]
fn validate_nibble(value: &str) -> bool {
    if value.len() > token::PACKED_MAX as usize {
        return false;
    }
    value
        .as_bytes()
        .iter()
        .all(|&b| b.is_ascii_digit() || b == b'-' || b == b'.')
}

#[inline]
fn validate_hex(value: &str) -> bool {
    if value.len() > token::PACKED_MAX as usize {
        return false;
    }
    value
        .as_bytes()
        .iter()
        .all(|&b| b.is_ascii_digit() || (b'A'..=b'F').contains(&b))
}

pub(crate) struct Encoder<'a, W: ByteWriter> {
    writer: W,
    string_hints: Option<&'a StringHintCache>,
}

impl<W: Write> Encoder<'static, IoByteWriter<W>> {
    pub(crate) fn new(writer: W) -> Result<Self> {
        let mut enc = Self {
            writer: IoByteWriter::new(writer),
            string_hints: None,
        };
        enc.write_u8(0)?;
        Ok(enc)
    }
}

impl<'v> Encoder<'static, VecByteWriter<'v>> {
    pub(crate) fn new_vec(buffer: &'v mut Vec<u8>) -> Result<Self> {
        let mut enc = Self {
            writer: VecByteWriter::new(buffer),
            string_hints: None,
        };
        enc.write_u8(0)?;
        Ok(enc)
    }
}

impl<'a> Encoder<'a, SliceByteWriter<'a>> {
    pub(crate) fn new_slice(
        buffer: &'a mut [u8],
        string_hints: Option<&'a StringHintCache>,
    ) -> Result<Self> {
        let mut enc = Self {
            writer: SliceByteWriter::new(buffer),
            string_hints,
        };
        enc.write_u8(0)?;
        Ok(enc)
    }

    #[inline]
    pub(crate) fn bytes_written(&self) -> usize {
        self.writer.bytes_written()
    }
}

impl<'a, W: ByteWriter> Encoder<'a, W> {
    #[inline(always)]
    fn write_u8(&mut self, val: u8) -> Result<()> {
        self.writer.write_u8(val)
    }

    #[inline(always)]
    fn write_u16_be(&mut self, val: u16) -> Result<()> {
        self.writer.write_bytes(&val.to_be_bytes())
    }

    #[inline(always)]
    fn write_u32_be(&mut self, val: u32) -> Result<()> {
        self.writer.write_bytes(&val.to_be_bytes())
    }

    #[inline(always)]
    fn write_u20_be(&mut self, value: u32) -> Result<()> {
        let bytes = [
            ((value >> 16) & 0x0F) as u8,
            ((value >> 8) & 0xFF) as u8,
            (value & 0xFF) as u8,
        ];
        self.writer.write_bytes(&bytes)
    }

    #[inline(always)]
    fn write_raw_bytes(&mut self, bytes: &[u8]) -> Result<()> {
        self.writer.write_bytes(bytes)
    }

    #[inline(always)]
    fn write_bytes_with_len(&mut self, bytes: &[u8]) -> Result<()> {
        let len = bytes.len();
        if len < 256 {
            self.write_u8(token::BINARY_8)?;
            self.write_u8(len as u8)?;
        } else if len < (1 << 20) {
            self.write_u8(token::BINARY_20)?;
            self.write_u20_be(len as u32)?;
        } else {
            self.write_u8(token::BINARY_32)?;
            self.write_u32_be(len as u32)?;
        }
        self.write_raw_bytes(bytes)
    }

    #[inline(always)]
    fn write_string(&mut self, s: &str) -> Result<()> {
        if let Some(string_hints) = self.string_hints
            && let Some(hint) = string_hints.hint_for(s)
        {
            return self.write_string_with_hint(s, hint);
        }
        self.write_string_uncached(s)
    }

    #[inline(always)]
    fn write_string_uncached(&mut self, s: &str) -> Result<()> {
        self.write_string_with_hint(s, classify_string_hint(s))
    }

    #[inline(always)]
    fn write_string_with_hint(&mut self, s: &str, hint: StringHint) -> Result<()> {
        match hint {
            StringHint::Empty => {
                self.write_u8(token::BINARY_8)?;
                self.write_u8(0)?;
            }
            StringHint::SingleToken(token) => self.write_u8(token)?,
            StringHint::DoubleToken { dict, token } => {
                self.write_u8(token::DICTIONARY_0 + dict)?;
                self.write_u8(token)?;
            }
            StringHint::PackedNibble => self.write_packed_bytes(s, token::NIBBLE_8)?,
            StringHint::PackedHex => self.write_packed_bytes(s, token::HEX_8)?,
            StringHint::Jid(meta) => self.write_jid_from_meta(s, meta)?,
            StringHint::RawBytes => self.write_bytes_with_len(s.as_bytes())?,
        }
        Ok(())
    }

    #[inline(always)]
    fn write_jid_from_meta(&mut self, jid: &str, meta: ParsedJidMeta) -> Result<()> {
        let (user, server) = split_jid_from_meta(jid, meta);
        if let Some(device) = meta.device {
            self.write_u8(token::AD_JID)?;
            self.write_u8(meta.domain_type)?;
            self.write_u8(device)?;
            self.write_string(user)?;
        } else {
            self.write_u8(token::JID_PAIR)?;
            if user.is_empty() {
                self.write_u8(token::LIST_EMPTY)?;
            } else {
                self.write_string(user)?;
            }
            self.write_string(server)?;
        }
        Ok(())
    }

    /// Write a JidRef directly without converting to string first.
    /// This avoids the allocation that would occur with `jid.to_string()`.
    fn write_jid_ref(&mut self, jid: &JidRef<'_>) -> Result<()> {
        if jid.device > 0 {
            // AD_JID format: domain_type, device, user
            let device = u8::try_from(jid.device).map_err(|_| {
                BinaryError::AttrParse(format!("AD_JID device id out of range: {}", jid.device))
            })?;
            self.write_u8(token::AD_JID)?;
            self.write_u8(server_to_domain_type(&jid.server, jid.agent))?;
            self.write_u8(device)?;
            self.write_string(&jid.user)?;
        } else {
            // JID_PAIR format: user, server
            self.write_u8(token::JID_PAIR)?;
            if jid.user.is_empty() {
                self.write_u8(token::LIST_EMPTY)?;
            } else {
                self.write_string(&jid.user)?;
            }
            self.write_string(&jid.server)?;
        }
        Ok(())
    }

    /// Write an owned Jid directly without converting to string first.
    /// This avoids the allocation that would occur with `jid.to_string()`.
    fn write_jid_owned(&mut self, jid: &Jid) -> Result<()> {
        if jid.device > 0 {
            // AD_JID format: domain_type, device, user
            let device = u8::try_from(jid.device).map_err(|_| {
                BinaryError::AttrParse(format!("AD_JID device id out of range: {}", jid.device))
            })?;
            self.write_u8(token::AD_JID)?;
            self.write_u8(server_to_domain_type(jid.server.as_ref(), jid.agent))?;
            self.write_u8(device)?;
            self.write_string(&jid.user)?;
        } else {
            // JID_PAIR format: user, server
            self.write_u8(token::JID_PAIR)?;
            if jid.user.is_empty() {
                self.write_u8(token::LIST_EMPTY)?;
            } else {
                self.write_string(&jid.user)?;
            }
            self.write_string(&jid.server)?;
        }
        Ok(())
    }

    #[inline(always)]
    fn pack_nibble(value: u8) -> u8 {
        match value {
            b'-' => 10,
            b'.' => 11,
            0 => 15,
            c if c.is_ascii_digit() => c - b'0',
            _ => panic!("Invalid char for nibble packing: {value}"),
        }
    }

    #[inline(always)]
    fn pack_hex(value: u8) -> u8 {
        match value {
            c if c.is_ascii_digit() => c - b'0',
            c if (b'A'..=b'F').contains(&c) => 10 + (c - b'A'),
            0 => 15,
            _ => panic!("Invalid char for hex packing: {value}"),
        }
    }

    #[inline(always)]
    fn pack_byte_pair(packer: fn(u8) -> u8, part1: u8, part2: u8) -> u8 {
        (packer(part1) << 4) | packer(part2)
    }

    fn write_packed_bytes(&mut self, value: &str, data_type: u8) -> Result<()> {
        if value.len() > token::PACKED_MAX as usize {
            panic!("String too long to be packed: {}", value.len());
        }

        self.write_u8(data_type)?;

        let mut rounded_len = value.len().div_ceil(2) as u8;
        if !value.len().is_multiple_of(2) {
            rounded_len |= 0x80;
        }
        self.write_u8(rounded_len)?;

        #[allow(unused_mut)]
        let mut input_bytes = value.as_bytes();

        if data_type == token::NIBBLE_8 {
            #[cfg(feature = "simd")]
            {
                const NIBBLE_LOOKUP: [u8; 16] =
                    [10, 11, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255];
                let lookup = Simd::from_array(NIBBLE_LOOKUP);
                let nibble_base = Simd::splat(b'-');

                while input_bytes.len() >= 16 {
                    let (chunk, rest) = input_bytes.split_at(16);
                    let input = u8x16::from_slice(chunk);
                    let indices = input.saturating_sub(nibble_base);
                    let nibbles = lookup.swizzle_dyn(indices);

                    let (evens, odds) = nibbles.deinterleave(nibbles.rotate_elements_left::<1>());
                    let packed: Simd<u8, 16> = (evens << Simd::splat(4)) | odds;
                    let packed_bytes = packed.to_array();
                    self.write_raw_bytes(&packed_bytes[..8])?;

                    input_bytes = rest;
                }
            }

            let mut bytes_iter = input_bytes.iter().copied();
            while let Some(part1) = bytes_iter.next() {
                let part2 = bytes_iter.next().unwrap_or(0);
                self.write_u8(Self::pack_byte_pair(Self::pack_nibble, part1, part2))?;
            }
        } else {
            #[cfg(feature = "simd")]
            {
                let ascii_0 = Simd::splat(b'0');
                let ascii_a = Simd::splat(b'A');
                let ten = Simd::splat(10);

                while input_bytes.len() >= 16 {
                    let (chunk, rest) = input_bytes.split_at(16);
                    let input = u8x16::from_slice(chunk);

                    let digit_vals = input - ascii_0;
                    let letter_vals = input - ascii_a + ten;
                    let is_letter = input.simd_ge(ascii_a);
                    let nibbles = is_letter.select(letter_vals, digit_vals);

                    let (evens, odds) = nibbles.deinterleave(nibbles.rotate_elements_left::<1>());
                    let packed: Simd<u8, 16> = (evens << Simd::splat(4)) | odds;
                    let packed_bytes = packed.to_array();
                    self.write_raw_bytes(&packed_bytes[..8])?;

                    input_bytes = rest;
                }
            }

            let mut bytes_iter = input_bytes.iter().copied();
            while let Some(part1) = bytes_iter.next() {
                let part2 = bytes_iter.next().unwrap_or(0);
                self.write_u8(Self::pack_byte_pair(Self::pack_hex, part1, part2))?;
            }
        }
        Ok(())
    }

    fn write_list_start(&mut self, len: usize) -> Result<()> {
        if len == 0 {
            self.write_u8(token::LIST_EMPTY)?;
        } else if len < 256 {
            self.write_u8(248)?;
            self.write_u8(len as u8)?;
        } else {
            self.write_u8(249)?;
            self.write_u16_be(len as u16)?;
        }
        Ok(())
    }

    /// Write any node type (owned or borrowed) using the EncodeNode trait.
    pub(crate) fn write_node<N: EncodeNode>(&mut self, node: &N) -> Result<()> {
        let content_len = if node.has_content() { 1 } else { 0 };
        let list_len = 1 + (node.attrs_len() * 2) + content_len;

        self.write_list_start(list_len)?;
        self.write_string(node.tag())?;
        node.encode_attrs(self)?;
        node.encode_content(self)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::NodeBuilder;
    use crate::node::Attrs;
    use std::io::Cursor;

    type TestResult = crate::error::Result<()>;

    #[test]
    fn test_encode_node() -> TestResult {
        let node = Node::new(
            "message",
            Attrs::new(),
            Some(NodeContent::String("receipt".to_string())),
        );

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&node)?;

        let expected = vec![0, 248, 2, 19, 7];
        assert_eq!(buffer, expected);
        assert_eq!(buffer.len(), 5);
        Ok(())
    }

    #[test]
    fn test_nibble_packing() -> TestResult {
        // Test string with nibble characters: '-', '.', '0'-'9'
        let test_str = "-.0123456789";
        let node = Node::new(
            "test",
            Attrs::new(),
            Some(NodeContent::String(test_str.to_string())),
        );

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&node)?;

        let expected = vec![
            0, 248, 2, 252, 4, 116, 101, 115, 116, 255, 6, 171, 1, 35, 69, 103, 137,
        ];
        assert_eq!(buffer, expected);
        assert_eq!(buffer.len(), 17);
        Ok(())
    }

    /// Test LIST_8 boundary (length 255)
    #[test]
    fn test_list_size_list8_boundary() -> TestResult {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;

        // LIST_8 should be used for lengths 1-255
        encoder.write_list_start(255)?;

        // Expected: LIST_8 (248), then length 255
        assert_eq!(buffer[1], token::LIST_8);
        assert_eq!(buffer[2], 255);
        Ok(())
    }

    /// Test LIST_16 boundary (length 256)
    #[test]
    fn test_list_size_list16_boundary() -> TestResult {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;

        // LIST_16 should be used for lengths 256+
        encoder.write_list_start(256)?;

        // Expected: LIST_16 (249), then length as u16 big-endian
        assert_eq!(buffer[1], token::LIST_16);
        assert_eq!(buffer[2], 0x01); // 256 >> 8
        assert_eq!(buffer[3], 0x00); // 256 & 0xFF
        Ok(())
    }

    /// Test empty list encoding
    #[test]
    fn test_list_size_empty() -> TestResult {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;

        encoder.write_list_start(0)?;

        // Empty list uses LIST_EMPTY token
        assert_eq!(buffer[1], token::LIST_EMPTY);
        Ok(())
    }

    /// Test hex packing validation
    #[test]
    fn test_hex_validation() {
        // Valid hex strings (uppercase A-F, digits 0-9)
        assert!(validate_hex("0123456789ABCDEF"));
        assert!(validate_hex("DEADBEEF"));
        assert!(validate_hex("1234"));

        // Invalid: lowercase letters
        assert!(!validate_hex("abcdef"));
        assert!(!validate_hex("DeadBeef"));

        // Invalid: special characters
        assert!(!validate_hex("-"));
        assert!(!validate_hex("."));
        assert!(!validate_hex(" "));

        // Empty string is valid (but will be encoded as regular string)
        assert!(validate_hex(""));
    }

    /// Test nibble packing validation
    #[test]
    fn test_nibble_validation() {
        // Valid nibble strings: digits, dash, dot
        assert!(validate_nibble("0123456789"));
        assert!(validate_nibble("-"));
        assert!(validate_nibble("."));
        assert!(validate_nibble("123-456.789"));

        // Invalid: letters
        assert!(!validate_nibble("abc"));
        assert!(!validate_nibble("123abc"));

        // Invalid: uppercase letters
        assert!(!validate_nibble("ABC"));

        // Invalid: special characters other than - and .
        assert!(!validate_nibble("123!456"));
        assert!(!validate_nibble("@"));
    }

    /// Test BINARY_8, BINARY_20, BINARY_32 boundary transitions
    #[test]
    fn test_binary_length_boundaries() -> TestResult {
        // BINARY_8: length < 256
        let short_data = vec![0x42; 255];
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_bytes_with_len(&short_data)?;
        assert_eq!(buffer[1], token::BINARY_8);
        assert_eq!(buffer[2], 255);

        // BINARY_20: 256 <= length < 2^20
        let medium_data = vec![0x42; 256];
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_bytes_with_len(&medium_data)?;
        assert_eq!(buffer[1], token::BINARY_20);
        // 256 in u20 big-endian: 0x00, 0x01, 0x00
        assert_eq!(buffer[2], 0x00);
        assert_eq!(buffer[3], 0x01);
        assert_eq!(buffer[4], 0x00);

        Ok(())
    }

    /// Test node with many children uses correct list encoding
    #[test]
    fn test_node_with_255_children() -> TestResult {
        let children: Vec<Node> = (0..255)
            .map(|_| Node::new("child", Attrs::new(), None))
            .collect();

        let parent = Node::new("parent", Attrs::new(), Some(NodeContent::Nodes(children)));

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&parent)?;

        // Should encode successfully with LIST_8 for children
        assert!(!buffer.is_empty());
        Ok(())
    }

    /// Test node with 256 children uses LIST_16
    #[test]
    fn test_node_with_256_children() -> TestResult {
        let children: Vec<Node> = (0..256)
            .map(|_| Node::new("x", Attrs::new(), None))
            .collect();

        let parent = Node::new("parent", Attrs::new(), Some(NodeContent::Nodes(children)));

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&parent)?;

        // Should encode successfully with LIST_16 for children
        assert!(!buffer.is_empty());
        Ok(())
    }

    /// Test string at PACKED_MAX boundary (127 chars)
    #[test]
    fn test_packed_max_boundary() {
        // Exactly PACKED_MAX characters should be valid for packing
        let max_nibble = "0".repeat(token::PACKED_MAX as usize);
        assert!(validate_nibble(&max_nibble));

        // One more than PACKED_MAX should NOT be packed
        let over_max = "0".repeat(token::PACKED_MAX as usize + 1);
        assert!(!validate_nibble(&over_max));
    }

    /// Test empty string encoding - should be BINARY_8 + 0, not just 0
    #[test]
    fn test_empty_string_encoding() -> TestResult {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_string("")?;

        // According to WhatsApp web protocol:
        // Empty string should be encoded as BINARY_8 (252) + 0
        // NOT as token 0 (LIST_EMPTY)
        println!("Empty string encoding: {:?}", &buffer[1..]);
        assert_eq!(
            buffer.len(),
            3,
            "Empty string should encode to 2 bytes (plus leading 0)"
        );
        assert_eq!(
            buffer[1],
            token::BINARY_8,
            "First byte should be BINARY_8 (252)"
        );
        assert_eq!(buffer[2], 0, "Second byte should be 0 (length)");
        Ok(())
    }

    /// Test encode/decode round-trip for empty string in node attributes
    #[test]
    fn test_empty_string_roundtrip() -> TestResult {
        use crate::decoder::Decoder;

        let mut attrs = Attrs::new();
        attrs.insert("key", ""); // Empty value
        attrs.insert("", "value"); // Empty key

        let node = Node::new("test", attrs, Some(NodeContent::String("".to_string())));

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&node)?;

        let mut decoder = Decoder::new(&buffer[1..]);
        let decoded = decoder.read_node_ref()?.to_owned();

        assert_eq!(decoded.tag, "test");
        assert_eq!(
            decoded.attrs.get("key"),
            Some(&NodeValue::String("".to_string()))
        );
        assert_eq!(
            decoded.attrs.get(""),
            Some(&NodeValue::String("value".to_string()))
        );

        // Empty strings are encoded as BINARY_8 + 0, which decodes as empty bytes
        match &decoded.content {
            Some(NodeContent::Bytes(b)) => assert!(b.is_empty(), "Content should be empty bytes"),
            other => panic!("Expected empty bytes, got {:?}", other),
        }
        Ok(())
    }

    /// Test the JID parsing optimization: short JIDs should still be parsed,
    /// while long strings should be encoded as raw bytes.
    #[test]
    fn test_jid_length_heuristic() -> TestResult {
        use crate::decoder::Decoder;
        use crate::token;

        // Short JID: should be encoded as a JID token (48 bytes or less)
        let short_jid = "user@s.whatsapp.net";
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_string(short_jid)?;

        // JID_PAIR token indicates JID encoding was used
        assert_eq!(
            buffer[1],
            token::JID_PAIR,
            "Short JID should be encoded as JID_PAIR token"
        );

        // Long string (> 48 chars): should be encoded as raw bytes, not as JID
        let long_text = "x".repeat(300) + "@s.whatsapp.net";
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_string(&long_text)?;

        // BINARY_20 token indicates raw bytes encoding (length > 255)
        assert_eq!(
            buffer[1],
            token::BINARY_20,
            "Long string should be encoded as BINARY_20, not as JID"
        );

        // Verify round-trip for long string
        let node = Node::new(
            "msg",
            Attrs::new(),
            Some(NodeContent::String(long_text.clone())),
        );
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&node)?;

        let mut decoder = Decoder::new(&buffer[1..]);
        let decoded = decoder.read_node_ref()?.to_owned();
        match &decoded.content {
            Some(NodeContent::Bytes(b)) => {
                assert_eq!(
                    String::from_utf8_lossy(b),
                    long_text,
                    "Long string should round-trip correctly"
                );
            }
            other => panic!("Expected bytes content, got {:?}", other),
        }

        Ok(())
    }

    #[test]
    fn test_jid_parser_preserves_non_numeric_device_suffix() -> TestResult {
        use crate::decoder::Decoder;

        let value = "foo:bar@s.whatsapp.net";
        let node = Node::new(
            "msg",
            Attrs::new(),
            Some(NodeContent::String(value.to_string())),
        );

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&node)?;

        let mut decoder = Decoder::new(&buffer[1..]);
        let decoded = decoder.read_node_ref()?.to_owned();
        match decoded.content {
            Some(NodeContent::String(s)) => assert_eq!(s, value),
            other => panic!("Expected string content, got {:?}", other),
        }
        Ok(())
    }

    #[test]
    fn test_jid_parser_preserves_non_numeric_agent_suffix() -> TestResult {
        use crate::decoder::Decoder;

        let value = "hello_world@s.whatsapp.net";
        let node = Node::new(
            "msg",
            Attrs::new(),
            Some(NodeContent::String(value.to_string())),
        );

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&node)?;

        let mut decoder = Decoder::new(&buffer[1..]);
        let decoded = decoder.read_node_ref()?.to_owned();
        match decoded.content {
            Some(NodeContent::String(s)) => assert_eq!(s, value),
            other => panic!("Expected string content, got {:?}", other),
        }
        Ok(())
    }

    /// Regression test: AD_JID domain_type must be derived from the server field,
    /// not from jid.agent.
    ///
    /// The binary AD_JID format is: [0xF7] [domain_type] [device] [user_string]
    /// where domain_type encodes the server: 0=s.whatsapp.net, 1=lid, 128=hosted.
    ///
    /// A previous bug wrote `jid.agent` (always 0) instead of the domain_type,
    /// causing LID JIDs to be encoded as s.whatsapp.net JIDs. The real WhatsApp
    /// server rejected these with error 421, while our mock server accepted them
    /// because it doesn't validate domain_type — hence e2e tests didn't catch it.
    #[test]
    fn test_ad_jid_domain_type_lid() -> TestResult {
        // Encode a LID device JID as a node attribute
        let lid_jid = Jid::lid_device("236395184570386", 39);
        let node = NodeBuilder::new("to").attr("jid", lid_jid).build();

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&node)?;

        // Find the AD_JID marker (0xF7 = 247) in the encoded bytes
        let ad_jid_pos = buffer
            .iter()
            .position(|&b| b == token::AD_JID)
            .expect("AD_JID token (0xF7) must be present for device JID");

        // Byte after AD_JID is domain_type: must be 1 for "lid"
        let domain_type = buffer[ad_jid_pos + 1];
        assert_eq!(
            domain_type, 1,
            "LID JID must encode domain_type=1 (lid), got {domain_type} (0=whatsapp, 128=hosted)"
        );

        // Byte after domain_type is device
        let device = buffer[ad_jid_pos + 2];
        assert_eq!(device, 39, "Device byte must be 39");

        Ok(())
    }

    #[test]
    fn test_ad_jid_domain_type_whatsapp() -> TestResult {
        let pn_jid = Jid::pn_device("559984726662", 33);
        let node = NodeBuilder::new("to").attr("jid", pn_jid).build();

        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(Cursor::new(&mut buffer))?;
        encoder.write_node(&node)?;

        let ad_jid_pos = buffer
            .iter()
            .position(|&b| b == token::AD_JID)
            .expect("AD_JID token must be present for device JID");

        let domain_type = buffer[ad_jid_pos + 1];
        assert_eq!(
            domain_type, 0,
            "s.whatsapp.net JID must encode domain_type=0, got {domain_type}"
        );

        Ok(())
    }

    /// Verify that string-encoded JIDs and direct Jid-encoded JIDs produce
    /// identical bytes AND decode back to the same JID. This catches any
    /// divergence between the two encoding paths (root cause of the domain_type
    /// bug) and ensures encode→decode round-trip fidelity for all server types.
    #[test]
    fn test_jid_string_vs_direct_encoding_matches() -> TestResult {
        use crate::decoder::Decoder;

        let test_cases: Vec<Jid> = vec![
            Jid::lid_device("236395184570386", 39),     // LID with device
            Jid::pn_device("559984726662", 33),         // PN with device
            Jid::lid("236395184570386"),                // LID primary (device 0)
            Jid::pn("559984726662"),                    // PN primary (device 0)
            "5511999887766:99@hosted".parse().unwrap(), // HOSTED device
            "100000012345678:99@hosted.lid".parse().unwrap(), // HOSTED_LID device
        ];

        for jid in test_cases {
            // Path 1: string encoding (known correct — uses parse_jid_meta)
            let node_str = NodeBuilder::new("to").attr("jid", jid.to_string()).build();

            // Path 2: direct Jid encoding (uses write_jid_owned)
            let node_jid = NodeBuilder::new("to").attr("jid", jid.clone()).build();

            let mut buf_str = Vec::new();
            Encoder::new(Cursor::new(&mut buf_str))?.write_node(&node_str)?;

            let mut buf_jid = Vec::new();
            Encoder::new(Cursor::new(&mut buf_jid))?.write_node(&node_jid)?;

            assert_eq!(
                buf_str, buf_jid,
                "String vs direct Jid encoding must produce identical bytes for {jid}"
            );

            // Round-trip: decode the encoded bytes and verify the JID is preserved.
            // Skip version byte (first byte) then decode.
            let mut decoder = Decoder::new(&buf_jid[1..]);
            let decoded_node = decoder.read_node_ref()?.to_owned();
            let decoded_jid: Jid = decoded_node
                .attrs()
                .optional_jid("jid")
                .expect("jid attr must round-trip as JID");

            assert_eq!(
                jid.user, decoded_jid.user,
                "Round-trip user mismatch for {jid}"
            );
            assert_eq!(
                jid.device, decoded_jid.device,
                "Round-trip device mismatch for {jid}"
            );
            assert_eq!(
                jid.server.as_ref(),
                decoded_jid.server.as_ref(),
                "Round-trip server mismatch for {jid}"
            );
        }

        Ok(())
    }
}