hadris-iso 1.2.0

A rust implementation of the ISO-9660 filesystem.
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
//! Tests for RRIP (Rock Ridge) reader support.
//!
//! Tests RRIP auto-detection, NM name assembly, SL symlink reconstruction,
//! TF timestamp parsing, CE continuation area reading, and the RRIP-aware
//! directory iterator.

use hadris_iso::read::IsoImage;
use hadris_iso::read::PathSeparator;
use hadris_iso::write::options::{CreationFeatures, FormatOptions};
use hadris_iso::write::{File as IsoFile, InputFiles, IsoImageWriter};
use std::io::Cursor;
use std::sync::Arc;

/// Helper to create an ISO image from files with given features.
fn create_iso(files: Vec<IsoFile>, features: CreationFeatures) -> Vec<u8> {
    let input = InputFiles {
        path_separator: PathSeparator::ForwardSlash,
        files,
    };
    let options = FormatOptions {
        volume_name: "TEST".to_string(),
        system_id: None,
        volume_set_id: None,
        publisher_id: None,
        preparer_id: None,
        application_id: None,
        sector_size: 2048,
        path_separator: PathSeparator::ForwardSlash,
        features,
        strict_charset: false,
    };
    let mut buffer = Cursor::new(vec![0u8; 4 * 1024 * 1024]);
    IsoImageWriter::format_new(&mut buffer, input, options).unwrap();
    buffer.into_inner()
}

// =============================================================================
// RRIP Detection Tests
// =============================================================================

#[test]
fn test_rrip_detection_with_rock_ridge() {
    let files = vec![IsoFile::File {
        name: Arc::new("hello.txt".to_string()),
        contents: b"Hello, World!".to_vec(),
    }];
    let iso_data = create_iso(files, CreationFeatures::with_rock_ridge());
    let image = IsoImage::open(Cursor::new(iso_data)).unwrap();
    assert!(
        image.supports_rrip(),
        "RRIP should be detected for Rock Ridge ISO"
    );
}

#[test]
fn test_rrip_detection_without_rock_ridge() {
    let files = vec![IsoFile::File {
        name: Arc::new("hello.txt".to_string()),
        contents: b"Hello, World!".to_vec(),
    }];
    let iso_data = create_iso(files, CreationFeatures::default());
    let image = IsoImage::open(Cursor::new(iso_data)).unwrap();
    assert!(
        !image.supports_rrip(),
        "RRIP should NOT be detected for plain ISO"
    );
}

// =============================================================================
// NM Name Assembly Tests
// =============================================================================

#[test]
fn test_rrip_nm_names() {
    let files = vec![
        IsoFile::File {
            name: Arc::new("readme.txt".to_string()),
            contents: b"readme content".to_vec(),
        },
        IsoFile::File {
            name: Arc::new("LongFileName_WithMixedCase.dat".to_string()),
            contents: b"data".to_vec(),
        },
    ];
    let iso_data = create_iso(files, CreationFeatures::with_rock_ridge());
    let image = IsoImage::open(Cursor::new(iso_data)).unwrap();

    let root = image.root_dir();
    let dir = root.iter(&image);
    let entries: Vec<_> = dir
        .entries()
        .filter_map(|e| e.ok())
        .filter(|e| !e.is_special())
        .collect();

    // Collect RRIP names
    let names: Vec<String> = entries
        .iter()
        .map(|e| e.display_name().into_owned())
        .collect();

    assert!(
        names.contains(&"readme.txt".to_string()),
        "Should find 'readme.txt' via RRIP NM, got: {:?}",
        names
    );
    assert!(
        names.contains(&"LongFileName_WithMixedCase.dat".to_string()),
        "Should find mixed-case filename via RRIP NM, got: {:?}",
        names
    );
}

// =============================================================================
// TF Timestamp Parsing Tests
// =============================================================================

#[test]
fn test_rrip_tf_timestamps() {
    let files = vec![IsoFile::File {
        name: Arc::new("test.txt".to_string()),
        contents: b"test".to_vec(),
    }];
    let iso_data = create_iso(files, CreationFeatures::with_rock_ridge());
    let image = IsoImage::open(Cursor::new(iso_data)).unwrap();

    let root = image.root_dir();
    let dir = root.iter(&image);
    let entries: Vec<_> = dir
        .entries()
        .filter_map(|e| e.ok())
        .filter(|e| !e.is_special())
        .collect();

    assert!(!entries.is_empty(), "Should have at least one file entry");

    let entry = &entries[0];
    if let Some(ref ts) = entry.rrip.as_ref().unwrap().timestamps {
        // The writer should produce at least MODIFY and ACCESS timestamps
        if let Some(ref modify) = ts.modify {
            assert!(
                modify.year >= 2024,
                "Modify year should be recent: {}",
                modify.year
            );
            assert!(modify.month >= 1 && modify.month <= 12);
        }
    }
    // Note: timestamps may or may not be present depending on writer behavior
}

// =============================================================================
// PX POSIX Attributes Tests
// =============================================================================

#[test]
fn test_rrip_px_attributes() {
    let files = vec![
        IsoFile::File {
            name: Arc::new("file.txt".to_string()),
            contents: b"content".to_vec(),
        },
        IsoFile::Directory {
            name: Arc::new("subdir".to_string()),
            children: vec![],
        },
    ];
    let iso_data = create_iso(files, CreationFeatures::with_rock_ridge());
    let image = IsoImage::open(Cursor::new(iso_data)).unwrap();

    let root = image.root_dir();
    let dir = root.iter(&image);
    let entries: Vec<_> = dir
        .entries()
        .filter_map(|e| e.ok())
        .filter(|e| !e.is_special())
        .collect();

    for entry in &entries {
        if let Some(ref px) = entry.rrip.as_ref().unwrap().posix_attributes {
            let mode = px.file_mode.read();
            if entry.is_directory() {
                // Directory should have directory file type bit set (0o040000)
                assert!(
                    mode & 0o170000 == 0o040000,
                    "Directory should have S_IFDIR mode, got {:#o}",
                    mode
                );
            } else {
                // Regular file should have regular file type bit set (0o100000)
                assert!(
                    mode & 0o170000 == 0o100000,
                    "File should have S_IFREG mode, got {:#o}",
                    mode
                );
            }
        }
    }
}

// =============================================================================
// Directory Iterator Tests
// =============================================================================

#[test]
fn test_rrip_directory_iteration() {
    let files = vec![
        IsoFile::File {
            name: Arc::new("alpha.txt".to_string()),
            contents: b"alpha".to_vec(),
        },
        IsoFile::File {
            name: Arc::new("beta.txt".to_string()),
            contents: b"beta".to_vec(),
        },
        IsoFile::Directory {
            name: Arc::new("gamma_dir".to_string()),
            children: vec![],
        },
    ];
    let iso_data = create_iso(files, CreationFeatures::with_rock_ridge());
    let image = IsoImage::open(Cursor::new(iso_data)).unwrap();

    let root = image.root_dir();
    let dir = root.iter(&image);

    // Count non-special entries (should be alpha.txt, beta.txt, gamma_dir)
    let entries: Vec<_> = dir
        .entries()
        .filter_map(|e| e.ok())
        .filter(|e| !e.is_special())
        .collect();

    assert_eq!(
        entries.len(),
        3,
        "Should have 3 non-special entries, got {}",
        entries.len()
    );

    // Verify directory vs file detection
    let dir_count = entries.iter().filter(|e| e.is_directory()).count();
    let file_count = entries.iter().filter(|e| !e.is_directory()).count();
    assert_eq!(dir_count, 1, "Should have 1 directory");
    assert_eq!(file_count, 2, "Should have 2 files");
}

#[test]
fn test_rrip_subdirectory_navigation() {
    let files = vec![IsoFile::Directory {
        name: Arc::new("mydir".to_string()),
        children: vec![IsoFile::File {
            name: Arc::new("inner.txt".to_string()),
            contents: b"inner content".to_vec(),
        }],
    }];
    let iso_data = create_iso(files, CreationFeatures::with_rock_ridge());
    let image = IsoImage::open(Cursor::new(iso_data)).unwrap();

    let root = image.root_dir();
    let root_dir = root.iter(&image);
    let root_entries: Vec<_> = root_dir
        .entries()
        .filter_map(|e| e.ok())
        .filter(|e| !e.is_special())
        .collect();

    // Find the subdirectory
    let subdir_entry = root_entries
        .iter()
        .find(|e| e.is_directory())
        .expect("Should find a subdirectory");

    // Navigate into the subdirectory
    let subdir_ref = subdir_entry.as_dir_ref(&image).unwrap();
    let subdir = image.open_dir(subdir_ref);
    let sub_entries: Vec<_> = subdir
        .entries()
        .filter_map(|e| e.ok())
        .filter(|e| !e.is_special())
        .collect();

    assert_eq!(
        sub_entries.len(),
        1,
        "Subdirectory should have 1 file, got {}",
        sub_entries.len()
    );

    let inner_name = sub_entries[0].display_name();
    assert_eq!(
        inner_name, "inner.txt",
        "Inner file should be 'inner.txt', got '{}'",
        inner_name
    );
}

// =============================================================================
// ES Extension Selector Parsing Tests
// =============================================================================

#[test]
fn test_es_parsing() {
    use hadris_iso::susp::{SystemUseField, SystemUseIter};

    // ES entry: sig='ES', length=5, version=1, extension_sequence=42
    let data: &[u8] = &[b'E', b'S', 5, 1, 42];
    let mut iter = SystemUseIter::new(data, 0);
    match iter.next() {
        Some(SystemUseField::ExtensionSelector { extension_sequence }) => {
            assert_eq!(extension_sequence, 42);
        }
        other => panic!("expected ES entry, got {:?}", other),
    }
    assert!(iter.next().is_none());
}

// =============================================================================
// SL Symlink Path Assembly Tests (unit-level)
// =============================================================================

#[test]
fn test_sl_absolute_path_assembly() {
    use hadris_iso::read::RripMetadata;
    use hadris_iso::rrip::{SlComponent, SlComponentFlags, SlEntry};
    use hadris_iso::susp::SystemUseField;

    // Build SL for "/usr/bin"
    let sl = SlEntry {
        flags: 0,
        components: vec![
            SlComponent {
                flags: SlComponentFlags::ROOT,
                content: vec![],
            },
            SlComponent {
                flags: SlComponentFlags::empty(),
                content: b"usr".to_vec(),
            },
            SlComponent {
                flags: SlComponentFlags::empty(),
                content: b"bin".to_vec(),
            },
        ],
    };
    let fields = vec![SystemUseField::SymbolicLink(sl)];
    let meta = RripMetadata::from_fields(&fields);
    assert_eq!(meta.symlink_target.as_deref(), Some("/usr/bin"));
}

#[test]
fn test_sl_relative_path_assembly() {
    use hadris_iso::read::RripMetadata;
    use hadris_iso::rrip::{SlComponent, SlComponentFlags, SlEntry};
    use hadris_iso::susp::SystemUseField;

    // Build SL for "../lib/libfoo.so"
    let sl = SlEntry {
        flags: 0,
        components: vec![
            SlComponent {
                flags: SlComponentFlags::PARENT,
                content: vec![],
            },
            SlComponent {
                flags: SlComponentFlags::empty(),
                content: b"lib".to_vec(),
            },
            SlComponent {
                flags: SlComponentFlags::empty(),
                content: b"libfoo.so".to_vec(),
            },
        ],
    };
    let fields = vec![SystemUseField::SymbolicLink(sl)];
    let meta = RripMetadata::from_fields(&fields);
    assert_eq!(meta.symlink_target.as_deref(), Some("../lib/libfoo.so"));
}

#[test]
fn test_sl_continue_component_assembly() {
    use hadris_iso::read::RripMetadata;
    use hadris_iso::rrip::{SlComponent, SlComponentFlags, SlEntry};
    use hadris_iso::susp::SystemUseField;

    // Build SL where a component is split across entries using CONTINUE
    let sl = SlEntry {
        flags: 0,
        components: vec![
            SlComponent {
                flags: SlComponentFlags::CONTINUE,
                content: b"long".to_vec(),
            },
            SlComponent {
                flags: SlComponentFlags::empty(),
                content: b"name".to_vec(),
            },
        ],
    };
    let fields = vec![SystemUseField::SymbolicLink(sl)];
    let meta = RripMetadata::from_fields(&fields);
    assert_eq!(meta.symlink_target.as_deref(), Some("longname"));
}

// =============================================================================
// NM Multi-Entry Concatenation Tests (unit-level)
// =============================================================================

#[test]
fn test_nm_multi_entry_concatenation() {
    use hadris_iso::read::RripMetadata;
    use hadris_iso::rrip::{NmEntry, NmFlags};
    use hadris_iso::susp::SystemUseField;

    // Two NM entries that should concatenate
    let fields = vec![
        SystemUseField::AlternateName(NmEntry {
            flags: NmFlags::CONTINUE,
            name: b"very_long_file".to_vec(),
        }),
        SystemUseField::AlternateName(NmEntry {
            flags: NmFlags::empty(),
            name: b"name.txt".to_vec(),
        }),
    ];
    let meta = RripMetadata::from_fields(&fields);
    assert_eq!(
        meta.alternate_name.as_deref(),
        Some("very_long_filename.txt")
    );
}

#[test]
fn test_nm_current_directory() {
    use hadris_iso::read::RripMetadata;
    use hadris_iso::rrip::{NmEntry, NmFlags};
    use hadris_iso::susp::SystemUseField;

    let fields = vec![SystemUseField::AlternateName(NmEntry {
        flags: NmFlags::CURRENT,
        name: vec![],
    })];
    let meta = RripMetadata::from_fields(&fields);
    assert_eq!(meta.alternate_name.as_deref(), Some("."));
}

#[test]
fn test_nm_parent_directory() {
    use hadris_iso::read::RripMetadata;
    use hadris_iso::rrip::{NmEntry, NmFlags};
    use hadris_iso::susp::SystemUseField;

    let fields = vec![SystemUseField::AlternateName(NmEntry {
        flags: NmFlags::PARENT,
        name: vec![],
    })];
    let meta = RripMetadata::from_fields(&fields);
    assert_eq!(meta.alternate_name.as_deref(), Some(".."));
}

#[test]
fn test_rrip_detection_with_joliet_and_rock_ridge() {
    let files = vec![IsoFile::File {
        name: Arc::new("hello.txt".to_string()),
        contents: b"Hello, World!".to_vec(),
    }];
    let iso_data = create_iso(files, CreationFeatures::with_extensions());
    let image = IsoImage::open(Cursor::new(iso_data)).unwrap();
    assert!(
        image.supports_rrip(),
        "RRIP should be detected with Joliet+RR"
    );
}

#[test]
fn test_pvd_root_directory_has_directory_flag() {
    use hadris_iso::directory::FileFlags;

    let files = vec![IsoFile::File {
        name: Arc::new("test.txt".to_string()),
        contents: b"test".to_vec(),
    }];
    let iso_data = create_iso(files, CreationFeatures::default());

    // PVD is at sector 16 (offset 32768). Root directory record at PVD offset 156.
    // File flags byte is at offset 25 within the directory record.
    let pvd_root_flags = iso_data[32768 + 156 + 25];
    assert_eq!(
        pvd_root_flags,
        FileFlags::DIRECTORY.bits(),
        "PVD root directory record must have DIRECTORY flag set"
    );
}

#[test]
fn test_pvd_root_directory_record_fields() {
    let files = vec![IsoFile::File {
        name: Arc::new("test.txt".to_string()),
        contents: b"test".to_vec(),
    }];
    let iso_data = create_iso(files, CreationFeatures::default());

    // Root directory record starts at PVD offset 156 (byte 32768 + 156 = 32924)
    let base = 32768 + 156;
    let record_len = iso_data[base];
    let file_id_len = iso_data[base + 32];
    let vol_seq_le = u16::from_le_bytes([iso_data[base + 28], iso_data[base + 29]]);

    assert_eq!(record_len, 34, "Root directory record length should be 34");
    assert_eq!(
        file_id_len, 1,
        "Root directory file_identifier_len should be 1"
    );
    assert_eq!(
        vol_seq_le, 1,
        "Root directory volume_sequence_number should be 1"
    );
}

#[test]
fn test_joliet_svd_volume_name_utf16be() {
    let files = vec![IsoFile::File {
        name: Arc::new("test.txt".to_string()),
        contents: b"test".to_vec(),
    }];

    // Create ISO with Joliet and custom volume name
    let input = InputFiles {
        path_separator: PathSeparator::ForwardSlash,
        files,
    };
    let options = FormatOptions {
        volume_name: "MYISO".to_string(),
        system_id: None,
        volume_set_id: None,
        publisher_id: None,
        preparer_id: None,
        application_id: None,
        sector_size: 2048,
        path_separator: PathSeparator::ForwardSlash,
        features: CreationFeatures::with_joliet(hadris_iso::joliet::JolietLevel::Level3),
        strict_charset: false,
    };
    let mut buffer = Cursor::new(vec![0u8; 4 * 1024 * 1024]);
    IsoImageWriter::format_new(&mut buffer, input, options).unwrap();
    let iso_data = buffer.into_inner();

    // Find the Joliet SVD (type 0x02 = Supplementary VD, after PVD at sector 16)
    // SVD should be at sector 17
    let svd_offset = 17 * 2048;
    assert_eq!(iso_data[svd_offset], 0x02, "Sector 17 should be SVD");

    // Volume identifier is at offset 40, 32 bytes
    let vol_id = &iso_data[svd_offset + 40..svd_offset + 40 + 32];

    // "MYISO" in UTF-16BE: 00 4D 00 59 00 49 00 53 00 4F
    assert_eq!(
        vol_id[0..2],
        [0x00, b'M'],
        "First char should be UTF-16BE 'M'"
    );
    assert_eq!(
        vol_id[2..4],
        [0x00, b'Y'],
        "Second char should be UTF-16BE 'Y'"
    );
    assert_eq!(
        vol_id[4..6],
        [0x00, b'I'],
        "Third char should be UTF-16BE 'I'"
    );
    assert_eq!(
        vol_id[6..8],
        [0x00, b'S'],
        "Fourth char should be UTF-16BE 'S'"
    );
    assert_eq!(
        vol_id[8..10],
        [0x00, b'O'],
        "Fifth char should be UTF-16BE 'O'"
    );
    // Remaining should be UTF-16BE spaces (0x00, 0x20)
    assert_eq!(
        vol_id[10..12],
        [0x00, 0x20],
        "Padding should be UTF-16BE space"
    );
}

#[test]
fn test_joliet_svd_strings_are_utf16be() {
    let files = vec![IsoFile::File {
        name: Arc::new("test.txt".to_string()),
        contents: b"test".to_vec(),
    }];

    let input = InputFiles {
        path_separator: PathSeparator::ForwardSlash,
        files,
    };
    let options = FormatOptions {
        volume_name: "TEST".to_string(),
        system_id: None,
        volume_set_id: None,
        publisher_id: Some("MY PUBLISHER".to_string()),
        preparer_id: Some("MY PREPARER".to_string()),
        application_id: None,
        sector_size: 2048,
        path_separator: PathSeparator::ForwardSlash,
        features: CreationFeatures::with_joliet(hadris_iso::joliet::JolietLevel::Level3),
        strict_charset: false,
    };
    let mut buffer = Cursor::new(vec![0u8; 4 * 1024 * 1024]);
    IsoImageWriter::format_new(&mut buffer, input, options).unwrap();
    let iso_data = buffer.into_inner();

    let svd_offset = 17 * 2048;
    assert_eq!(iso_data[svd_offset], 0x02, "Sector 17 should be SVD");

    // Application identifier at offset 574, 128 bytes
    // Default "HADRIS-ISO" should be UTF-16BE encoded
    let app_id = &iso_data[svd_offset + 574..svd_offset + 574 + 128];
    // 'H' in UTF-16BE = 0x00 0x48
    assert_eq!(
        app_id[0..2],
        [0x00, b'H'],
        "App id first char should be UTF-16BE 'H'"
    );
    assert_eq!(
        app_id[2..4],
        [0x00, b'A'],
        "App id second char should be UTF-16BE 'A'"
    );

    // Publisher identifier at offset 318, 128 bytes
    let pub_id = &iso_data[svd_offset + 318..svd_offset + 318 + 128];
    // "MY PUBLISHER" in UTF-16BE
    assert_eq!(pub_id[0..2], [0x00, b'M'], "Publisher first char");
    assert_eq!(pub_id[2..4], [0x00, b'Y'], "Publisher second char");
    assert_eq!(pub_id[4..6], [0x00, b' '], "Publisher third char (space)");
    assert_eq!(pub_id[6..8], [0x00, b'P'], "Publisher fourth char");

    // Preparer identifier at offset 446, 128 bytes
    let prep_id = &iso_data[svd_offset + 446..svd_offset + 446 + 128];
    assert_eq!(prep_id[0..2], [0x00, b'M'], "Preparer first char");
    assert_eq!(prep_id[2..4], [0x00, b'Y'], "Preparer second char");

    // Empty fields should be UTF-16BE spaces (0x00, 0x20), not ASCII spaces (0x20)
    // System identifier at offset 8, 32 bytes
    let sys_id = &iso_data[svd_offset + 8..svd_offset + 8 + 32];
    assert_eq!(
        sys_id[0..2],
        [0x00, 0x20],
        "Empty system id should be UTF-16BE space"
    );
    assert_eq!(
        sys_id[2..4],
        [0x00, 0x20],
        "Empty system id second pair should be UTF-16BE space"
    );
}

#[test]
fn test_pvd_strings_with_spaces() {
    let files = vec![IsoFile::File {
        name: Arc::new("test.txt".to_string()),
        contents: b"test".to_vec(),
    }];

    let input = InputFiles {
        path_separator: PathSeparator::ForwardSlash,
        files,
    };
    let options = FormatOptions {
        volume_name: "TEST".to_string(),
        system_id: None,
        volume_set_id: None,
        publisher_id: Some("EXAMPLE PUBLISHER".to_string()),
        preparer_id: Some("EXAMPLE PREPARER".to_string()),
        application_id: None,
        sector_size: 2048,
        path_separator: PathSeparator::ForwardSlash,
        features: CreationFeatures::default(),
        strict_charset: false,
    };
    let mut buffer = Cursor::new(vec![0u8; 4 * 1024 * 1024]);
    IsoImageWriter::format_new(&mut buffer, input, options).unwrap();
    let iso_data = buffer.into_inner();

    // Open the ISO and read the PVD
    let image = hadris_iso::read::IsoImage::open(Cursor::new(iso_data)).unwrap();
    let pvd = image.read_pvd();

    // Verify strings with spaces are not truncated (Issue #8)
    assert_eq!(pvd.publisher_identifier.to_str(), "EXAMPLE PUBLISHER");
    assert_eq!(pvd.preparer_identifier.to_str(), "EXAMPLE PREPARER");
}

// =============================================================================
// TF Timestamp Parsing Tests (unit-level)
// =============================================================================

#[test]
fn test_tf_short_form_timestamps() {
    use hadris_iso::read::RripMetadata;
    use hadris_iso::rrip::{TfEntry, TfFlags};
    use hadris_iso::susp::SystemUseField;

    // TF with MODIFY(0x02) + ACCESS(0x04) flags, short form
    let mut timestamps = Vec::new();
    // Modify: 2026-02-17 10:30:00 UTC
    timestamps.extend_from_slice(&[126, 2, 17, 10, 30, 0, 0]);
    // Access: 2026-02-17 12:00:00 UTC
    timestamps.extend_from_slice(&[126, 2, 17, 12, 0, 0, 0]);

    let fields = vec![SystemUseField::Timestamps(TfEntry {
        flags: TfFlags::MODIFY | TfFlags::ACCESS,
        timestamps,
    })];
    let meta = RripMetadata::from_fields(&fields);

    let ts = meta.timestamps.expect("should have timestamps");
    assert!(ts.creation.is_none(), "creation should not be present");

    let modify = ts.modify.expect("modify should be present");
    assert_eq!(modify.year, 2026);
    assert_eq!(modify.month, 2);
    assert_eq!(modify.day, 17);
    assert_eq!(modify.hour, 10);
    assert_eq!(modify.minute, 30);

    let access = ts.access.expect("access should be present");
    assert_eq!(access.year, 2026);
    assert_eq!(access.month, 2);
    assert_eq!(access.day, 17);
    assert_eq!(access.hour, 12);
    assert_eq!(access.minute, 0);
}

#[test]
fn test_tf_long_form_timestamps() {
    use hadris_iso::read::RripMetadata;
    use hadris_iso::rrip::{TfEntry, TfFlags};
    use hadris_iso::susp::SystemUseField;

    // TF with CREATION flag, long form
    let mut timestamps = Vec::new();
    // Creation: "2026021710300000" + gmt_offset=0
    timestamps.extend_from_slice(b"2026021710300000");
    timestamps.push(0); // gmt_offset

    let fields = vec![SystemUseField::Timestamps(TfEntry {
        flags: TfFlags::CREATION | TfFlags::LONG_FORM,
        timestamps,
    })];
    let meta = RripMetadata::from_fields(&fields);

    let ts = meta.timestamps.expect("should have timestamps");
    let creation = ts.creation.expect("creation should be present");
    assert_eq!(creation.year, 2026);
    assert_eq!(creation.month, 2);
    assert_eq!(creation.day, 17);
    assert_eq!(creation.hour, 10);
    assert_eq!(creation.minute, 30);
}