hadris-iso 2.5.0

Pure Rust ISO 9660 library with allocation-free reading, Joliet, Rock Ridge, and El Torito
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
#[cfg(feature = "unstable-streaming")]
use alloc::boxed::Box;
use core::{fmt, ops::Deref};
use std::{fs::FileType, path::PathBuf};

use alloc::{
    collections::{BTreeMap, BTreeSet, VecDeque},
    string::{String, ToString},
    sync::Arc,
    vec::Vec,
};

use super::FileConversionError;
use crate::{
    directory::{DirectoryRef, FileFlags},
    file::{ConvertedName, EntryType},
    io::{self},
    read::PathSeparator,
    rrip::RripOptions,
    susp::SplitSu,
    write::{utils::*, writer::*},
};

/// Represents a file in the write order: (directory ID, file index).
pub type FileOrder = (DirectoryId, usize);

/// Maps (directory ID, entry type) to directory reference for relocation.
pub type RelocationMap = BTreeMap<(usize, EntryType), DirectoryRef>;

/// RRIP timestamp (7 bytes: year, month, day, hour, minute, second, offset).
pub type RripTime = [u8; 7];

/// A compact input tree for callers that do not need per-entry metadata.
///
/// [`InputTree`] is the richer model for Rock Ridge metadata and host
/// filesystem imports. Both models are accepted by
/// [`IsoImageWriter::create`](crate::write::IsoImageWriter::create).
pub struct InputFiles {
    /// Separator used by paths referenced from writer options.
    pub path_separator: PathSeparator,
    /// Root-level files and directories.
    pub files: Vec<File>,
}

#[derive(Clone, PartialEq, Eq)]
/// A file or directory in the compact [`InputFiles`] model.
pub enum File {
    /// The `File` variant.
    File {
        /// The `name` field.
        name: Arc<String>,
        /// The `contents` field.
        contents: Vec<u8>,
    },
    /// The `Directory` variant.
    Directory {
        /// The `name` field.
        name: Arc<String>,
        /// The `children` field.
        children: Vec<File>,
    },
}

impl core::fmt::Debug for File {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut dbg = f.debug_struct("File");
        match self {
            Self::Directory { name, children } => {
                dbg.field("name", name);
                dbg.field("children", children);
            }
            Self::File { name, contents } => {
                dbg.field("name", name);
                dbg.field("data_len", &contents.len());
            }
        }
        dbg.finish()
    }
}

impl File {
    /// Performs the `name` operation.
    pub fn name(&self) -> Arc<String> {
        match self {
            File::File { name, .. } => name.clone(),
            File::Directory { name, .. } => name.clone(),
        }
    }
}

/// A metadata-aware tree used to create an ISO image.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InputTree {
    /// The `path_separator` field.
    pub path_separator: PathSeparator,
    /// The `entries` field.
    pub entries: Vec<InputEntry>,
}

impl InputTree {
    /// Recursive validation.
    ///
    /// Checks:
    /// - Depth: max 8 directories (unless RRIP deep dirs enabled)
    /// - Path length: max 255 bytes (unless RRIP deep dirs enabled)
    /// - Symlinks: require RRIP preserve_symlinks
    /// - Devices: require RRIP preserve_devices
    /// - File size: max 4 GiB
    pub(crate) fn validate(&self, rrip: Option<&RripOptions>) -> crate::io::Result<()> {
        Self::visit(&self.entries, rrip, 1, 0)
    }

    fn visit(
        entries: &[InputEntry],
        rrip: Option<&RripOptions>,
        depth: usize,
        path_len: usize,
    ) -> io::Result<()> {
        for entry in entries {
            match &entry.kind {
                InputEntryKind::Directory(children) => {
                    let child_path_len = if path_len == 0 {
                        entry.name.len()
                    } else {
                        path_len + 1 + entry.name.len()
                    };
                    if (depth >= 8 || child_path_len > 255)
                        && !rrip
                            .is_some_and(|options| options.enabled && options.relocate_deep_dirs)
                    {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            "directory depth or path length exceeds ISO 9660 limits and RRIP relocation is disabled",
                        ));
                    }

                    Self::visit(children, rrip, depth + 1, child_path_len)?;
                }
                InputEntryKind::Symlink(_) => {
                    if !rrip.is_some_and(|options| options.enabled && options.preserve_symlinks) {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            "symbolic links require RRIP preserve_symlinks",
                        ));
                    }
                }
                InputEntryKind::CharacterDevice { .. } | InputEntryKind::BlockDevice { .. } => {
                    if !rrip.is_some_and(|options| options.enabled && options.preserve_devices) {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            "device entries require RRIP preserve_devices",
                        ));
                    }
                }
                InputEntryKind::File(_contents) => {
                    // if contents.len() as u64 > Self::MAX_SINGLE_EXTENT_FILE_LEN {
                    //     return Err(io::Error::new(
                    //         io::ErrorKind::InvalidInput,
                    //         "file exceeds 4 GiB; the ISO writer stores each file in a single \
                    //         extent and cannot yet emit multi-extent records",
                    //     ));
                    // }
                }
                #[cfg(feature = "unstable-streaming")]
                InputEntryKind::Source(_) => {}
                #[cfg(test)]
                InputEntryKind::TestFile { .. } => {}
            }
        }
        Ok(())
    }
}

/// Optional POSIX metadata for an input entry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct InputMetadata {
    /// The `mode` field.
    pub mode: Option<u32>,
    /// The `uid` field.
    pub uid: Option<u32>,
    /// The `gid` field.
    pub gid: Option<u32>,
    /// Creation time as seconds since the Unix epoch.
    pub created: Option<i64>,
    /// Modification time as seconds since the Unix epoch.
    pub modified: Option<i64>,
    /// Access time as seconds since the Unix epoch.
    pub accessed: Option<i64>,
}

impl InputMetadata {
    /// Creates metadata from filesystem metadata.
    pub(crate) fn from_fs(fs_metadata: std::fs::Metadata) -> Self {
        #[allow(unused_mut)]
        let mut metadata = Self {
            created: system_time_seconds(fs_metadata.created()),
            modified: system_time_seconds(fs_metadata.modified()),
            accessed: system_time_seconds(fs_metadata.accessed()),
            ..Self::default()
        };

        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            metadata.mode = Some(fs_metadata.mode() & 0o7777);
            metadata.uid = Some(fs_metadata.uid());
            metadata.gid = Some(fs_metadata.gid());
        }

        metadata
    }
}

/// File contents that are read from a reader while the image is written.
///
/// An [`InputEntryKind::File`] holds its contents in memory. A `FileSource` holds
/// only the length and a way to open a reader, so a large file is streamed into the
/// image in fixed-size chunks and never has to fit in memory. The writer opens the
/// reader once per file, in image order, and reads exactly `len` bytes from it: a
/// reader that ends early fails the write with [`ErrorKind::UnexpectedEof`], and
/// bytes beyond `len` are never read.
///
/// The reader is a blocking [`std::io::Read`] in both the sync and the async writer;
/// the async writer awaits only its output.
///
/// Requires the `unstable-streaming` feature, which is outside the V2 API
/// stability promise: this type and [`InputEntryKind::Source`] may change in any
/// release.
///
/// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
#[cfg(feature = "unstable-streaming")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-streaming")))]
#[derive(Clone)]
pub struct FileSource {
    len: u64,
    open:
        alloc::sync::Arc<dyn Fn() -> std::io::Result<Box<dyn std::io::Read + Send>> + Send + Sync>,
}

#[cfg(feature = "unstable-streaming")]
impl FileSource {
    /// A source of `len` bytes that `open` produces a reader for.
    pub fn new<F>(len: u64, open: F) -> Self
    where
        F: Fn() -> std::io::Result<Box<dyn std::io::Read + Send>> + Send + Sync + 'static,
    {
        Self {
            len,
            open: alloc::sync::Arc::new(open),
        }
    }

    /// A source that streams the file at `path`, whose length is taken now.
    ///
    /// The file is opened when the image is written; its length must not change
    /// in between.
    ///
    /// ```
    /// # #[cfg(feature = "unstable-streaming")] {
    /// use hadris_iso::write::FileSource;
    ///
    /// let path = std::env::temp_dir().join("hadris-iso-file-source-doc.bin");
    /// std::fs::write(&path, b"streamed")?;
    /// let source = FileSource::from_path(&path)?;
    /// assert_eq!(source.len(), 8);
    /// let mut contents = Vec::new();
    /// source.open()?.read_to_end(&mut contents)?;
    /// assert_eq!(contents, b"streamed");
    /// # std::fs::remove_file(&path)?;
    /// # }
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn from_path(path: impl Into<PathBuf>) -> std::io::Result<Self> {
        let path = path.into();
        let len = std::fs::metadata(&path)?.len();
        Ok(Self::new(len, move || {
            std::fs::File::open(&path).map(|file| Box::new(file) as Box<dyn std::io::Read + Send>)
        }))
    }

    /// The number of bytes the source provides.
    pub const fn len(&self) -> u64 {
        self.len
    }

    /// Whether the source provides no bytes.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Opens a fresh reader positioned at the start of the contents.
    pub fn open(&self) -> std::io::Result<Box<dyn std::io::Read + Send>> {
        (self.open)()
    }
}

#[cfg(feature = "unstable-streaming")]
impl fmt::Debug for FileSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FileSource")
            .field("len", &self.len)
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "unstable-streaming")]
impl PartialEq for FileSource {
    /// Two sources are equal when they share the same opener and length.
    fn eq(&self, other: &Self) -> bool {
        self.len == other.len && alloc::sync::Arc::ptr_eq(&self.open, &other.open)
    }
}

#[cfg(feature = "unstable-streaming")]
impl Eq for FileSource {}

/// The data represented by an [`InputEntry`].
///
/// With the `unstable-streaming` feature enabled this enum gains the
/// `Source` variant, so exhaustive matches on it must account for
/// that variant when the feature is on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputEntryKind {
    /// The `File` variant.
    File(Vec<u8>),
    /// A file whose contents are streamed from a reader while the image is written.
    ///
    /// Requires the `unstable-streaming` feature and is outside the V2 API
    /// stability promise.
    #[cfg(feature = "unstable-streaming")]
    #[cfg_attr(docsrs, doc(cfg(feature = "unstable-streaming")))]
    Source(FileSource),
    /// A virtual sparse file used by large-file regression tests.
    #[cfg(test)]
    TestFile {
        /// Virtual file size in bytes.
        size: u64,
    },
    /// The `Directory` variant.
    Directory(Vec<InputEntry>),
    /// The `Symlink` variant.
    Symlink(String),
    /// A POSIX character device.
    CharacterDevice {
        /// Device-class identifier.
        major: u32,
        /// Device identifier within the class.
        minor: u32,
    },
    /// A POSIX block device.
    BlockDevice {
        /// Device-class identifier.
        major: u32,
        /// Device identifier within the class.
        minor: u32,
    },
}

impl InputEntryKind {
    pub(crate) fn file_len(&self) -> Option<u64> {
        match self {
            Self::File(contents) => Some(contents.len() as u64),
            #[cfg(feature = "unstable-streaming")]
            Self::Source(source) => Some(source.len()),
            #[cfg(test)]
            Self::TestFile { size } => Some(*size),
            _ => None,
        }
    }

    /// Creates an `InputEntryKind` from a filesystem file type and path.
    ///
    /// This function inspects the file type and constructs the appropriate variant:
    /// - Regular files → `File` (contents are read into memory).
    /// - Directories → `Directory` (recursively reads all children).
    /// - Symlinks → `Symlink` (reads the link target as a string).
    /// - Character/block devices → `CharacterDevice` or `BlockDevice` (Unix only).
    pub(crate) fn new(
        file_type: FileType,
        path: PathBuf,
    ) -> core::result::Result<Self, FileConversionError> {
        if file_type.is_file() {
            let content = std::fs::read(&path)?;
            Ok(InputEntryKind::File(content))
        } else if file_type.is_dir() {
            let dir = read_input_directory_recursively(&path)?;
            Ok(InputEntryKind::Directory(dir))
        } else if file_type.is_symlink() {
            let target = std::fs::read_link(&path)?;
            let symlink = target
                .to_str()
                .ok_or_else(|| FileConversionError::InvalidUtf8Path(target.clone()))?
                .to_string();
            Ok(InputEntryKind::Symlink(symlink))
        } else {
            #[cfg(unix)]
            {
                use std::os::unix::fs::{FileTypeExt, MetadataExt};
                const DEV_MAJOR_MASK_LOW: u64 = 0xfff;
                const DEV_MAJOR_MASK_HIGH: u64 = 0xfffff000;
                const DEV_MINOR_MASK_LOW: u64 = 0xff;
                const DEV_MINOR_MASK_HIGH: u64 = 0xffffff00;

                let fs_metadata = std::fs::symlink_metadata(&path)?;
                let device = fs_metadata.rdev();
                let major =
                    ((device >> 8) & DEV_MAJOR_MASK_LOW) | ((device >> 32) & DEV_MAJOR_MASK_HIGH);
                let minor = (device & DEV_MINOR_MASK_LOW) | ((device >> 12) & DEV_MINOR_MASK_HIGH);
                if file_type.is_char_device() {
                    Ok(InputEntryKind::CharacterDevice {
                        major: major as u32,
                        minor: minor as u32,
                    })
                } else if file_type.is_block_device() {
                    Ok(InputEntryKind::BlockDevice {
                        major: major as u32,
                        minor: minor as u32,
                    })
                } else {
                    Err(FileConversionError::UnsupportedFileType(path))
                }
            }
            #[cfg(not(unix))]
            return Err(FileConversionError::UnsupportedFileType(path));
        }
    }
}

/// A named entry in the input tree, representing a file, directory, symlink, or device.
///
/// This struct is the building block of [`InputTree`]. Each entry has a name,
/// a kind (file, directory, symlink, or device), and optional POSIX metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InputEntry {
    /// The name of the entry (e.g., `"README.txt"` or `"src"`).
    pub name: Arc<String>,
    /// The kind of entry (file, directory, symlink, or device).
    pub kind: InputEntryKind,
    /// Optional POSIX metadata (permissions, ownership, timestamps).
    pub metadata: InputMetadata,
}

impl InputEntry {
    /// Creates a regular file entry with content.
    pub fn file(name: impl Into<String>, contents: impl Into<Vec<u8>>) -> Self {
        Self::new(name, InputEntryKind::File(contents.into()))
    }

    /// Creates a directory entry with children.
    pub fn directory(name: impl Into<String>, children: Vec<Self>) -> Self {
        Self::new(name, InputEntryKind::Directory(children))
    }

    /// Creates a symbolic link entry.
    pub fn symlink(name: impl Into<String>, target: impl Into<String>) -> Self {
        Self::new(name, InputEntryKind::Symlink(target.into()))
    }

    /// Creates a character device entry (Unix only).
    pub fn character_device(name: impl Into<String>, major: u32, minor: u32) -> Self {
        Self::new(name, InputEntryKind::CharacterDevice { major, minor })
    }

    /// Creates a block device entry (Unix only).
    pub fn block_device(name: impl Into<String>, major: u32, minor: u32) -> Self {
        Self::new(name, InputEntryKind::BlockDevice { major, minor })
    }

    /// Sets the metadata for this entry.
    pub fn with_metadata(mut self, metadata: InputMetadata) -> Self {
        self.metadata = metadata;
        self
    }

    /// Returns the name of the entry.
    pub fn name(&self) -> Arc<String> {
        self.name.clone()
    }

    fn new(name: impl Into<String>, kind: InputEntryKind) -> Self {
        Self {
            name: Arc::new(name.into()),
            kind,
            metadata: InputMetadata::default(),
        }
    }
}

impl InputTree {
    /// Performs the `new` operation.
    pub fn new(path_separator: PathSeparator, entries: Vec<InputEntry>) -> Self {
        Self {
            path_separator,
            entries,
        }
    }

    /// Performs the `from_fs` operation.
    pub fn from_fs(
        root_path: &std::path::Path,
        path_separator: PathSeparator,
    ) -> core::result::Result<Self, FileConversionError> {
        if !root_path.is_dir() {
            return Err(FileConversionError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                alloc::format!("Root path '{root_path:?}' is not a directory"),
            )));
        }
        Ok(Self::new(
            path_separator,
            read_input_directory_recursively(root_path)?,
        ))
    }
}

impl From<InputFiles> for InputTree {
    fn from(value: InputFiles) -> Self {
        fn convert(file: File) -> InputEntry {
            match file {
                File::File { name, contents } => InputEntry {
                    name,
                    kind: InputEntryKind::File(contents),
                    metadata: InputMetadata::default(),
                },
                File::Directory { name, children } => InputEntry {
                    name,
                    kind: InputEntryKind::Directory(children.into_iter().map(convert).collect()),
                    metadata: InputMetadata::default(),
                },
            }
        }
        Self::new(
            value.path_separator,
            value.files.into_iter().map(convert).collect(),
        )
    }
}

/// Depth-first tree walker.
pub struct FileTreeWalker<'a>(VecDeque<StackFrame<'a>>);

/// Walker internal state.
enum StackFrame<'a> {
    Node(&'a InputEntry),
    DirExit(&'a InputEntry),
}

/// Walker events.
#[derive(Debug, PartialEq, Eq)]
pub enum TreeWalkerItem<'a> {
    /// Entering a directory.
    EnterDirectory(&'a InputEntry),
    /// A file.
    File(&'a InputEntry),
    /// Exiting a directory.
    ExitDirectory(&'a InputEntry),
}

impl<'a> FileTreeWalker<'a> {
    /// New walker.
    pub fn new(input: &'a InputTree) -> Self {
        let mut stack = VecDeque::new();
        for file in input.entries.iter().rev() {
            stack.push_back(StackFrame::Node(file));
        }
        FileTreeWalker(stack)
    }

    /// Walk the tree and build WrittenFiles.
    pub fn walk(self, written_files: &mut WrittenFiles) {
        let mut next_directory_id = 1usize;
        let mut current_dir = written_files.root_dir();

        for file in self {
            match file {
                TreeWalkerItem::EnterDirectory(dir) => {
                    let name = dir.name();
                    let metadata = dir.metadata;
                    let written_dir = written_files.get_mut(&current_dir);
                    let index = written_dir.push_dir(name, metadata);
                    written_dir.dirs[index].id = next_directory_id;
                    next_directory_id += 1;
                    current_dir.push(index);
                }
                TreeWalkerItem::ExitDirectory(_dir) => {
                    current_dir.pop();
                }
                TreeWalkerItem::File(file) => {
                    // Extents are assigned in the planning pass below.
                    // Empty files keep extent 0 (per ISO 9660 they have no
                    // data to reference).
                    let dir = written_files.get_mut(&current_dir);
                    dir.push_file(WrittenFile::new(
                        file.name.clone(),
                        file.kind.clone(),
                        file.metadata,
                    ));
                }
            };
        }
    }
}

impl<'a> Iterator for FileTreeWalker<'a> {
    type Item = TreeWalkerItem<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let frame = self.0.pop_back()?;
        match frame {
            StackFrame::Node(file) => match &file.kind {
                InputEntryKind::Directory(children) => {
                    // Yield that we are entering this directory (pre-order event)
                    let current_dir = file;

                    // Push an Exit frame to signal leaving this directory later
                    self.0.push_back(StackFrame::DirExit(current_dir));

                    // Push children in reverse order for DFS
                    for child in children.iter().rev() {
                        self.0.push_back(StackFrame::Node(child));
                    }

                    Some(TreeWalkerItem::EnterDirectory(current_dir))
                }
                _ => Some(TreeWalkerItem::File(file)),
            },
            StackFrame::DirExit(dir) => Some(TreeWalkerItem::ExitDirectory(dir)),
        }
    }
}

/// Selects which RRIP fields to emit for a directory entry.
pub enum RripEntryKind<'a> {
    /// Root "." entry: SP + ER + PX + NM(CURRENT)
    RootDot {
        /// File metadata.
        metadata: InputMetadata,
        /// Number of hard links.
        nlink: u32,
    },
    /// Root ".." entry: PX + NM(PARENT)
    RootDotDot {
        /// File metadata.
        metadata: InputMetadata,
        /// Number of hard links.
        nlink: u32,
    },
    /// Non-root "." entry: PX + NM(CURRENT)
    Dot {
        /// File metadata.
        metadata: InputMetadata,
        /// Number of hard links.
        nlink: u32,
    },
    /// Non-root ".." entry: PX + NM(PARENT)
    DotDot {
        /// File metadata.
        metadata: InputMetadata,
        /// Number of hard links.
        nlink: u32,
    },
    /// Named directory entry.
    Directory {
        /// Original filename.
        original_name: &'a str,
        /// File metadata.
        metadata: InputMetadata,
        /// Number of hard links.
        nlink: u32,
    },
    /// Named file entry.
    Entry {
        /// Original filename.
        original_name: &'a str,
        /// File metadata.
        metadata: InputMetadata,
        /// File contents.
        kind: &'a InputEntryKind,
    },
}

/// Pending directory records ready for layout planning and writing.
///
/// # Overview
/// These records represent a single directory's contents, including:
/// - "." and ".." entries
/// - Child directories
/// - Files (including multi-extent files)
///
/// # RRIP System Use
/// Each record can have inline System Use data (RRIP extensions).
/// If the data exceeds the available inline space, overflow is tracked
/// and written to a separate continuation area.
///
/// # Multi-Extent Files
/// Files larger than 4 GiB are split into multiple extents.
/// Each extent gets its own directory record with the same name.
/// The first record contains the RRIP data; subsequent extents
/// have empty System Use.
///
/// # Processing Phases
/// 1. Build all records with RRIP entries split against inline space
/// 2. If any record has overflow: allocate continuation area, patch CE entries
/// 3. Write directory records with inline SU bytes
///
/// # Ordering
/// Records are ordered by File Identifier (ECMA-119 9.3):
/// - "." (0x00) first
/// - ".." (0x01) second
/// - All other entries sorted by name
pub struct PendingRecords(Vec<PendingRecord>);

impl PendingRecords {
    /// Build the pending records for one directory: dot/dotdot, child
    /// directories, and files, with RRIP system-use areas split against the
    /// inline budget, names deduplicated, and records ordered by File
    /// Identifier (ECMA-119 9.3). Sizes never depend on extent values, so
    /// the planning pass calls this with placeholder refs and the write pass
    /// rebuilds with the real ones.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        ty: EntryType,
        dir: &WrittenDirectory,
        is_root: bool,
        inode_counter: &mut u32,
        rrip_options: Option<&RripOptions>,
        fallback_time: &RripTime,
        relocation_refs: &BTreeMap<(usize, EntryType), DirectoryRef>,
        sector_size: u64,
    ) -> io::Result<Self> {
        let rrip_options = rrip_options.filter(|options| options.enabled);
        let has_rrip = ty.supports_rrip() && rrip_options.is_some();
        let options = rrip_options.copied().unwrap_or_else(RripOptions::disabled);
        let directory_nlink = 2 + dir.dirs.len() as u32;

        let mut records: Vec<PendingRecord> = Vec::new();

        records.push(Self::build_dot_record(
            has_rrip,
            is_root,
            &dir.metadata,
            directory_nlink,
            &options,
            fallback_time,
        ));
        records.push(Self::build_dotdot_record(
            has_rrip,
            is_root,
            dir,
            ty,
            &options,
            fallback_time,
            relocation_refs,
        )?);

        Self::build_directory_records(
            &mut records,
            &dir.dirs,
            ty,
            has_rrip,
            &options,
            inode_counter,
            fallback_time,
            relocation_refs,
        )?;

        Self::build_file_records(
            &mut records,
            &dir.files,
            ty,
            has_rrip,
            &options,
            inode_counter,
            fallback_time,
            sector_size,
        )?;

        Self::deduplicate_names(&mut records, ty);
        Self::sort_records(&mut records);

        Ok(Self(records))
    }

    fn build_dot_record(
        has_rrip: bool,
        is_root: bool,
        metadata: &InputMetadata,
        nlink: u32,
        options: &RripOptions,
        fallback_time: &RripTime,
    ) -> PendingRecord {
        let split = if has_rrip {
            let kind = if is_root {
                RripEntryKind::RootDot {
                    metadata: *metadata,
                    nlink,
                }
            } else {
                RripEntryKind::Dot {
                    metadata: *metadata,
                    nlink,
                }
            };
            let max = available_su_space(1); // name is b"\x00"
            build_rrip_entries(kind, 0, options, fallback_time).build_split(max)
        } else {
            SplitSu::empty()
        };
        PendingRecord::current_dir(split)
    }

    fn build_dotdot_record(
        has_rrip: bool,
        is_root: bool,
        dir: &WrittenDirectory,
        ty: EntryType,
        options: &RripOptions,
        fallback_time: &RripTime,
        relocation_refs: &BTreeMap<(usize, EntryType), DirectoryRef>,
    ) -> io::Result<PendingRecord> {
        let split = if has_rrip {
            let kind = if is_root {
                RripEntryKind::RootDotDot {
                    metadata: dir.metadata,
                    nlink: 2 + dir.dirs.len() as u32,
                }
            } else {
                RripEntryKind::DotDot {
                    metadata: dir.metadata,
                    nlink: 2 + dir.dirs.len() as u32,
                }
            };
            let max = available_su_space(1); // name is b"\x01"
            let mut builder = build_rrip_entries(kind, 0, options, fallback_time);
            if let DirectoryRelocation::Moved { logical_parent, .. } = dir.relocation {
                let parent = relocation_refs
                    .get(&(logical_parent, ty))
                    .copied()
                    .unwrap_or_default();
                builder.add_pl(parent.extent.0 as u32);
            }
            builder.build_split(max)
        } else {
            SplitSu::empty()
        };
        Ok(PendingRecord::parent_dir(split))
    }

    #[allow(clippy::too_many_arguments)]
    fn build_directory_records(
        records: &mut Vec<PendingRecord>,
        dirs: &[WrittenDirectory],
        ty: EntryType,
        has_rrip: bool,
        options: &RripOptions,
        inode_counter: &mut u32,
        fallback_time: &RripTime,
        relocation_refs: &BTreeMap<(usize, EntryType), DirectoryRef>,
    ) -> io::Result<()> {
        for directory in dirs {
            let converted_name = ty.convert_directory_name(&directory.name);
            let split = if has_rrip {
                let inode = *inode_counter;
                *inode_counter += 1;
                let max = available_su_space(converted_name.as_bytes().len());
                let mut builder = build_rrip_entries(
                    RripEntryKind::Directory {
                        original_name: &directory.rrip_name,
                        metadata: directory.metadata,
                        nlink: 2 + directory.dirs.len() as u32,
                    },
                    inode,
                    options,
                    fallback_time,
                );
                match directory.relocation {
                    DirectoryRelocation::Placeholder { target } => {
                        let target = relocation_refs.get(&(target, ty)).ok_or_else(|| {
                            io::Error::new(
                                io::ErrorKind::InvalidData,
                                "relocated directory extent was not written",
                            )
                        })?;
                        builder.add_cl(target.extent.0 as u32);
                    }
                    DirectoryRelocation::Moved { .. } => {
                        builder.add_re();
                    }
                    DirectoryRelocation::None => {}
                }
                builder.build_split(max)
            } else {
                SplitSu::empty()
            };

            let dir_ref = directory.get_dir_ref(ty, relocation_refs);
            let flags = if has_rrip
                && matches!(
                    directory.relocation,
                    DirectoryRelocation::Placeholder { .. }
                ) {
                FileFlags::empty()
            } else {
                FileFlags::DIRECTORY
            };
            let record = PendingRecord::new(&converted_name, split, dir_ref, flags);

            records.push(record);
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn build_file_records(
        records: &mut Vec<PendingRecord>,
        files: &[WrittenFile],
        ty: EntryType,
        has_rrip: bool,
        options: &RripOptions,
        inode_counter: &mut u32,
        fallback_time: &RripTime,
        sector_size: u64,
    ) -> io::Result<()> {
        for file in files {
            let converted_name = ty.convert_name(&file.name);

            // Main file entry (with RRIP if enabled)
            let split = if has_rrip {
                let inode = *inode_counter;
                *inode_counter += 1;
                let max = available_su_space(converted_name.as_bytes().len());
                let kind = RripEntryKind::Entry {
                    original_name: &file.name,
                    metadata: file.metadata,
                    kind: &file.kind,
                };
                build_rrip_entries(kind, inode, options, fallback_time).build_split(max)
            } else {
                SplitSu::empty()
            };

            let len = file.kind.file_len().unwrap_or(file.entry.size as u64);
            let cursor = file.entry.extent.0 as u64 * sector_size;
            let mut additional_extents =
                ExtentIter::new(len, cursor, sector_size).skip(1).peekable();
            let first_flags = if additional_extents.peek().is_none() {
                FileFlags::empty()
            } else {
                FileFlags::NOT_FINAL
            };

            let first = PendingRecord::new(&converted_name, split, file.entry, first_flags);
            records.push(first);

            while let Some((dir_ref, _)) = additional_extents.next() {
                let flags = if additional_extents.peek().is_none() {
                    FileFlags::empty()
                } else {
                    FileFlags::NOT_FINAL
                };

                let record = PendingRecord::new(&converted_name, SplitSu::empty(), dir_ref, flags);
                records.push(record);
            }
        }
        Ok(())
    }

    fn deduplicate_names(records: &mut [PendingRecord], ty: EntryType) {
        let mut seen: BTreeSet<PendingRecordName> = BTreeSet::new();
        let mut start = 0;

        while start < records.len() {
            if records[start].name.len() == 1
                && (records[start].name[0] == 0x00 || records[start].name[0] == 0x01)
            {
                start += 1;
                continue;
            }

            let mut end = start + 1;
            while end < records.len() && records[end - 1].flags.contains(FileFlags::NOT_FINAL) {
                end += 1;
            }

            let original_name = records[start].name.clone();
            let unique_name = if seen.contains(&original_name) {
                let mut suffix = 1;
                loop {
                    let candidate = apply_dedup_suffix(&original_name, suffix, ty).into();
                    suffix += 1;
                    if !seen.contains(&candidate) {
                        break candidate;
                    }
                }
            } else {
                original_name.clone()
            };

            seen.insert(unique_name.clone());

            for record in &mut records[start..end] {
                record.name = unique_name.clone();
            }

            start = end;
        }
    }

    fn sort_records(records: &mut [PendingRecord]) {
        records.sort_by(|a, b| {
            let rank = |name: &[u8]| match name {
                [0x00] => 0,
                [0x01] => 1,
                _ => 2,
            };
            rank(&a.name)
                .cmp(&rank(&b.name))
                .then_with(|| a.name.cmp(&b.name))
        });
    }

    /// Total length of all overflow (continuation area) data.
    pub fn overflow_len(&self) -> u64 {
        self.0
            .iter()
            .filter(|r| r.split.has_overflow())
            .map(|r| r.split.overflow.len() as u64)
            .sum()
    }

    /// Returns true if any record has RRIP overflow (needs continuation area).
    pub fn has_overflow(&self) -> bool {
        self.0.iter().any(|r| r.split.has_overflow())
    }

    /// Iterates over pending records.
    pub fn iter(&self) -> impl Iterator<Item = &PendingRecord> {
        self.0.iter()
    }

    /// Mutably iterates over pending records.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut PendingRecord> {
        self.0.iter_mut()
    }
}

/// A reference-counted, cloneable name for a pending directory record.
///
/// This type wraps an `Arc<[u8]>`, allowing efficient sharing of the name
/// across multiple records (e.g., multi-extent files where all extents share
/// the same name). It is cheap to clone and can be compared and hashed.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PendingRecordName(Arc<[u8]>);

impl From<Vec<u8>> for PendingRecordName {
    fn from(value: Vec<u8>) -> Self {
        Self(value.into())
    }
}

impl Deref for PendingRecordName {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// A pending directory record, built in phase 1 and written in phases 2-3.
#[derive(Debug, Clone)]
pub struct PendingRecord {
    /// File or directory name.
    pub name: PendingRecordName,
    /// System Use data (split into inline and overflow).
    pub split: SplitSu,
    /// Location and size of the file/dir.
    pub dir_ref: DirectoryRef,
    /// File flags (directory, hidden, etc.).
    pub flags: FileFlags,
}

impl PendingRecord {
    /// Creates a new pending directory record.
    pub fn new(
        name: &ConvertedName,
        split: SplitSu,
        dir_ref: DirectoryRef,
        flags: FileFlags,
    ) -> Self {
        Self {
            name: PendingRecordName(name.as_bytes().into()),
            split,
            dir_ref,
            flags,
        }
    }

    /// Current directory "." entry.
    pub fn current_dir(dot_split: SplitSu) -> Self {
        Self {
            name: PendingRecordName([0x00].into()),
            split: dot_split,
            dir_ref: DirectoryRef::default(),
            flags: FileFlags::DIRECTORY,
        }
    }

    /// Parent directory ".." entry.
    pub fn parent_dir(dotdot_split: SplitSu) -> Self {
        Self {
            name: PendingRecordName([0x01].into()),
            split: dotdot_split,
            dir_ref: DirectoryRef::default(),
            flags: FileFlags::DIRECTORY,
        }
    }
}

/// An iterator that splits a file into ISO 9660 extents.
pub struct ExtentIter {
    remaining: u64,
    cursor: u64,
    sector_size: u64,
}

impl ExtentIter {
    /// Creates a new extent iterator.
    pub fn new(len: u64, cursor: u64, sector_size: u64) -> Self {
        Self {
            remaining: len,
            cursor,
            sector_size,
        }
    }

    // ECMA-119 6.5.4: Non-final extents must be multiples of the logical block size.
    fn max_extent_size(&self) -> u64 {
        (u32::MAX as u64 / self.sector_size) * self.sector_size
    }

    /// Collects all extents into a `Vec<DirectoryRef>` and returns the final cursor.
    #[cfg(test)]
    pub fn collect_with_cursor(self) -> (Vec<DirectoryRef>, u64) {
        let mut extents = Vec::new();
        let mut cursor = self.cursor;

        for (extent, new_cursor) in self {
            extents.push(extent);
            cursor = new_cursor;
        }

        (extents, cursor)
    }
}

impl Iterator for ExtentIter {
    type Item = (DirectoryRef, u64);

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }

        let chunk = self.remaining.min(self.max_extent_size());

        let aligned = (self.cursor + self.sector_size - 1) & !(self.sector_size - 1);
        let extent = DirectoryRef::new((aligned / self.sector_size) as usize, chunk as usize);

        self.cursor = aligned + chunk;
        self.remaining -= chunk;

        Some((extent, self.cursor))
    }
}

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

    #[test]
    fn extent_iter_splits_correctly() {
        let sector_size = 2048;
        let cursor = 0;

        let len = u32::MAX as u64 + 1;
        let iter = ExtentIter::new(len, cursor, sector_size);
        let (extents, final_cursor) = iter.collect_with_cursor();

        assert_eq!(extents.len(), 2);

        assert_eq!(extents[0].size, 4_294_965_248);
        assert_eq!(extents[0].extent.0, 0);

        assert_eq!(extents[1].size, 2048);
        let expected_sector: u64 = 4_294_965_248 / 2048;
        assert_eq!(extents[1].extent.0, expected_sector as usize);

        assert_eq!(final_cursor, len);
    }

    #[test]
    fn extent_iter_aligns_non_final_extents_to_sector_size() {
        let sector_size = 4096;
        let len = u32::MAX as u64 + 1;
        let (extents, final_cursor) = ExtentIter::new(len, 0, sector_size).collect_with_cursor();

        assert_eq!(extents.len(), 2);
        assert_eq!(extents[0].size as u64, 4_294_963_200);
        assert_eq!(extents[0].size as u64 % sector_size, 0);
        assert_eq!(extents[1].size as u64, len - 4_294_963_200);
        assert_eq!(extents[1].extent.0 as u64, 4_294_963_200 / sector_size);
        assert_eq!(final_cursor, len);
    }

    #[test]
    fn extent_iter_small_file() {
        let sector_size = 2048;
        let len = 1024; // < 4 GiB
        let iter = ExtentIter::new(len, 0, sector_size);
        let (extents, final_cursor) = iter.collect_with_cursor();

        assert_eq!(extents.len(), 1);
        assert_eq!(extents[0].size, 1024);
        assert_eq!(extents[0].extent.0, 0);
        assert_eq!(final_cursor, 1024);
    }

    #[test]
    fn deduplicates_logical_files_without_splitting_extent_names() {
        let record = |flags| PendingRecord {
            name: b"README.TXT;1".to_vec().into(),
            split: SplitSu::empty(),
            dir_ref: DirectoryRef::default(),
            flags,
        };
        let mut records = vec![
            record(FileFlags::NOT_FINAL),
            record(FileFlags::empty()),
            record(FileFlags::empty()),
        ];

        PendingRecords::deduplicate_names(&mut records, EntryType::default());

        assert_eq!(records[0].name, records[1].name);
        assert_ne!(records[1].name, records[2].name);
    }
}