opticaldiscs 0.6.0

Format-agnostic optical disc image reading and filesystem browsing (ISO, BIN/CUE, CHD)
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
//! ISO 9660 Primary Volume Descriptor (PVD) parsing.
//!
//! The PVD lives at sector 16 (byte offset 32 768) and is the entry point for
//! everything else: volume label, root directory location, and block geometry.
//!
//! Reference: ECMA-119 / ISO 9660, section 8.4.

use crate::error::{OpticaldiscsError, Result};
use crate::sector_reader::SectorReader;

/// Sector number of the Primary Volume Descriptor.
pub const PVD_SECTOR: u64 = 16;

/// Byte offset of the PVD from the start of the disc.
pub const PVD_OFFSET: u64 = PVD_SECTOR * crate::sector_reader::SECTOR_SIZE;

const PVD_TYPE: u8 = 0x01;
const VD_SET_TERMINATOR_TYPE: u8 = 0xFF;
const ISO9660_ID: &[u8; 5] = b"CD001";

/// A date/time decoded from a 17-byte ISO 9660 "dec-datetime" field
/// (ECMA-119 §8.4.26.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PvdDateTime {
    /// Year, full four digits (e.g. 1997).
    pub year: u16,
    /// Month, 1–12.
    pub month: u8,
    /// Day of month, 1–31.
    pub day: u8,
    /// Hour, 0–23.
    pub hour: u8,
    /// Minute, 0–59.
    pub minute: u8,
    /// Second, 0–59.
    pub second: u8,
    /// Hundredths of a second, 0–99.
    pub hundredths: u8,
    /// GMT offset in 15-minute intervals (range -48..=52).
    pub gmt_offset_quarter_hours: i8,
}

impl PvdDateTime {
    /// Parse a 17-byte dec-datetime field.
    ///
    /// Returns `None` for the "not specified" encoding (all ASCII '0' with a
    /// zero offset byte, or all 0x00) and for corrupt fields whose digit
    /// groups are not actually ASCII digits.
    pub fn parse(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < 17 {
            return None;
        }

        // "Not specified": all 0x00, or all ASCII '0' with zero offset.
        if bytes[..17].iter().all(|&b| b == 0) {
            return None;
        }
        if bytes[..16].iter().all(|&b| b == b'0') && bytes[16] == 0 {
            return None;
        }

        let year = parse_digits(&bytes[0..4])? as u16;
        let month = parse_digits(&bytes[4..6])? as u8;
        let day = parse_digits(&bytes[6..8])? as u8;
        let hour = parse_digits(&bytes[8..10])? as u8;
        let minute = parse_digits(&bytes[10..12])? as u8;
        let second = parse_digits(&bytes[12..14])? as u8;
        let hundredths = parse_digits(&bytes[14..16])? as u8;
        let gmt_offset_quarter_hours = bytes[16] as i8;

        Some(Self {
            year,
            month,
            day,
            hour,
            minute,
            second,
            hundredths,
            gmt_offset_quarter_hours,
        })
    }

    /// Render as the ISO-8601 string redump uses, e.g.
    /// `1997-03-18T16:45:47.00+00:00`.
    pub fn to_iso8601(&self) -> String {
        let total_minutes = self.gmt_offset_quarter_hours as i32 * 15;
        let sign = if total_minutes < 0 { '-' } else { '+' };
        let abs = total_minutes.abs();
        format!(
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:02}{}{:02}:{:02}",
            self.year,
            self.month,
            self.day,
            self.hour,
            self.minute,
            self.second,
            self.hundredths,
            sign,
            abs / 60,
            abs % 60,
        )
    }
}

/// Parse a group of ASCII decimal digits into a `u32`, returning `None` if any
/// byte is not an ASCII digit.
fn parse_digits(bytes: &[u8]) -> Option<u32> {
    let mut value = 0u32;
    for &b in bytes {
        if !b.is_ascii_digit() {
            return None;
        }
        value = value * 10 + (b - b'0') as u32;
    }
    Some(value)
}

/// A parsed ISO 9660 directory-record recording date/time (ECMA-119 §9.1.5):
/// the 7-byte *binary* form recorded per file and directory. This is distinct
/// from the 17-byte ASCII [`PvdDateTime`] used in the volume descriptor.
///
/// Values are stored raw and untranslated; use [`Self::to_iso8601`] for display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Iso9660DateTime {
    /// Number of years since 1900 (e.g. `97` = 1997), stored raw.
    pub years_since_1900: u8,
    /// Month, 1–12.
    pub month: u8,
    /// Day of month, 1–31.
    pub day: u8,
    /// Hour, 0–23.
    pub hour: u8,
    /// Minute, 0–59.
    pub minute: u8,
    /// Second, 0–59.
    pub second: u8,
    /// Offset from GMT in 15-minute intervals (range -48..=52).
    pub gmt_offset_quarter_hours: i8,
}

impl Iso9660DateTime {
    /// Parse a 7-byte recording date/time field.
    ///
    /// Returns `None` if the slice is shorter than 7 bytes or the field is all
    /// zero (the "not specified" encoding).
    pub fn parse(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < 7 || bytes[..7].iter().all(|&b| b == 0) {
            return None;
        }
        Some(Self {
            years_since_1900: bytes[0],
            month: bytes[1],
            day: bytes[2],
            hour: bytes[3],
            minute: bytes[4],
            second: bytes[5],
            gmt_offset_quarter_hours: bytes[6] as i8,
        })
    }

    /// Full four-digit year (e.g. 1997).
    pub fn year(&self) -> u16 {
        1900 + self.years_since_1900 as u16
    }

    /// Render as ISO-8601, e.g. `1997-03-18T16:45:47+00:00`.
    pub fn to_iso8601(&self) -> String {
        let total_minutes = self.gmt_offset_quarter_hours as i32 * 15;
        let sign = if total_minutes < 0 { '-' } else { '+' };
        let abs = total_minutes.abs();
        format!(
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{}{:02}:{:02}",
            self.year(),
            self.month,
            self.day,
            self.hour,
            self.minute,
            self.second,
            sign,
            abs / 60,
            abs % 60,
        )
    }
}

/// Information extracted from an ISO 9660 Primary Volume Descriptor.
#[derive(Debug, Clone)]
pub struct PrimaryVolumeDescriptor {
    /// Volume identifier (label), up to 32 characters.
    pub volume_id: String,
    /// System identifier, up to 32 characters.
    pub system_id: String,
    /// Volume set identifier, up to 128 characters.
    pub volume_set_id: String,
    /// Publisher identifier, up to 128 characters.
    pub publisher_id: String,
    /// Application identifier, up to 128 characters.
    pub application_id: String,
    /// Total number of logical blocks on the volume.
    pub volume_space_size: u32,
    /// Logical block size in bytes (almost always 2048).
    pub logical_block_size: u16,
    /// LBA of the root directory extent.
    pub root_directory_lba: u32,
    /// Size of the root directory extent in bytes.
    pub root_directory_size: u32,
    /// Volume creation date/time (PVD offset 813), `None` if not specified.
    pub creation_date: Option<PvdDateTime>,
    /// Volume modification date/time (PVD offset 830), `None` if not specified.
    pub modification_date: Option<PvdDateTime>,
    /// Volume expiration date/time (PVD offset 847), `None` if not specified.
    pub expiration_date: Option<PvdDateTime>,
    /// Volume effective date/time (PVD offset 864), `None` if not specified.
    pub effective_date: Option<PvdDateTime>,
}

impl PrimaryVolumeDescriptor {
    /// Read and parse the PVD via a `SectorReader`.
    pub fn read_from(reader: &mut dyn SectorReader) -> Result<Self> {
        let sector = reader.read_sector(PVD_SECTOR)?;
        Self::parse(&sector)
    }

    /// Parse a PVD from a raw 2048-byte sector slice.
    pub fn parse(sector: &[u8]) -> Result<Self> {
        if sector.len() < crate::sector_reader::SECTOR_SIZE as usize {
            return Err(OpticaldiscsError::Parse(format!(
                "sector too small: {} bytes",
                sector.len()
            )));
        }

        match sector[0] {
            PVD_TYPE => {}
            VD_SET_TERMINATOR_TYPE => {
                return Err(OpticaldiscsError::Parse(
                    "reached Volume Descriptor Set Terminator before PVD".into(),
                ))
            }
            t => {
                return Err(OpticaldiscsError::Parse(format!(
                    "unexpected volume descriptor type 0x{t:02X} (expected 0x01)"
                )))
            }
        }

        if &sector[1..6] != ISO9660_ID {
            return Err(OpticaldiscsError::Parse(
                "missing ISO 9660 identifier 'CD001'".into(),
            ));
        }

        if sector[6] != 1 {
            return Err(OpticaldiscsError::Parse(format!(
                "unsupported PVD version {}",
                sector[6]
            )));
        }

        // ECMA-119 §8.4 field offsets
        let system_id = Self::extract_str(&sector[8..40]);
        let volume_id = Self::extract_str(&sector[40..72]);
        let volume_space_size = u32::from_le_bytes(sector[80..84].try_into().unwrap());
        let logical_block_size = u16::from_le_bytes(sector[128..130].try_into().unwrap());
        let volume_set_id = Self::extract_str(&sector[190..318]);
        let publisher_id = Self::extract_str(&sector[318..446]);
        let application_id = Self::extract_str(&sector[574..702]);

        // Root Directory Record is embedded at offset 156 (34 bytes)
        let rdr = &sector[156..190];
        let root_directory_lba = u32::from_le_bytes(rdr[2..6].try_into().unwrap());
        let root_directory_size = u32::from_le_bytes(rdr[10..14].try_into().unwrap());

        // Volume date/time fields (ECMA-119 §8.4.26..29), each 17 bytes.
        let creation_date = PvdDateTime::parse(&sector[813..830]);
        let modification_date = PvdDateTime::parse(&sector[830..847]);
        let expiration_date = PvdDateTime::parse(&sector[847..864]);
        let effective_date = PvdDateTime::parse(&sector[864..881]);

        Ok(Self {
            volume_id,
            system_id,
            volume_set_id,
            publisher_id,
            application_id,
            volume_space_size,
            logical_block_size,
            root_directory_lba,
            root_directory_size,
            creation_date,
            modification_date,
            expiration_date,
            effective_date,
        })
    }

    /// Trim trailing spaces and NUL bytes from an ISO 9660 fixed-width string.
    fn extract_str(bytes: &[u8]) -> String {
        String::from_utf8_lossy(bytes)
            .trim_end_matches([' ', '\0'])
            .to_string()
    }
}

/// Volume-descriptor type code for a Supplementary Volume Descriptor (ECMA-119
/// §8.5). Joliet stores its Unicode directory tree in one of these.
const SVD_TYPE: u8 = 0x02;

/// Decode a big-endian UTF-16 (UCS-2) byte slice — the encoding Joliet uses for
/// volume and file identifiers. A trailing odd byte is ignored; invalid
/// sequences become U+FFFD.
pub(crate) fn decode_utf16be(bytes: &[u8]) -> String {
    let units: Vec<u16> = bytes
        .chunks_exact(2)
        .map(|c| u16::from_be_bytes([c[0], c[1]]))
        .collect();
    String::from_utf16_lossy(&units)
}

/// A Joliet Supplementary Volume Descriptor: just enough to browse the Joliet
/// directory tree (which carries UCS-2 / UTF-16BE names).
#[derive(Debug, Clone)]
pub struct JolietVolumeDescriptor {
    /// Volume identifier (label), decoded from UTF-16BE.
    pub volume_id: String,
    /// Root directory extent LBA of the Joliet tree.
    pub root_directory_lba: u32,
    /// Root directory extent size in bytes.
    pub root_directory_size: u32,
}

impl JolietVolumeDescriptor {
    /// Scan the volume-descriptor set (starting at sector 16) for a Joliet SVD:
    /// a Supplementary Volume Descriptor whose escape sequences (bytes 88..120)
    /// select a UCS-2 level (`%/@`, `%/C`, or `%/E`).
    ///
    /// Returns `Ok(None)` if the disc has no Joliet tree.
    pub fn find(reader: &mut dyn SectorReader) -> Result<Option<Self>> {
        // Bound the scan so damaged media can't spin forever.
        for i in 0..32u64 {
            let sector = match reader.read_sector(PVD_SECTOR + i) {
                Ok(s) => s,
                Err(_) => break,
            };
            if sector.len() < 190 || &sector[1..6] != ISO9660_ID {
                break;
            }
            let vd_type = sector[0];
            if vd_type == VD_SET_TERMINATOR_TYPE {
                break;
            }
            if vd_type == SVD_TYPE && is_joliet_escape(&sector[88..120]) {
                let volume_id = decode_utf16be(&sector[40..72])
                    .trim_end_matches([' ', '\0'])
                    .to_string();
                let rdr = &sector[156..190];
                let root_directory_lba = u32::from_le_bytes(rdr[2..6].try_into().unwrap());
                let root_directory_size = u32::from_le_bytes(rdr[10..14].try_into().unwrap());
                return Ok(Some(Self {
                    volume_id,
                    root_directory_lba,
                    root_directory_size,
                }));
            }
        }
        Ok(None)
    }
}

/// True if a descriptor's escape-sequence field selects a Joliet UCS-2 level.
fn is_joliet_escape(escape: &[u8]) -> bool {
    escape
        .windows(3)
        .any(|w| w == b"%/@" || w == b"%/C" || w == b"%/E")
}

// ── Helpers for tests and detect.rs ──────────────────────────────────────────

/// Build a minimal but structurally valid 2048-byte PVD sector for testing.
///
/// Produces a byte vector that `PrimaryVolumeDescriptor::parse()` will accept.
/// Intended for unit and integration tests in this crate and downstream crates.
#[doc(hidden)]
pub fn build_test_pvd_sector(volume_id: &str, root_lba: u32, root_size: u32) -> Vec<u8> {
    let mut s = vec![0u8; 2048];
    s[0] = PVD_TYPE;
    s[1..6].copy_from_slice(ISO9660_ID);
    s[6] = 1; // version

    // System identifier (offset 8, 32 bytes)
    let sys = b"CDROM                           ";
    s[8..40].copy_from_slice(sys);

    // Volume identifier (offset 40, 32 bytes)
    let mut vol = [b' '; 32];
    let src = volume_id.as_bytes();
    let len = src.len().min(32);
    vol[..len].copy_from_slice(&src[..len]);
    s[40..72].copy_from_slice(&vol);

    // Volume space size LE+BE (offsets 80..84, 84..88)
    let total = 100u32;
    s[80..84].copy_from_slice(&total.to_le_bytes());
    s[84..88].copy_from_slice(&total.to_be_bytes());

    // Logical block size LE+BE (offsets 128..130, 130..132)
    s[128..130].copy_from_slice(&2048u16.to_le_bytes());
    s[130..132].copy_from_slice(&2048u16.to_be_bytes());

    // Root Directory Record at offset 156
    // [0]   record length = 34
    // [1]   extended attr length = 0
    // [2..6]  LBA LE
    // [6..10] LBA BE
    // [10..14] data length LE
    // [14..18] data length BE
    // [25]  file flags = 0x02 (directory)
    // [32]  file identifier length = 1
    // [33]  file identifier = 0x00 (current)
    let rdr = &mut s[156..190];
    rdr[0] = 34;
    rdr[2..6].copy_from_slice(&root_lba.to_le_bytes());
    rdr[6..10].copy_from_slice(&root_lba.to_be_bytes());
    rdr[10..14].copy_from_slice(&root_size.to_le_bytes());
    rdr[14..18].copy_from_slice(&root_size.to_be_bytes());
    rdr[25] = 0x02;
    rdr[32] = 1;
    rdr[33] = 0x00;

    s
}

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

    #[test]
    fn parse_valid_pvd() {
        let sector = build_test_pvd_sector("MY_DISC", 20, 2048);
        let pvd = PrimaryVolumeDescriptor::parse(&sector).unwrap();
        assert_eq!(pvd.volume_id, "MY_DISC");
        assert_eq!(pvd.system_id, "CDROM");
        assert_eq!(pvd.logical_block_size, 2048);
        assert_eq!(pvd.root_directory_lba, 20);
        assert_eq!(pvd.root_directory_size, 2048);
    }

    /// Write a 17-byte dec-datetime field into `sector` at `offset`.
    fn write_datetime(sector: &mut [u8], offset: usize, ascii16: &[u8; 16], gmt: i8) {
        sector[offset..offset + 16].copy_from_slice(ascii16);
        sector[offset + 16] = gmt as u8;
    }

    #[test]
    fn parse_creation_date() {
        let mut sector = build_test_pvd_sector("DATED_DISC", 20, 2048);
        write_datetime(&mut sector, 813, b"1997031816454700", 0);

        let pvd = PrimaryVolumeDescriptor::parse(&sector).unwrap();
        let dt = pvd.creation_date.expect("creation date present");
        assert_eq!(dt.year, 1997);
        assert_eq!(dt.month, 3);
        assert_eq!(dt.day, 18);
        assert_eq!(dt.hour, 16);
        assert_eq!(dt.minute, 45);
        assert_eq!(dt.second, 47);
        assert_eq!(dt.hundredths, 0);
        assert_eq!(dt.gmt_offset_quarter_hours, 0);
        assert_eq!(dt.to_iso8601(), "1997-03-18T16:45:47.00+00:00");
    }

    #[test]
    fn parse_date_not_specified() {
        // All ASCII '0' with zero offset → None.
        let mut sector = build_test_pvd_sector("X", 20, 2048);
        write_datetime(&mut sector, 813, b"0000000000000000", 0);
        let pvd = PrimaryVolumeDescriptor::parse(&sector).unwrap();
        assert_eq!(pvd.creation_date, None);

        // All 0x00 (default fixture state) → None.
        let sector = build_test_pvd_sector("X", 20, 2048);
        let pvd = PrimaryVolumeDescriptor::parse(&sector).unwrap();
        assert_eq!(pvd.creation_date, None);
        assert_eq!(pvd.modification_date, None);
        assert_eq!(pvd.expiration_date, None);
        assert_eq!(pvd.effective_date, None);
    }

    #[test]
    fn parse_negative_gmt_offset() {
        let mut sector = build_test_pvd_sector("X", 20, 2048);
        // -28 quarter-hours = -07:00
        write_datetime(&mut sector, 813, b"1997031816454700", -28);
        let pvd = PrimaryVolumeDescriptor::parse(&sector).unwrap();
        let dt = pvd.creation_date.unwrap();
        assert_eq!(dt.gmt_offset_quarter_hours, -28);
        assert_eq!(dt.to_iso8601(), "1997-03-18T16:45:47.00-07:00");
    }

    #[test]
    fn parse_date_rejects_non_digits() {
        let mut sector = build_test_pvd_sector("X", 20, 2048);
        write_datetime(&mut sector, 813, b"19X7031816454700", 0);
        let pvd = PrimaryVolumeDescriptor::parse(&sector).unwrap();
        assert_eq!(pvd.creation_date, None);
    }

    #[test]
    fn parse_rejects_wrong_magic() {
        let mut sector = build_test_pvd_sector("X", 20, 2048);
        sector[1..6].copy_from_slice(b"XXXXX");
        assert!(PrimaryVolumeDescriptor::parse(&sector).is_err());
    }

    #[test]
    fn parse_rejects_wrong_type() {
        let mut sector = build_test_pvd_sector("X", 20, 2048);
        sector[0] = 0x02; // Supplementary VD, not Primary
        assert!(PrimaryVolumeDescriptor::parse(&sector).is_err());
    }

    #[test]
    fn parse_rejects_terminator() {
        let mut sector = build_test_pvd_sector("X", 20, 2048);
        sector[0] = 0xFF;
        assert!(PrimaryVolumeDescriptor::parse(&sector).is_err());
    }

    #[test]
    fn extract_str_trims_spaces_and_nulls() {
        let bytes = b"HELLO   \0\0";
        assert_eq!(PrimaryVolumeDescriptor::extract_str(bytes), "HELLO");
    }

    #[test]
    fn read_from_sector_reader() {
        use crate::sector_reader::SECTOR_SIZE;
        use std::io::Cursor;

        // Build a minimal disc image: 17 empty sectors + PVD at sector 16
        let total = (PVD_SECTOR + 1) * SECTOR_SIZE;
        let mut img = vec![0u8; total as usize];
        let pvd_bytes = build_test_pvd_sector("READER_TEST", 18, 2048);
        let start = (PVD_SECTOR * SECTOR_SIZE) as usize;
        img[start..start + 2048].copy_from_slice(&pvd_bytes);

        let mut reader = CursorSectorReader(Cursor::new(img));
        let pvd = PrimaryVolumeDescriptor::read_from(&mut reader).unwrap();
        assert_eq!(pvd.volume_id, "READER_TEST");
    }

    #[test]
    fn iso9660_datetime_parses_binary_form() {
        // years-since-1900=97, 1997-03-18 16:45:47, GMT+0.
        let dt = Iso9660DateTime::parse(&[97, 3, 18, 16, 45, 47, 0]).unwrap();
        assert_eq!(dt.year(), 1997);
        assert_eq!(dt.month, 3);
        assert_eq!(dt.day, 18);
        assert_eq!(dt.hour, 16);
        assert_eq!(dt.second, 47);
        assert_eq!(dt.to_iso8601(), "1997-03-18T16:45:47+00:00");
    }

    #[test]
    fn iso9660_datetime_not_specified_and_short() {
        assert_eq!(Iso9660DateTime::parse(&[0, 0, 0, 0, 0, 0, 0]), None);
        assert_eq!(Iso9660DateTime::parse(&[97, 3, 18]), None);
    }

    #[test]
    fn iso9660_datetime_negative_gmt_offset() {
        // GMT offset -4h = -16 quarter-hours.
        let dt = Iso9660DateTime::parse(&[97, 3, 18, 12, 0, 0, (-16i8) as u8]).unwrap();
        assert_eq!(dt.to_iso8601(), "1997-03-18T12:00:00-04:00");
    }

    #[test]
    fn decode_utf16be_basic() {
        let bytes: Vec<u8> = "Héllo".encode_utf16().flat_map(u16::to_be_bytes).collect();
        assert_eq!(decode_utf16be(&bytes), "Héllo");
    }

    /// Build a 2048-byte Joliet SVD sector (root at `root_lba`, label `label`).
    fn build_joliet_svd(label: &str, root_lba: u32) -> Vec<u8> {
        let mut svd = vec![0u8; 2048];
        svd[0] = SVD_TYPE;
        svd[1..6].copy_from_slice(ISO9660_ID);
        svd[6] = 1;
        svd[88..91].copy_from_slice(b"%/E"); // Joliet level 3 escape
        let vid: Vec<u8> = label.encode_utf16().flat_map(u16::to_be_bytes).collect();
        svd[40..40 + vid.len()].copy_from_slice(&vid);
        let rdr = &mut svd[156..190];
        rdr[0] = 34;
        rdr[2..6].copy_from_slice(&root_lba.to_le_bytes());
        rdr[6..10].copy_from_slice(&root_lba.to_be_bytes());
        rdr[10..14].copy_from_slice(&2048u32.to_le_bytes());
        rdr[14..18].copy_from_slice(&2048u32.to_be_bytes());
        svd
    }

    #[test]
    fn joliet_find_returns_svd() {
        // Sector 16 = PVD, 17 = Joliet SVD, 18 = terminator.
        let mut img = vec![0u8; 19 * 2048];
        img[16 * 2048..17 * 2048].copy_from_slice(&build_test_pvd_sector("PRIMARY", 20, 2048));
        img[17 * 2048..18 * 2048].copy_from_slice(&build_joliet_svd("JOLIET", 30));
        img[18 * 2048] = VD_SET_TERMINATOR_TYPE;
        img[18 * 2048 + 1..18 * 2048 + 6].copy_from_slice(ISO9660_ID);

        let mut reader = CursorSectorReader(std::io::Cursor::new(img));
        let svd = JolietVolumeDescriptor::find(&mut reader).unwrap().unwrap();
        assert_eq!(svd.volume_id, "JOLIET");
        assert_eq!(svd.root_directory_lba, 30);
        assert_eq!(svd.root_directory_size, 2048);
    }

    #[test]
    fn joliet_find_none_for_plain_iso() {
        // Sector 16 = PVD, 17 = terminator, no SVD.
        let mut img = vec![0u8; 18 * 2048];
        img[16 * 2048..17 * 2048].copy_from_slice(&build_test_pvd_sector("PLAIN", 20, 2048));
        img[17 * 2048] = VD_SET_TERMINATOR_TYPE;
        img[17 * 2048 + 1..17 * 2048 + 6].copy_from_slice(ISO9660_ID);

        let mut reader = CursorSectorReader(std::io::Cursor::new(img));
        assert!(JolietVolumeDescriptor::find(&mut reader).unwrap().is_none());
    }

    /// Minimal SectorReader wrapper around a Cursor for testing.
    struct CursorSectorReader(std::io::Cursor<Vec<u8>>);
    impl SectorReader for CursorSectorReader {
        fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>> {
            use std::io::{Read, Seek, SeekFrom};
            self.0
                .seek(SeekFrom::Start(lba * crate::sector_reader::SECTOR_SIZE))
                .map_err(OpticaldiscsError::Io)?;
            let mut buf = vec![0u8; crate::sector_reader::SECTOR_SIZE as usize];
            self.0.read_exact(&mut buf).map_err(OpticaldiscsError::Io)?;
            Ok(buf)
        }
    }
}