libxml-rs 0.1.0-alpha.4

Phase 3: I/O, encoding, URI, catalog, serialization, HTML. Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. 357 tests passing, full encoding subsystem, URI parser, OASIS catalog, HTML parser/serializer, tree serialization, custom I/O buffers.
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
//! Parser input buffer management — safe Rust wrapper (§19.3, §20.4).
//!
//! This module provides internal safe-Rust abstractions over XML input sources:
//! memory buffers, files, and custom I/O callbacks. It handles character-level
//! reading with position tracking (line/column/byte-offset), BOM detection,
//! encoding detection from XML declarations, and entity-expansion input stacks.
//!
//! # Architecture
//!
//! ```text
//! C ABI (_xmlParserInput, _xmlParserInputBuffer)
//!         ↕  populate / read from
//! InputBuffer (safe internal representation)
//!         ↕  stack management
//! InputStack (entity expansion nesting)
//! ```
//!
//! The safe types (`InputBuffer`, `InputStack`, `InputSource`) are NOT `#[repr(C)]`;
//! they are implementation details. C ABI structs are only populated when crossing
//! the FFI boundary.

#![allow(dead_code)]

use crate::abi::callbacks::{xmlInputCloseCallback, xmlInputReadCallback};
use crate::abi::structs::{_xmlParserInput, _xmlParserInputBuffer};
use crate::abi::types::xmlCharEncoding;
use std::fs;
use std::io::Read;
use std::os::raw::{c_char, c_int, c_ulong, c_void};
use std::path::Path;

// ═══════════════════════════════════════════════════════════════════════════════
// Encoding
// ═══════════════════════════════════════════════════════════════════════════════

/// Internal encoding representation (not `#[repr(C)]`).
///
/// Maps to [`xmlCharEncoding`] for FFI conversion.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Encoding {
    /// No encoding detected / unknown.
    None,
    /// UTF-8.
    Utf8,
    /// UTF-16 little-endian.
    Utf16Le,
    /// UTF-16 big-endian.
    Utf16Be,
    /// US-ASCII.
    Ascii,
    /// ISO-8859-1 (Latin-1).
    Iso8859_1,
    /// Other encoding (name stored for reference).
    Other(String),
}

impl Encoding {
    /// Convert to the C ABI [`xmlCharEncoding`] value.
    pub(crate) fn to_xml_char_encoding(&self) -> xmlCharEncoding {
        match self {
            Self::None => xmlCharEncoding::XML_CHAR_ENCODING_NONE,
            Self::Utf8 => xmlCharEncoding::XML_CHAR_ENCODING_UTF8,
            Self::Utf16Le => xmlCharEncoding::XML_CHAR_ENCODING_UTF16LE,
            Self::Utf16Be => xmlCharEncoding::XML_CHAR_ENCODING_UTF16BE,
            Self::Ascii => xmlCharEncoding::XML_CHAR_ENCODING_ASCII,
            Self::Iso8859_1 => xmlCharEncoding::XML_CHAR_ENCODING_8859_1,
            Self::Other(_) => xmlCharEncoding::XML_CHAR_ENCODING_ERROR,
        }
    }

    /// Parse an encoding name from an XML declaration.
    fn from_name(name: &str) -> Self {
        match name.trim().to_ascii_lowercase().as_str() {
            "utf-8" | "utf8" => Encoding::Utf8,
            "utf-16" | "utf16" => Encoding::Utf16Le, // default LE when no BOM
            "utf-16le" | "utf16le" => Encoding::Utf16Le,
            "utf-16be" | "utf16be" => Encoding::Utf16Be,
            "us-ascii" | "ascii" => Encoding::Ascii,
            "iso-8859-1" | "iso8859-1" | "latin1" | "latin-1" => Encoding::Iso8859_1,
            other => Encoding::Other(other.to_string()),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// InputSource
// ═══════════════════════════════════════════════════════════════════════════════

/// Internal abstraction over an XML input source.
///
/// This is NOT a `#[repr(C)]` type; it is a safe Rust implementation detail.
#[derive(Debug)]
pub(crate) enum InputSource {
    /// Data from an in-memory byte slice (copied into owned storage).
    Memory(Vec<u8>),
    /// Data from a file on disk.
    File {
        /// The file path.
        path: String,
        /// The open file handle.
        file: fs::File,
    },
    /// Data from custom I/O callbacks.
    Callback {
        /// Read callback — reads bytes into a buffer.
        read: xmlInputReadCallback,
        /// Close callback — called when the input is closed.
        close: xmlInputCloseCallback,
        /// Opaque context pointer passed to both callbacks.
        ctx: *mut c_void,
    },
}

impl InputSource {
    /// Read raw bytes from the source into a `Vec<u8>`.
    ///
    /// For memory sources this is a clone of the underlying data.
    /// For file sources this reads the entire file.
    /// For callback sources this reads incrementally until EOF.
    fn read_all(&mut self) -> Result<Vec<u8>, InputError> {
        match self {
            InputSource::Memory(data) => Ok(data.clone()),
            InputSource::File { file, .. } => {
                let mut buf = Vec::new();
                file.read_to_end(&mut buf)
                    .map_err(|e| InputError::Io(e.to_string()))?;
                Ok(buf)
            }
            InputSource::Callback { read, ctx, .. } => {
                let mut buf = Vec::new();
                let mut tmp = [0u8; 4096];
                loop {
                    // SAFETY: The caller guarantees that `read` is a valid function pointer
                    // and `ctx` is a valid pointer. The callback writes up to `tmp.len()`
                    // bytes into `tmp`. We trust the callback to not overrun the buffer.
                    let n =
                        unsafe { read(*ctx, tmp.as_mut_ptr() as *mut c_char, tmp.len() as c_int) };
                    if n < 0 {
                        return Err(InputError::Callback("read callback returned error".into()));
                    }
                    if n == 0 {
                        break; // EOF
                    }
                    buf.extend_from_slice(&tmp[..n as usize]);
                }
                Ok(buf)
            }
        }
    }

    /// Read a chunk of bytes into a buffer. Returns the number of bytes read.
    fn read_chunk(&mut self, buf: &mut [u8]) -> Result<usize, InputError> {
        match self {
            InputSource::Memory(_data) => {
                // Memory reads are handled by the buffer directly.
                Ok(0)
            }
            InputSource::File { file, .. } => {
                file.read(buf).map_err(|e| InputError::Io(e.to_string()))
            }
            InputSource::Callback { read, ctx, .. } => {
                // SAFETY: Same as in `read_all`.
                let n = unsafe { read(*ctx, buf.as_mut_ptr() as *mut c_char, buf.len() as c_int) };
                if n < 0 {
                    Err(InputError::Callback("read callback returned error".into()))
                } else {
                    Ok(n as usize)
                }
            }
        }
    }

    /// Get the filename/URI if available.
    fn filename(&self) -> Option<&str> {
        match self {
            InputSource::File { path, .. } => Some(path.as_str()),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// InputError
// ═══════════════════════════════════════════════════════════════════════════════

/// Errors that can occur during input operations.
#[derive(Debug)]
pub(crate) enum InputError {
    /// I/O error (file not found, permission denied, etc.).
    Io(String),
    /// Callback returned an error.
    Callback(String),
    /// Invalid UTF-8 sequence encountered.
    InvalidUtf8,
    /// Unexpected end of input.
    UnexpectedEof,
    /// Empty input.
    EmptyInput,
}

impl std::fmt::Display for InputError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InputError::Io(msg) => write!(f, "I/O error: {msg}"),
            InputError::Callback(msg) => write!(f, "callback error: {msg}"),
            InputError::InvalidUtf8 => write!(f, "invalid UTF-8 sequence"),
            InputError::UnexpectedEof => write!(f, "unexpected end of input"),
            InputError::EmptyInput => write!(f, "empty input"),
        }
    }
}

impl std::error::Error for InputError {}

// ═══════════════════════════════════════════════════════════════════════════════
// InputBuffer
// ═══════════════════════════════════════════════════════════════════════════════

/// Internal safe representation of an XML input source with position tracking.
///
/// This type is NOT `#[repr(C)]`. It is an internal implementation detail that
/// wraps raw input sources and provides character-level reading, line/column
/// tracking, BOM detection, and encoding detection.
///
/// # Position tracking
///
/// - Line numbers are 1-based (first line is line 1).
/// - Column numbers are 1-based (first column is col 1).
/// - Byte offset is 0-based from the start of the input.
/// - Both `\n` (LF) and `\r` (CR) increment the line counter.
/// - `\r\n` (CRLF) is treated as a single line break.
pub(crate) struct InputBuffer {
    /// The raw input source.
    source: InputSource,
    /// The complete buffered data (after any encoding conversion to UTF-8).
    data: Vec<u8>,
    /// Current byte position in `data`.
    pos: usize,
    /// Current line number (1-based).
    line: usize,
    /// Current column number (1-based).
    col: usize,
    /// Detected character encoding.
    encoding: Encoding,
    /// Filename or URI, if known.
    filename: Option<String>,
    /// Whether the BOM has been consumed.
    bom_consumed: bool,
}

impl std::fmt::Debug for InputBuffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InputBuffer")
            .field("source", &self.source)
            .field("pos", &self.pos)
            .field("line", &self.line)
            .field("col", &self.col)
            .field("encoding", &self.encoding)
            .field("filename", &self.filename)
            .field("len", &self.data.len())
            .field("bom_consumed", &self.bom_consumed)
            .finish()
    }
}

impl InputBuffer {
    // ── Constructors ───────────────────────────────────────────────────────

    /// Create an `InputBuffer` from an in-memory byte slice.
    ///
    /// The bytes are copied into an owned buffer. BOM and encoding detection
    /// are performed during construction.
    pub fn from_memory(buf: &[u8], uri: Option<&str>) -> Self {
        let data = buf.to_vec();
        let filename = uri.map(|s| s.to_string());
        let mut ib = InputBuffer {
            source: InputSource::Memory(data.clone()),
            data,
            pos: 0,
            line: 1,
            col: 1,
            encoding: Encoding::None,
            filename,
            bom_consumed: false,
        };
        ib.detect_bom_and_encoding();
        ib
    }

    /// Create an `InputBuffer` from a file on disk.
    ///
    /// Returns `Err` if the file cannot be opened or read.
    pub fn from_file(path: &str) -> Result<Self, InputError> {
        let p = Path::new(path);
        let file = fs::File::open(p).map_err(|e| InputError::Io(e.to_string()))?;
        let filename = Some(path.to_string());

        let mut source = InputSource::File {
            path: path.to_string(),
            file,
        };
        let data = source.read_all()?;

        let mut ib = InputBuffer {
            source,
            data,
            pos: 0,
            line: 1,
            col: 1,
            encoding: Encoding::None,
            filename,
            bom_consumed: false,
        };
        ib.detect_bom_and_encoding();
        Ok(ib)
    }

    /// Create an `InputBuffer` from custom I/O callbacks.
    ///
    /// The callbacks are used to read all available data from the source.
    pub fn from_callback(
        read: xmlInputReadCallback,
        close: xmlInputCloseCallback,
        ctx: *mut c_void,
    ) -> Result<Self, InputError> {
        let mut source = InputSource::Callback { read, close, ctx };
        let data = source.read_all()?;

        let mut ib = InputBuffer {
            source,
            data,
            pos: 0,
            line: 1,
            col: 1,
            encoding: Encoding::None,
            filename: None,
            bom_consumed: false,
        };
        ib.detect_bom_and_encoding();
        Ok(ib)
    }

    // ── BOM and encoding detection ─────────────────────────────────────────

    /// Detect BOM and encoding from the beginning of the data.
    ///
    /// This checks:
    /// 1. UTF-8 BOM (`EF BB BF`)
    /// 2. UTF-16 LE BOM (`FF FE`)
    /// 3. UTF-16 BE BOM (`FE FF`)
    /// 4. XML declaration (`<?xml encoding="..."?>`)
    ///
    /// The BOM is consumed (position advanced past it) so that subsequent
    /// reads start after the BOM.
    fn detect_bom_and_encoding(&mut self) {
        if self.data.is_empty() {
            self.encoding = Encoding::Utf8;
            return;
        }

        // Check for UTF-8 BOM: EF BB BF
        if self.data.len() >= 3
            && self.data[0] == 0xEF
            && self.data[1] == 0xBB
            && self.data[2] == 0xBF
        {
            self.encoding = Encoding::Utf8;
            self.pos = 3;
            self.col = 4; // BOM occupies columns 1-3
            self.bom_consumed = true;
            // After consuming BOM, check for XML declaration
            self.detect_encoding_from_xml_declaration();
            return;
        }

        // Check for UTF-16 LE BOM: FF FE
        if self.data.len() >= 2 && self.data[0] == 0xFF && self.data[1] == 0xFE {
            self.encoding = Encoding::Utf16Le;
            self.pos = 2;
            self.col = 3;
            self.bom_consumed = true;
            // We don't try to decode UTF-16 yet; mark and continue
            return;
        }

        // Check for UTF-16 BE BOM: FE FF
        if self.data.len() >= 2 && self.data[0] == 0xFE && self.data[1] == 0xFF {
            self.encoding = Encoding::Utf16Be;
            self.pos = 2;
            self.col = 3;
            self.bom_consumed = true;
            return;
        }

        // No BOM found. Default to UTF-8 and check for XML declaration.
        self.encoding = Encoding::Utf8;
        self.detect_encoding_from_xml_declaration();
    }

    /// Try to detect encoding from an XML declaration at the start of the input.
    ///
    /// Looks for `<?xml ... encoding="..."?>` or `<?xml ... encoding='...'?>`
    /// after any BOM has been consumed.
    fn detect_encoding_from_xml_declaration(&mut self) {
        let remaining = &self.data[self.pos..];

        // Must start with "<?xml"
        if remaining.len() < 5 {
            return;
        }
        if &remaining[..5] != b"<?xml" {
            return;
        }

        // Find the end of the PI: "?>"
        let pi_end = remaining.windows(2).position(|w| w == b"?>");
        let pi_end = match pi_end {
            Some(e) => e + 2,
            None => return, // Malformed PI, ignore
        };

        // Look for 'encoding' in the PI
        let pi_content = &remaining[..pi_end];
        let pi_str = match std::str::from_utf8(pi_content) {
            Ok(s) => s,
            Err(_) => return,
        };

        // Find encoding="..." or encoding='...'
        if let Some(enc) = Self::extract_encoding_from_pi(pi_str) {
            self.encoding = Encoding::from_name(&enc);
        }
    }

    /// Extract the encoding name from an XML processing instruction.
    ///
    /// Handles both single and double quotes around the encoding value.
    fn extract_encoding_from_pi(pi: &str) -> Option<String> {
        // Find "encoding" keyword
        let pi_lower = pi.to_ascii_lowercase();
        let kw_pos = pi_lower.find("encoding")?;

        let after_kw = &pi[kw_pos + 8..]; // skip past "encoding"
        let after_kw = after_kw.trim_start();

        // Must be followed by '='
        if !after_kw.starts_with('=') {
            return None;
        }
        let after_eq = after_kw[1..].trim_start();

        // Check for quote character
        let quote = after_eq.chars().next()?;
        if quote != '"' && quote != '\'' {
            return None;
        }

        // Find the closing quote
        let value_start = 1; // skip opening quote
        let value_end = after_eq[value_start..].find(quote)? + value_start;

        Some(after_eq[value_start..value_end].to_string())
    }

    // ── Character reading ──────────────────────────────────────────────────

    /// Read and return the next UTF-8 character, advancing the position.
    ///
    /// Returns `None` at EOF.
    ///
    /// Updates line/column tracking:
    /// - `\n` (LF) increments line, resets col.
    /// - `\r` (CR) increments line, resets col.
    /// - `\r\n` (CRLF) counts as one line break.
    /// - Tab advances col by 1 (libxml2 behavior).
    pub fn read_char(&mut self) -> Option<char> {
        let c = self.peek_char_inner()?;
        self.advance_past_char(c);
        Some(c)
    }

    /// Return the next UTF-8 character without advancing.
    ///
    /// Returns `None` at EOF.
    pub fn peek_char(&self) -> Option<char> {
        self.peek_char_inner()
    }

    /// Internal peek implementation.
    fn peek_char_inner(&self) -> Option<char> {
        if self.pos >= self.data.len() {
            return None;
        }

        let remaining = &self.data[self.pos..];
        Self::decode_utf8_char(remaining)
    }

    /// Decode a single UTF-8 character from the beginning of a byte slice.
    ///
    /// Returns `None` if the slice is empty or starts with an invalid sequence.
    fn decode_utf8_char(bytes: &[u8]) -> Option<char> {
        if bytes.is_empty() {
            return None;
        }

        let byte = bytes[0];
        let (code_point, _len) = if byte & 0x80 == 0 {
            // 1-byte sequence: 0xxxxxxx
            (u32::from(byte), 1)
        } else if byte & 0xE0 == 0xC0 {
            // 2-byte sequence: 110xxxxx 10xxxxxx
            if bytes.len() < 2 {
                return None;
            }
            let b1 = u32::from(bytes[1]);
            if b1 & 0xC0 != 0x80 {
                return None;
            }
            ((u32::from(byte & 0x1F) << 6) | (b1 & 0x3F), 2)
        } else if byte & 0xF0 == 0xE0 {
            // 3-byte sequence: 1110xxxx 10xxxxxx 10xxxxxx
            if bytes.len() < 3 {
                return None;
            }
            let b1 = u32::from(bytes[1]);
            let b2 = u32::from(bytes[2]);
            if b1 & 0xC0 != 0x80 || b2 & 0xC0 != 0x80 {
                return None;
            }
            (
                (u32::from(byte & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F),
                3,
            )
        } else if byte & 0xF8 == 0xF0 {
            // 4-byte sequence: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
            if bytes.len() < 4 {
                return None;
            }
            let b1 = u32::from(bytes[1]);
            let b2 = u32::from(bytes[2]);
            let b3 = u32::from(bytes[3]);
            if b1 & 0xC0 != 0x80 || b2 & 0xC0 != 0x80 || b3 & 0xC0 != 0x80 {
                return None;
            }
            (
                (u32::from(byte & 0x07) << 18)
                    | ((b1 & 0x3F) << 12)
                    | ((b2 & 0x3F) << 6)
                    | (b3 & 0x3F),
                4,
            )
        } else {
            // Invalid leading byte
            return None;
        };

        char::from_u32(code_point)
    }

    /// Get the byte length of the UTF-8 character starting at the current position.
    fn char_len(&self) -> usize {
        if self.pos >= self.data.len() {
            return 0;
        }
        Self::utf8_char_len(self.data[self.pos])
    }

    /// Determine the byte length of a UTF-8 character from its leading byte.
    fn utf8_char_len(leading: u8) -> usize {
        if leading & 0x80 == 0 {
            1
        } else if leading & 0xE0 == 0xC0 {
            2
        } else if leading & 0xF0 == 0xE0 {
            3
        } else if leading & 0xF8 == 0xF0 {
            4
        } else {
            // Invalid leading byte; treat as 1 byte to avoid stalling
            1
        }
    }

    /// Advance position past a character, updating line/col tracking.
    fn advance_past_char(&mut self, c: char) {
        let byte_len = self.char_len();
        let old_pos = self.pos;
        self.pos += byte_len;

        // Track the bytes we're advancing over for \r\n detection
        if byte_len == 1 && self.data[old_pos] == b'\n' {
            // LF: new line
            self.line += 1;
            self.col = 1;
        } else if byte_len == 1 && self.data[old_pos] == b'\r' {
            // CR: check for CRLF
            if self.pos < self.data.len() && self.data[self.pos] == b'\n' {
                // CRLF: consume the LF too and count as one line break
                self.pos += 1;
            }
            self.line += 1;
            self.col = 1;
        } else if c == '\t' {
            // Tab: advance col (libxml2 treats tab as single column)
            self.col += 1;
        } else {
            // Regular character
            self.col += 1;
        }
    }

    // ── Bulk reading ───────────────────────────────────────────────────────

    /// Read a string of up to `max_chars` characters.
    ///
    /// Returns the string read, which may be shorter than `max_chars` if EOF
    /// is encountered. Line/column tracking is updated for each character.
    pub fn read_string(&mut self, max_chars: usize) -> String {
        let mut s = String::with_capacity(max_chars.min(256));
        for _ in 0..max_chars {
            match self.read_char() {
                Some(c) => s.push(c),
                None => break,
            }
        }
        s
    }

    /// Read all remaining characters as a string.
    pub fn read_all_chars(&mut self) -> String {
        let mut s = String::new();
        while let Some(c) = self.read_char() {
            s.push(c);
        }
        s
    }

    // ── Skip ───────────────────────────────────────────────────────────────

    /// Skip `n` bytes forward (not characters).
    ///
    /// This is a byte-level skip that does not attempt character decoding.
    /// Line/column counts are updated based on the bytes skipped.
    ///
    /// Returns the number of bytes actually skipped (may be less than `n`
    /// if EOF is reached).
    pub fn skip(&mut self, n: usize) -> usize {
        let end = self.pos.saturating_add(n).min(self.data.len());
        let skipped = end - self.pos;

        // Update line/col based on bytes in the skipped range
        for &byte in &self.data[self.pos..end] {
            match byte {
                b'\n' => {
                    self.line += 1;
                    self.col = 1;
                }
                b'\r' => {
                    self.line += 1;
                    self.col = 1;
                }
                _ => {
                    self.col += 1;
                }
            }
        }

        self.pos = end;
        skipped
    }

    // ── Position queries ───────────────────────────────────────────────────

    /// Return the current position as `(line, col, byte_offset)`.
    ///
    /// Line and column are 1-based. Byte offset is 0-based.
    pub fn pos(&self) -> (usize, usize, usize) {
        (self.line, self.col, self.pos)
    }

    /// Check if the input has been fully consumed.
    pub fn is_eof(&self) -> bool {
        self.pos >= self.data.len()
    }

    /// Return the remaining unconsumed bytes.
    pub fn remaining(&self) -> &[u8] {
        &self.data[self.pos..]
    }

    /// Return the bytes consumed so far.
    pub fn consumed(&self) -> &[u8] {
        &self.data[..self.pos]
    }

    /// Return the total length of the buffered data in bytes.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Return the filename or URI, if known.
    pub fn filename(&self) -> Option<&str> {
        self.filename.as_deref()
    }

    /// Return the detected encoding.
    pub fn encoding(&self) -> &Encoding {
        &self.encoding
    }

    /// Return whether a BOM was detected and consumed.
    pub fn bom_was_consumed(&self) -> bool {
        self.bom_consumed
    }

    // ── C ABI integration ──────────────────────────────────────────────────

    /// Populate a `_xmlParserInput` struct with the current state of this buffer.
    ///
    /// The caller must ensure the raw pointers remain valid for the lifetime
    /// of the `_xmlParserInput` struct. This typically means the `InputBuffer`
    /// must not be dropped or reborrowed while the C struct is in use.
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    /// - The returned `_xmlParserInput` is not used after the `InputBuffer` is
    ///   dropped or mutably borrowed.
    /// - The `base`, `cur`, and `end` pointers point into stable storage.
    pub unsafe fn populate_parser_input(&self, input: &mut _xmlParserInput) {
        let data_ptr = self.data.as_ptr();
        let base = data_ptr as *const crate::abi::types::xmlChar;
        let cur = unsafe { data_ptr.add(self.pos) as *const crate::abi::types::xmlChar };
        let end = unsafe { data_ptr.add(self.data.len()) as *const crate::abi::types::xmlChar };

        input.base = base;
        input.cur = cur;
        input.end = end;
        input.line = self.line as c_int;
        input.col = self.col as c_int;
        input.length = self.data.len() as c_int;
        input.consumed = self.pos as c_ulong;
        input.filename = self
            .filename
            .as_ref()
            .map(|s| s.as_ptr() as *const c_char)
            .unwrap_or(std::ptr::null());
    }

    /// Create a `_xmlParserInputBuffer` from this buffer's source.
    ///
    /// # Safety
    ///
    /// The caller must ensure the callback function pointers are valid.
    pub unsafe fn populate_parser_input_buffer(&self, buf: &mut _xmlParserInputBuffer) {
        match &self.source {
            InputSource::Callback { read, close, ctx } => {
                buf.readcallback = Some(*read);
                buf.closecallback = Some(*close);
                buf.context = *ctx;
            }
            _ => {
                buf.readcallback = None;
                buf.closecallback = None;
                buf.context = std::ptr::null_mut();
            }
        }
        buf.encoder = std::ptr::null_mut();
        buf.buffer = std::ptr::null_mut();
        buf.raw = std::ptr::null_mut();
        buf.compressed = 0;
        buf.error = 0;
        buf.rawconsumed = 0;
    }

    // ── Resetting ──────────────────────────────────────────────────────────

    /// Reset the buffer to the beginning of the input.
    ///
    /// This allows re-parsing the same input from the start.
    pub fn reset(&mut self) {
        self.pos = 0;
        self.line = 1;
        self.col = 1;
        self.bom_consumed = false;
        self.detect_bom_and_encoding();
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// InputStack
// ═══════════════════════════════════════════════════════════════════════════════

/// A stack of input buffers, used for entity expansion.
///
/// When the parser encounters an entity reference, it pushes a new `InputBuffer`
/// onto the stack containing the entity's replacement text. When the entity's
/// content is fully consumed, the stack is popped to resume parsing the
/// original input.
///
/// # Invariants
///
/// - The stack always has at least one entry (the base input).
/// - `current` always indexes a valid entry in `inputs`.
pub(crate) struct InputStack {
    /// The stack of input buffers.
    inputs: Vec<InputBuffer>,
    /// Index of the current (top) input.
    current: usize,
}

impl std::fmt::Debug for InputStack {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InputStack")
            .field("depth", &self.inputs.len())
            .field("current", &self.current)
            .finish()
    }
}

impl InputStack {
    /// Create a new input stack with the given base input.
    pub fn new(base: InputBuffer) -> Self {
        InputStack {
            inputs: vec![base],
            current: 0,
        }
    }

    /// Push a new input onto the stack.
    ///
    /// This is used when entering an entity expansion.
    pub fn push(&mut self, input: InputBuffer) {
        self.inputs.push(input);
        self.current = self.inputs.len() - 1;
    }

    /// Pop the current input from the stack.
    ///
    /// Returns the popped input, or `None` if the stack would become empty
    /// (i.e., if there is only one input remaining).
    pub fn pop(&mut self) -> Option<InputBuffer> {
        if self.inputs.len() <= 1 {
            // Cannot pop the base input
            return None;
        }
        let popped = self.inputs.pop();
        self.current = self.inputs.len() - 1;
        popped
    }

    /// Get a mutable reference to the current (top) input buffer.
    pub fn current(&mut self) -> &mut InputBuffer {
        // `current` always indexes a valid entry.
        &mut self.inputs[self.current]
    }

    /// Get a shared reference to the current (top) input buffer.
    pub fn current_ref(&self) -> &InputBuffer {
        &self.inputs[self.current]
    }

    /// Get the current position across the entire stack.
    ///
    /// Returns `(line, col, byte_offset)` for the current input.
    pub fn current_pos(&self) -> (usize, usize, usize) {
        self.inputs[self.current].pos()
    }

    /// Returns the depth of the stack (number of nested inputs).
    ///
    /// A stack with only the base input has depth 1.
    pub fn depth(&self) -> usize {
        self.inputs.len()
    }

    /// Check if all inputs on the stack are at EOF.
    pub fn is_eof(&self) -> bool {
        self.inputs[self.current].is_eof()
    }

    /// Read the next character from the current input.
    ///
    /// If the current input is at EOF and there are pushed inputs above it,
    /// this does NOT automatically pop — the caller must manage stack depth.
    pub fn read_char(&mut self) -> Option<char> {
        self.inputs[self.current].read_char()
    }

    /// Peek at the next character from the current input without advancing.
    pub fn peek_char(&self) -> Option<char> {
        self.inputs[self.current].peek_char()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Free-standing helpers for C ABI population
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a `_xmlParserInput` from an `InputBuffer`.
///
/// This allocates a new `_xmlParserInput` on the heap (matching libxml2's
/// allocation pattern). The returned pointer must eventually be freed.
///
/// # Safety
///
/// The returned `_xmlParserInput` contains raw pointers into the `InputBuffer`'s
/// data storage. The caller must ensure the `InputBuffer` outlives the returned
/// struct.
pub(crate) unsafe fn input_buffer_to_parser_input(buf: &InputBuffer) -> *mut _xmlParserInput {
    let input = Box::into_raw(Box::new(_xmlParserInput {
        buf: std::ptr::null_mut(),
        filename: buf
            .filename
            .as_ref()
            .map(|s| s.as_ptr() as *const c_char)
            .unwrap_or(std::ptr::null()),
        directory: std::ptr::null(),
        base: buf.data.as_ptr() as *const crate::abi::types::xmlChar,
        cur: unsafe { buf.data.as_ptr().add(buf.pos) as *const crate::abi::types::xmlChar },
        end: unsafe { buf.data.as_ptr().add(buf.data.len()) as *const crate::abi::types::xmlChar },
        length: buf.data.len() as c_int,
        line: buf.line as c_int,
        col: buf.col as c_int,
        consumed: buf.pos as c_ulong,
        free: None,
        encoding: std::ptr::null(),
        version: std::ptr::null(),
        flags: 0,
        id: 0,
        parentConsumed: 0,
        entity: std::ptr::null_mut(),
    }));
    input
}

/// Create a `_xmlParserInputBuffer` from an `InputBuffer`.
///
/// This allocates a new `_xmlParserInputBuffer` on the heap.
///
/// # Safety
///
/// The caller must ensure callback pointers are valid if the input source
/// uses callbacks.
pub(crate) unsafe fn input_buffer_to_parser_input_buffer(
    buf: &InputBuffer,
) -> *mut _xmlParserInputBuffer {
    let mut raw_buf = Box::new(_xmlParserInputBuffer {
        context: std::ptr::null_mut(),
        readcallback: None,
        closecallback: None,
        encoder: std::ptr::null_mut(),
        buffer: std::ptr::null_mut(),
        raw: std::ptr::null_mut(),
        compressed: 0,
        error: 0,
        rawconsumed: 0,
    });

    unsafe {
        buf.populate_parser_input_buffer(&mut raw_buf);
    }

    Box::into_raw(raw_buf)
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    // ── Basic construction ─────────────────────────────────────────────────

    #[test]
    fn test_from_memory_empty() {
        let buf = InputBuffer::from_memory(b"", None);
        assert!(buf.is_eof());
        assert_eq!(buf.pos(), (1, 1, 0));
        assert_eq!(buf.encoding(), &Encoding::Utf8);
    }

    #[test]
    fn test_from_memory_basic() {
        let buf = InputBuffer::from_memory(b"hello", None);
        assert!(!buf.is_eof());
        assert_eq!(buf.len(), 5);
        assert_eq!(buf.remaining(), b"hello");
        assert!(buf.consumed().is_empty());
    }

    #[test]
    fn test_from_memory_with_uri() {
        let buf = InputBuffer::from_memory(b"test", Some("http://example.com"));
        assert_eq!(buf.filename(), Some("http://example.com"));
    }

    #[test]
    fn test_from_memory_with_encoding_declaration() {
        let buf =
            InputBuffer::from_memory(b"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>", None);
        assert_eq!(buf.encoding(), &Encoding::Iso8859_1);
    }

    // ── BOM detection ──────────────────────────────────────────────────────

    #[test]
    fn test_utf8_bom_detection() {
        // UTF-8 BOM: EF BB BF followed by "hello"
        let mut data = vec![0xEF, 0xBB, 0xBF];
        data.extend_from_slice(b"hello");
        let buf = InputBuffer::from_memory(&data, None);
        assert!(buf.bom_was_consumed());
        // BOM consumes 3 bytes
        assert_eq!(buf.pos, 3);
        assert_eq!(buf.col, 4);
        assert_eq!(buf.remaining(), b"hello");
    }

    #[test]
    fn test_utf16le_bom_detection() {
        let data = vec![0xFF, 0xFE, b'h', 0x00, b'i', 0x00];
        let buf = InputBuffer::from_memory(&data, None);
        assert!(buf.bom_was_consumed());
        assert_eq!(buf.encoding(), &Encoding::Utf16Le);
        assert_eq!(buf.pos, 2);
    }

    #[test]
    fn test_utf16be_bom_detection() {
        let data = vec![0xFE, 0xFF, 0x00, b'h', 0x00, b'i'];
        let buf = InputBuffer::from_memory(&data, None);
        assert!(buf.bom_was_consumed());
        assert_eq!(buf.encoding(), &Encoding::Utf16Be);
        assert_eq!(buf.pos, 2);
    }

    #[test]
    fn test_bom_with_encoding_declaration() {
        // BOM + XML declaration with encoding
        let mut data = vec![0xEF, 0xBB, 0xBF];
        data.extend_from_slice(b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        let buf = InputBuffer::from_memory(&data, None);
        assert!(buf.bom_was_consumed());
        assert_eq!(buf.encoding(), &Encoding::Utf8);
    }

    // ── Encoding detection from XML declaration ────────────────────────────

    #[test]
    fn test_encoding_extraction_from_pi() {
        let pi = r#"<?xml version="1.0" encoding="UTF-8"?>"#;
        assert_eq!(
            InputBuffer::extract_encoding_from_pi(pi),
            Some("UTF-8".to_string())
        );
    }

    #[test]
    fn test_encoding_extraction_single_quotes() {
        let pi = r#"<?xml version='1.0' encoding='ISO-8859-1'?>"#;
        assert_eq!(
            InputBuffer::extract_encoding_from_pi(pi),
            Some("ISO-8859-1".to_string())
        );
    }

    #[test]
    fn test_encoding_extraction_no_encoding() {
        let pi = r#"<?xml version="1.0"?>"#;
        assert_eq!(InputBuffer::extract_encoding_from_pi(pi), None);
    }

    #[test]
    fn test_encoding_from_name() {
        assert_eq!(Encoding::from_name("UTF-8"), Encoding::Utf8);
        assert_eq!(Encoding::from_name("utf8"), Encoding::Utf8);
        assert_eq!(Encoding::from_name("UTF-16"), Encoding::Utf16Le);
        assert_eq!(Encoding::from_name("utf-16le"), Encoding::Utf16Le);
        assert_eq!(Encoding::from_name("UTF-16BE"), Encoding::Utf16Be);
        assert_eq!(Encoding::from_name("ASCII"), Encoding::Ascii);
        assert_eq!(Encoding::from_name("ISO-8859-1"), Encoding::Iso8859_1);
        assert_eq!(
            Encoding::from_name("Shift_JIS"),
            Encoding::Other("shift_jis".to_string())
        );
    }

    // ── Character reading ──────────────────────────────────────────────────

    #[test]
    fn test_read_char_ascii() {
        let mut buf = InputBuffer::from_memory(b"abc", None);
        assert_eq!(buf.read_char(), Some('a'));
        assert_eq!(buf.read_char(), Some('b'));
        assert_eq!(buf.read_char(), Some('c'));
        assert_eq!(buf.read_char(), None);
        assert!(buf.is_eof());
    }

    #[test]
    fn test_read_char_multibyte_utf8() {
        // 2-byte: é (U+00E9) = 0xC3 0xA9
        // 3-byte: € (U+20AC) = 0xE2 0x82 0xAC
        // 4-byte: 𐍈 (U+10348) = 0xF0 0x90 0x8D 0x88
        let data = vec![0xC3, 0xA9, 0xE2, 0x82, 0xAC, 0xF0, 0x90, 0x8D, 0x88];
        let mut buf = InputBuffer::from_memory(&data, None);
        assert_eq!(buf.read_char(), Some('é'));
        assert_eq!(buf.read_char(), Some(''));
        assert_eq!(buf.read_char(), Some('𐍈'));
        assert_eq!(buf.read_char(), None);
    }

    #[test]
    fn test_peek_char() {
        let mut buf = InputBuffer::from_memory(b"abc", None);
        assert_eq!(buf.peek_char(), Some('a'));
        assert_eq!(buf.peek_char(), Some('a')); // peek doesn't advance
        assert_eq!(buf.read_char(), Some('a'));
        assert_eq!(buf.peek_char(), Some('b'));
    }

    #[test]
    fn test_read_char_tracking() {
        let mut buf = InputBuffer::from_memory(b"a\nb\nc", None);
        assert_eq!(buf.read_char(), Some('a'));
        assert_eq!(buf.pos(), (1, 2, 1));
        assert_eq!(buf.read_char(), Some('\n'));
        assert_eq!(buf.pos(), (2, 1, 2));
        assert_eq!(buf.read_char(), Some('b'));
        assert_eq!(buf.pos(), (2, 2, 3));
        assert_eq!(buf.read_char(), Some('\n'));
        assert_eq!(buf.pos(), (3, 1, 4));
        assert_eq!(buf.read_char(), Some('c'));
        assert_eq!(buf.pos(), (3, 2, 5));
    }

    #[test]
    fn test_crlf_handling() {
        let mut buf = InputBuffer::from_memory(b"a\r\nb", None);
        assert_eq!(buf.read_char(), Some('a'));
        assert_eq!(buf.pos(), (1, 2, 1));
        // \r should trigger newline; CRLF should consume the \n too
        assert_eq!(buf.read_char(), Some('\r'));
        // After \r, we're on line 2, col 1; the \n was consumed
        assert_eq!(buf.pos(), (2, 1, 3));
        assert_eq!(buf.read_char(), Some('b'));
        assert_eq!(buf.pos(), (2, 2, 4));
    }

    // ── Skip ───────────────────────────────────────────────────────────────

    #[test]
    fn test_skip() {
        let mut buf = InputBuffer::from_memory(b"hello world", None);
        assert_eq!(buf.skip(5), 5);
        assert_eq!(buf.remaining(), b" world");
        assert_eq!(buf.pos(), (1, 6, 5));
    }

    #[test]
    fn test_skip_past_end() {
        let mut buf = InputBuffer::from_memory(b"hi", None);
        assert_eq!(buf.skip(100), 2);
        assert!(buf.is_eof());
    }

    // ── Read string ────────────────────────────────────────────────────────

    #[test]
    fn test_read_string() {
        let mut buf = InputBuffer::from_memory(b"hello world", None);
        assert_eq!(buf.read_string(5), "hello");
        assert_eq!(buf.read_string(10), " world");
    }

    #[test]
    fn test_read_all_chars() {
        let mut buf = InputBuffer::from_memory(b"hello", None);
        assert_eq!(buf.read_all_chars(), "hello");
        assert!(buf.is_eof());
    }

    // ── Reset ──────────────────────────────────────────────────────────────

    #[test]
    fn test_reset() {
        let mut buf = InputBuffer::from_memory(b"hello", None);
        assert_eq!(buf.read_char(), Some('h'));
        assert_eq!(buf.read_char(), Some('e'));
        buf.reset();
        assert_eq!(buf.read_char(), Some('h'));
        assert_eq!(buf.pos(), (1, 2, 1));
    }

    // ── File reading ───────────────────────────────────────────────────────

    #[test]
    fn test_from_file_not_found() {
        let result = InputBuffer::from_file("/nonexistent/file.xml");
        assert!(result.is_err());
        match result {
            Err(InputError::Io(_)) => {} // expected
            _ => panic!("expected Io error"),
        }
    }

    // ── Position tracking ──────────────────────────────────────────────────

    #[test]
    fn test_position_tracking() {
        let mut buf = InputBuffer::from_memory(b"line1\nline2\nline3", None);
        // line1
        assert_eq!(buf.pos(), (1, 1, 0));
        assert_eq!(buf.read_string(5), "line1");
        assert_eq!(buf.pos(), (1, 6, 5));
        // \n
        assert_eq!(buf.read_char(), Some('\n'));
        assert_eq!(buf.pos(), (2, 1, 6));
        // line2
        assert_eq!(buf.read_string(5), "line2");
        assert_eq!(buf.pos(), (2, 6, 11));
        // \n
        assert_eq!(buf.read_char(), Some('\n'));
        assert_eq!(buf.pos(), (3, 1, 12));
        // line3
        assert_eq!(buf.read_string(5), "line3");
        assert_eq!(buf.pos(), (3, 6, 17));
        assert!(buf.is_eof());
    }

    // ── InputStack ─────────────────────────────────────────────────────────

    #[test]
    fn test_input_stack_basic() {
        let base = InputBuffer::from_memory(b"base ", None);
        let mut stack = InputStack::new(base);
        assert_eq!(stack.depth(), 1);

        let entity = InputBuffer::from_memory(b"entity", None);
        stack.push(entity);
        assert_eq!(stack.depth(), 2);

        // Read from entity
        assert_eq!(stack.read_char(), Some('e'));
        assert_eq!(stack.current_pos(), (1, 2, 1));

        // Pop back to base
        let popped = stack.pop();
        assert!(popped.is_some());
        assert_eq!(stack.depth(), 1);
        assert_eq!(stack.read_char(), Some('b'));
    }

    #[test]
    fn test_input_stack_no_pop_base() {
        let base = InputBuffer::from_memory(b"base", None);
        let mut stack = InputStack::new(base);
        assert!(stack.pop().is_none());
        assert_eq!(stack.depth(), 1);
    }

    #[test]
    fn test_input_stack_peek() {
        let base = InputBuffer::from_memory(b"abc", None);
        let mut stack = InputStack::new(base);
        assert_eq!(stack.peek_char(), Some('a'));
        assert_eq!(stack.read_char(), Some('a'));
        assert_eq!(stack.peek_char(), Some('b'));
    }

    #[test]
    fn test_input_stack_eof() {
        let base = InputBuffer::from_memory(b"ab", None);
        let mut stack = InputStack::new(base);
        assert!(!stack.is_eof());
        stack.read_char();
        stack.read_char();
        assert!(stack.is_eof());
    }

    // ── UTF-8 decoding edge cases ──────────────────────────────────────────

    #[test]
    fn test_decode_utf8_invalid_continuation() {
        // Invalid: 0xC0 followed by 0x00 (not a continuation byte)
        let data = vec![0xC0, 0x00];
        let mut buf = InputBuffer::from_memory(&data, None);
        // Should return None for the invalid sequence
        assert!(buf.read_char().is_none());
    }

    #[test]
    fn test_decode_utf8_truncated_sequence() {
        // Truncated 2-byte sequence (only leading byte)
        let data = vec![0xC3];
        let mut buf = InputBuffer::from_memory(&data, None);
        assert!(buf.read_char().is_none());
    }

    // ── Encoding detection in XML declaration (no BOM) ────────────────────

    #[test]
    fn test_encoding_detection_utf8_xml_decl() {
        let buf = InputBuffer::from_memory(b"<?xml version='1.0' encoding='UTF-8'?>", None);
        assert_eq!(buf.encoding(), &Encoding::Utf8);
    }

    #[test]
    fn test_encoding_detection_latin1_xml_decl() {
        let buf = InputBuffer::from_memory(b"<?xml version='1.0' encoding='ISO-8859-1'?>", None);
        assert_eq!(buf.encoding(), &Encoding::Iso8859_1);
    }

    #[test]
    fn test_encoding_detection_unknown() {
        let buf = InputBuffer::from_memory(b"<?xml version='1.0' encoding='Shift_JIS'?>", None);
        assert_eq!(buf.encoding(), &Encoding::Other("shift_jis".to_string()));
    }
}