rsmediainfo 0.1.0

Rust wrapper for MediaInfo library
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
//! XML parsing utilities for MediaInfo output.
//!
//! Turns the XML payload returned by the underlying media library into a
//! flat vector of [`Track`] values. Two historical document layouts are
//! accepted: the older form with `<File>` as the root element, and the
//! newer wrapped form `<MediaInfo>…<File>…</File>…</MediaInfo>`.

use crate::error::{EncodingErrorMode, MediaInfoError, Result};
use crate::track::{AttributeValue, Track};
use quick_xml::Reader;
use quick_xml::events::Event;
use std::fmt::Write;

/// Converts bytes to a string using the specified encoding error mode.
///
/// This function handles invalid UTF-8 sequences according to the mode:
/// - Strict: Returns an error if invalid bytes are found
/// - Replace: Replaces invalid bytes with the Unicode replacement character
/// - Ignore: Removes invalid bytes from the output
fn bytes_to_string(bytes: &[u8], mode: EncodingErrorMode) -> Result<String> {
    match mode {
        EncodingErrorMode::Strict => std::str::from_utf8(bytes)
            .map(|s| s.to_string())
            .map_err(|e| MediaInfoError::XmlParseError(format!("UTF-8 encoding error: {}", e))),
        EncodingErrorMode::Replace => Ok(String::from_utf8_lossy(bytes).into_owned()),
        EncodingErrorMode::Ignore => Ok(decode_with_handler(bytes, |_byte, _out| {})),
        EncodingErrorMode::BackslashReplace => Ok(decode_with_handler(bytes, |byte, out| {
            let _ = write!(out, "\\x{:02x}", byte);
        })),
        EncodingErrorMode::XmlCharRefReplace => Ok(decode_with_handler(bytes, |byte, out| {
            let _ = write!(out, "&#{};", byte);
        })),
    }
}

fn decode_with_handler<F>(bytes: &[u8], mut on_invalid: F) -> String
where
    F: FnMut(u8, &mut String),
{
    let mut output = String::new();
    for chunk in bytes.utf8_chunks() {
        output.push_str(chunk.valid());
        for &byte in chunk.invalid() {
            on_invalid(byte, &mut output);
        }
    }
    output
}

/// Parses an XML payload into a vector of [`Track`] values using the strict
/// encoding mode.
///
/// Both the older `<File>`-rooted layout and the newer
/// `<MediaInfo>…<File>…</File>…</MediaInfo>` wrapper are accepted. Each
/// element nested directly under a `<track>` becomes one entry on the
/// resulting track, with attribute names normalized and repeated attributes
/// folded into `other_<name>` lists.
///
/// # Arguments
///
/// * `xml` - The XML string to parse
///
/// # Returns
///
/// A vector of [`Track`] values built from the XML in document order.
#[allow(dead_code)]
pub(crate) fn parse_xml(xml: &str) -> Result<Vec<Track>> {
    parse_xml_with_encoding(xml, EncodingErrorMode::Strict)
}

/// Parses an XML payload into a vector of [`Track`] values using the
/// caller-supplied encoding mode.
///
/// The encoding mode is consulted whenever a byte slice in the input cannot
/// be decoded as UTF-8 — see [`EncodingErrorMode`] for the available
/// strategies. The structural rules are the same as [`parse_xml`].
///
/// # Arguments
///
/// * `xml` - The XML string to parse
/// * `encoding_mode` - How to handle invalid UTF-8 sequences
///
/// # Returns
///
/// A vector of [`Track`] values built from the XML in document order.
pub fn parse_xml_with_encoding(xml: &str, encoding_mode: EncodingErrorMode) -> Result<Vec<Track>> {
    parse_xml_str_with_encoding(xml, encoding_mode)
}

/// Parses MediaInfo XML output from raw bytes with specified encoding mode.
///
/// This handles invalid UTF-8 sequences according to the encoding mode before parsing.
pub fn parse_xml_bytes_with_encoding(
    xml_bytes: &[u8],
    encoding_mode: EncodingErrorMode,
) -> Result<Vec<Track>> {
    let xml_text = bytes_to_string(xml_bytes, encoding_mode)?;
    parse_xml_str_with_encoding(&xml_text, encoding_mode)
}

fn parse_xml_str_with_encoding(xml: &str, encoding_mode: EncodingErrorMode) -> Result<Vec<Track>> {
    let mut tracks = Vec::new();
    let mut reader = Reader::from_str(xml);
    reader.trim_text(false);

    let mut inside_file = false;
    let mut current_track: Option<Track> = None;
    let mut current_element_name: Option<String> = None;
    let mut current_element_has_text = false;
    let mut current_element_active = false;
    let mut current_element_text: Option<String> = None;
    let mut track_depth: usize = 0;
    let mut repeated_attributes: Vec<(String, String)> = Vec::new();
    let mut seen_element = false;

    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                let name_bytes = e.name();
                let tag_name = bytes_to_string(name_bytes.as_ref(), encoding_mode)?;
                seen_element = true;

                match tag_name.as_str() {
                    // Both layouts are accepted: the older `<File>`-rooted form
                    // and the newer `<MediaInfo>...<File>...</File>...</MediaInfo>`
                    // wrapper.
                    "File" => {
                        inside_file = true;
                    }
                    "track" if inside_file => {
                        let mut track_type = String::new();
                        for attr in e.attributes() {
                            let attr = attr?;
                            if attr.key.as_ref() == b"type" {
                                track_type = bytes_to_string(&attr.value, encoding_mode)?;
                                break;
                            }
                        }

                        current_track = Some(Track::new(track_type));
                        repeated_attributes.clear();
                        current_element_name = None;
                        current_element_has_text = false;
                        current_element_active = false;
                        current_element_text = None;
                        track_depth = 0;
                    }
                    _ if current_track.is_some() => {
                        track_depth += 1;
                        if track_depth == 1 {
                            current_element_name = Some(normalize_attribute_name(&tag_name));
                            current_element_has_text = false;
                            current_element_active = true;
                            current_element_text = Some(String::new());
                        } else if track_depth == 2 {
                            current_element_active = false;
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::Empty(ref e)) => {
                let name_bytes = e.name();
                let tag_name = bytes_to_string(name_bytes.as_ref(), encoding_mode)?;
                seen_element = true;

                match tag_name.as_str() {
                    "File" => {}
                    "track" if inside_file => {
                        let mut track_type = String::new();
                        for attr in e.attributes() {
                            let attr = attr?;
                            if attr.key.as_ref() == b"type" {
                                track_type = bytes_to_string(&attr.value, encoding_mode)?;
                                break;
                            }
                        }

                        let mut track = Track::new(track_type);
                        process_integer_conversion(&mut track, &repeated_attributes);
                        tracks.push(track);
                        repeated_attributes.clear();
                        current_track = None;
                        track_depth = 0;
                        current_element_name = None;
                        current_element_has_text = false;
                        current_element_active = false;
                        current_element_text = None;
                    }
                    _ if current_track.is_some() => {
                        track_depth += 1;
                        if track_depth == 1 {
                            let element_name = normalize_attribute_name(&tag_name);
                            if let Some(ref mut track) = current_track {
                                apply_attribute_value(
                                    track,
                                    &element_name,
                                    None,
                                    &mut repeated_attributes,
                                );
                            }
                        }

                        track_depth = track_depth.saturating_sub(1);
                        if track_depth == 0 {
                            current_element_name = None;
                            current_element_has_text = false;
                            current_element_active = false;
                            current_element_text = None;
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::Text(ref e)) => {
                if current_track.is_some()
                    && current_element_name.is_some()
                    && track_depth == 1
                    && current_element_active
                {
                    let unescaped = e.unescape()?;
                    let text = bytes_to_string(unescaped.as_bytes(), encoding_mode)?;
                    if !text.is_empty() {
                        current_element_has_text = true;
                        if let Some(ref mut buffer) = current_element_text {
                            buffer.push_str(&text);
                        }
                    }
                }
            }
            Ok(Event::CData(ref e)) => {
                if current_track.is_some()
                    && current_element_name.is_some()
                    && track_depth == 1
                    && current_element_active
                {
                    let text = bytes_to_string(e.as_ref(), encoding_mode)?;
                    if !text.is_empty() {
                        current_element_has_text = true;
                        if let Some(ref mut buffer) = current_element_text {
                            buffer.push_str(&text);
                        }
                    }
                }
            }
            Ok(Event::End(ref e)) => {
                let name_bytes = e.name();
                let tag_name = bytes_to_string(name_bytes.as_ref(), encoding_mode)?;
                seen_element = true;

                match tag_name.as_str() {
                    "track" => {
                        if let Some(mut track) = current_track.take() {
                            process_integer_conversion(&mut track, &repeated_attributes);
                            tracks.push(track);
                        }
                        repeated_attributes.clear();
                        track_depth = 0;
                        current_element_name = None;
                        current_element_has_text = false;
                        current_element_active = false;
                        current_element_text = None;
                    }
                    "File" => {
                        inside_file = false;
                    }
                    _ => {
                        if track_depth == 1
                            && let (Some(track), Some(element_name)) =
                                (&mut current_track, &current_element_name)
                        {
                            if current_element_has_text {
                                let text = current_element_text.take().unwrap_or_default();
                                apply_attribute_value(
                                    track,
                                    element_name,
                                    Some(text),
                                    &mut repeated_attributes,
                                );
                            } else {
                                apply_attribute_value(
                                    track,
                                    element_name,
                                    None,
                                    &mut repeated_attributes,
                                );
                            }
                        }

                        track_depth = track_depth.saturating_sub(1);

                        if track_depth == 0 {
                            current_element_name = None;
                            current_element_has_text = false;
                            current_element_active = false;
                            current_element_text = None;
                        }
                    }
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(MediaInfoError::xml_parse_error(e.to_string())),
            _ => {}
        }
        buf.clear();
    }

    if !seen_element {
        return Err(MediaInfoError::xml_parse_error("Invalid XML".to_string()));
    }

    Ok(tracks)
}

/// Normalizes an XML element name into the canonical attribute key used on
/// [`Track`].
///
/// The normalization rules, applied in order, are:
///
/// 1. Convert the name to lowercase.
/// 2. Strip surrounding whitespace.
/// 3. Strip leading and trailing underscores (interior underscores are
///    preserved).
/// 4. As a final special case, the bare key `"id"` is rewritten to
///    `"track_id"` so callers can address it consistently across track
///    types and so it never collides with a Rust keyword.
fn normalize_attribute_name(name: &str) -> String {
    let mut normalized = name.to_lowercase();
    normalized = normalized.trim().trim_matches('_').to_string();

    if normalized == "id" {
        "track_id".to_string()
    } else {
        normalized
    }
}

fn apply_attribute_value(
    track: &mut Track,
    element_name: &str,
    value: Option<String>,
    repeated_attributes: &mut Vec<(String, String)>,
) {
    match value {
        Some(text) => {
            if track.get(element_name).is_some() {
                let other_key = format!("other_{}", element_name);
                append_other_value(track, &other_key, text);

                if !repeated_attributes.iter().any(|(k, _)| k == element_name) {
                    repeated_attributes.push((element_name.to_string(), other_key));
                }
            } else {
                track.set_string(element_name.to_string(), text);
            }
        }
        None => {
            if track.get(element_name).is_some() {
                return;
            }
            track.set_null(element_name.to_string());
        }
    }
}

fn append_other_value(track: &mut Track, other_key: &str, value: String) {
    if let Some(AttributeValue::List(list)) = track.attributes_mut().get_mut(other_key) {
        list.push(value);
        return;
    }

    let existing = track.attributes().get(other_key).cloned();
    match existing {
        Some(AttributeValue::String(s)) => {
            track.set_list(other_key.to_string(), vec![s, value]);
        }
        Some(AttributeValue::Int(i)) => {
            track.set_list(other_key.to_string(), vec![i.to_string(), value]);
        }
        Some(AttributeValue::Null) | None => {
            track.set_list(other_key.to_string(), vec![value]);
        }
        Some(AttributeValue::List(_)) => {}
    }
}

/// Promotes integer values onto the primary slot for any attribute that
/// appeared multiple times in the source XML.
///
/// When the same element name shows up more than once on a track, the first
/// occurrence is stored under the canonical key and any extras are appended
/// to a sibling list under `other_<name>`. The library typically emits one
/// computer-readable integer value (e.g. `3000`) plus several human-readable
/// formats (e.g. `"3 s 0 ms"`, `"00:00:03.000"`). To make integer access
/// ergonomic, this pass:
///
/// 1. Tries to parse the current primary value as an `i64`. If that
///    succeeds, the primary slot is replaced in place with the parsed
///    integer and the loop moves on.
/// 2. Otherwise, walks the matching `other_<name>` list looking for the
///    first entry that parses as an `i64`. If one is found, the integer
///    becomes the primary value and the original primary string is
///    appended to the end of the list (the matched entry stays in place
///    so the list still records every variant).
/// 3. If no integer is found anywhere, the values are left untouched.
fn process_integer_conversion(track: &mut Track, repeated_attributes: &[(String, String)]) {
    for (primary_key, other_key) in repeated_attributes {
        let primary_value = match track.get(primary_key) {
            Some(AttributeValue::String(s)) => s.clone(),
            _ => continue,
        };

        if let Ok(int_val) = primary_value.parse::<i64>() {
            track.set_int(primary_key.clone(), int_val);
        } else {
            let other_values = match track.get(other_key) {
                Some(AttributeValue::List(l)) => l.clone(),
                _ => continue,
            };

            let mut found_int = false;
            // Preserve original list order; append the displaced primary string
            // after promoting an integer from `other_*` into the primary slot.
            let mut new_other_values = other_values.clone();

            for other_val in other_values.iter() {
                if let Ok(int_val) = other_val.parse::<i64>() {
                    track.set_int(primary_key.clone(), int_val);
                    new_other_values.push(primary_value.clone());
                    found_int = true;
                    break;
                }
            }

            if found_int {
                track.set_list(other_key.clone(), new_other_values);
            }
        }
    }
}

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

    #[test]
    fn test_normalize_attribute_name() {
        assert_eq!(normalize_attribute_name("Duration"), "duration");
        assert_eq!(normalize_attribute_name("ID"), "track_id");
        assert_eq!(normalize_attribute_name("id"), "track_id");
        assert_eq!(normalize_attribute_name("_Format_"), "format");
        assert_eq!(normalize_attribute_name("_StreamSize_"), "streamsize");
        assert_eq!(normalize_attribute_name(" Format "), "format");
        // Internal underscores must be preserved; only the leading and trailing
        // ones (and surrounding whitespace) are stripped during normalization.
        assert_eq!(normalize_attribute_name("  Stream_Size  "), "stream_size");
        assert_eq!(normalize_attribute_name("Bit_Rate"), "bit_rate");
    }

    #[test]
    fn test_parse_simple_xml() {
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="General">
<Format>Matroska</Format>
<Duration>3000</Duration>
</track>
</File>"#;

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].track_type(), "General");
        assert_eq!(tracks[0].get_string("format"), Some("Matroska"));
    }

    #[test]
    fn test_parse_new_format_xml() {
        let xml = r#"<?xml version="1.0"?>
<MediaInfo>
<File>
<track type="General">
<Format>Matroska</Format>
</track>
<track type="Video">
<Format>AVC</Format>
</track>
</File>
</MediaInfo>"#;

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 2);
        assert_eq!(tracks[0].track_type(), "General");
        assert_eq!(tracks[1].track_type(), "Video");
    }

    #[test]
    fn test_parse_repeated_attributes() {
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="General">
<Duration>3000</Duration>
<Duration>3 s 0 ms</Duration>
<Duration>00:00:03.000</Duration>
</track>
</File>"#;

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 1);

        assert_eq!(tracks[0].get_int("duration"), Some(3000));

        let other = tracks[0].get_list("other_duration").unwrap();
        assert!(other.contains(&"3 s 0 ms".to_string()));
        assert!(other.contains(&"00:00:03.000".to_string()));
    }

    #[test]
    fn test_parse_repeated_attributes_swap() {
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="General">
<Duration>3 s 0 ms</Duration>
<Duration>3000</Duration>
<Duration>00:00:03.000</Duration>
</track>
</File>"#;

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 1);

        assert_eq!(tracks[0].get_int("duration"), Some(3000));

        let other = tracks[0].get_list("other_duration").unwrap();
        assert!(other.contains(&"3 s 0 ms".to_string()));
    }

    #[test]
    fn test_parse_xml_with_track_id() {
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="Video">
<ID>1</ID>
<Format>AVC</Format>
</track>
</File>"#;

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].get_string("track_id"), Some("1"));
    }

    #[test]
    fn test_parse_invalid_xml() {
        let xml = "not valid xml";
        let result = parse_xml(xml);
        assert!(result.is_err());
    }

    #[test]
    fn test_bytes_to_string_strict_valid() {
        let bytes = b"Hello, World!";
        let result = bytes_to_string(bytes, EncodingErrorMode::Strict);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Hello, World!");
    }

    #[test]
    fn test_bytes_to_string_strict_invalid() {
        let bytes = &[0xff, 0xfe, 0x00, 0x01];
        let result = bytes_to_string(bytes, EncodingErrorMode::Strict);
        assert!(result.is_err());
    }

    #[test]
    fn test_bytes_to_string_replace_invalid() {
        let bytes = &[0x48, 0x65, 0x6c, 0x6c, 0x6f, 0xff, 0xfe];
        let result = bytes_to_string(bytes, EncodingErrorMode::Replace);
        assert!(result.is_ok());
        let s = result.unwrap();
        assert!(s.contains('\u{FFFD}'));
        assert!(s.starts_with("Hello"));
    }

    #[test]
    fn test_bytes_to_string_ignore_invalid() {
        let bytes = &[0x48, 0x65, 0x6c, 0x6c, 0x6f, 0xff, 0xfe];
        let result = bytes_to_string(bytes, EncodingErrorMode::Ignore);
        assert!(result.is_ok());
        let s = result.unwrap();
        assert!(!s.contains('\u{FFFD}'));
        assert_eq!(s, "Hello");
    }

    #[test]
    fn test_bytes_to_string_backslash_replace_invalid() {
        let bytes = &[0x48, 0x69, 0xff, 0xfe];
        let result = bytes_to_string(bytes, EncodingErrorMode::BackslashReplace);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Hi\\xff\\xfe");
    }

    #[test]
    fn test_bytes_to_string_xmlcharrefreplace_invalid() {
        let bytes = &[0x4f, 0x4b, 0xff];
        let result = bytes_to_string(bytes, EncodingErrorMode::XmlCharRefReplace);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "OK&#255;");
    }

    #[test]
    fn test_parse_xml_with_encoding_replace() {
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="General">
<Format>MKV</Format>
</track>
</File>"#;

        let tracks = parse_xml_with_encoding(xml, EncodingErrorMode::Replace).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].get_string("format"), Some("MKV"));
    }

    #[test]
    fn test_parse_xml_with_encoding_strict() {
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="General">
<Format>MP4</Format>
</track>
</File>"#;

        let tracks = parse_xml_with_encoding(xml, EncodingErrorMode::Strict).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].get_string("format"), Some("MP4"));
    }

    #[test]
    fn test_parse_xml_with_encoding_ignore() {
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="General">
<Format>AVI</Format>
</track>
</File>"#;

        let tracks = parse_xml_with_encoding(xml, EncodingErrorMode::Ignore).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].get_string("format"), Some("AVI"));
    }

    #[test]
    fn test_parse_xml_bytes_with_encoding_strict_invalid() {
        let xml_bytes = b"<?xml version=\"1.0\"?><File><track type=\"General\"><Title>Bad\xFF</Title></track></File>";
        let result = parse_xml_bytes_with_encoding(xml_bytes, EncodingErrorMode::Strict);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_xml_bytes_with_encoding_replace() {
        let xml_bytes = b"<?xml version=\"1.0\"?><File><track type=\"General\"><Title>Bad\xFF</Title></track></File>";
        let tracks = parse_xml_bytes_with_encoding(xml_bytes, EncodingErrorMode::Replace).unwrap();
        assert_eq!(tracks.len(), 1);
        let title = tracks[0].get_string("title").unwrap();
        assert!(title.contains('\u{FFFD}'));
    }

    #[test]
    fn test_parse_xml_bytes_with_encoding_ignore() {
        let xml_bytes = b"<?xml version=\"1.0\"?><File><track type=\"General\"><Title>Bad\xFF</Title></track></File>";
        let tracks = parse_xml_bytes_with_encoding(xml_bytes, EncodingErrorMode::Ignore).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].get_string("title"), Some("Bad"));
    }

    #[test]
    fn test_cdata_is_parsed_as_text() {
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="General">
<Description><![CDATA[CDATA with <tags>]]></Description>
</track>
</File>"#;

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(
            tracks[0].get_string("description"),
            Some("CDATA with <tags>")
        );
    }

    #[test]
    fn test_tracks_outside_file_are_ignored() {
        let xml = r#"<?xml version="1.0"?>
<MediaInfo>
<track type="General"><Format>Outside</Format></track>
<File>
<track type="General"><Format>Inside</Format></track>
</File>
</MediaInfo>"#;

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].get_string("format"), Some("Inside"));
    }

    #[test]
    fn test_xml_entities_are_unescaped_exactly_once() {
        // Each text segment must be unescaped a single time. The double-encoded
        // payload `&amp;amp;` should decode to `&amp;` (one level of unescape),
        // never collapsing further to `&` (which would indicate a second pass).
        // The numeric character reference is a third independent codepath.
        let xml = r#"<?xml version="1.0"?>
<File>
<track type="General">
<Title>A &amp; B</Title>
<Album>&amp;amp;</Album>
<Comment>x &#38; y</Comment>
</track>
</File>"#;

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 1);

        // Single-level entity: `&amp;` -> `&`.
        assert_eq!(tracks[0].get_string("title"), Some("A & B"));

        // Double-encoded sentinel: must stay at `&amp;`, proving exactly one
        // unescape pass ran on the segment.
        assert_eq!(tracks[0].get_string("album"), Some("&amp;"));

        // Numeric character reference is also unescaped once and only once.
        assert_eq!(tracks[0].get_string("comment"), Some("x & y"));
    }

    #[test]
    fn test_whitespace_only_text_is_preserved() {
        // Element bodies that contain only whitespace must round-trip
        // byte-for-byte. The reader is configured to never trim text and the
        // text-to-buffer path forwards the raw decoded bytes verbatim, so a
        // future change that introduces accidental trimming would fail here.
        let xml = "<?xml version=\"1.0\"?>\n\
<File>\n\
<track type=\"General\">\n\
<Format>   </Format>\n\
<Album>\t</Album>\n\
<Comment>  hi  </Comment>\n\
</track>\n\
</File>";

        let tracks = parse_xml(xml).unwrap();
        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].get_string("format"), Some("   "));
        assert_eq!(tracks[0].get_string("album"), Some("\t"));
        assert_eq!(tracks[0].get_string("comment"), Some("  hi  "));
    }
}