hadris-iso 1.1.2

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
use super::super::io::{self, Write};
use alloc::{collections::BTreeMap, collections::VecDeque, string::String, sync::Arc, vec::Vec};
use hadris_common::types::endian::EndianType;

use super::super::io::LogicalSector;
use super::super::path::PathTableEntryHeader;
use super::super::read::PathSeparator;
use crate::file::EntryType;
#[cfg(test)]
use crate::file::{convert_joliet3, convert_l1, convert_l2, convert_l3};

use super::super::directory::DirectoryRef;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct DirectoryId {
    indices: Vec<usize>,
}

impl DirectoryId {
    pub fn push(&mut self, index: usize) {
        self.indices.push(index);
    }

    pub fn pop(&mut self) -> usize {
        self.indices.pop().expect("directory underflow")
    }
}

#[derive(Debug)]
pub struct WrittenFiles {
    root: WrittenDirectory,
}

impl Default for WrittenFiles {
    fn default() -> Self {
        Self::new()
    }
}

impl WrittenFiles {
    pub fn new() -> Self {
        Self {
            root: WrittenDirectory::new(Arc::new(String::new())),
        }
    }

    pub fn find_file(&self, name: &str, _sep: PathSeparator) -> Option<DirectoryRef> {
        let mut current_dir = DirectoryId {
            indices: Vec::new(),
        };
        // Split on both separators for cross-platform compatibility
        let mut parts: Vec<&str> = name.split(['/', '\\']).filter(|s| !s.is_empty()).collect();
        // Empty path, not a valid file
        let filename = parts.pop()?;
        'outer: for part in parts {
            let dir = self.get(&current_dir);
            for (idx, dir) in dir.dirs.iter().enumerate() {
                if dir.name.as_str() == part {
                    current_dir.push(idx);
                    continue 'outer;
                }
            }
            // didn't find
            return None;
        }

        let dir = self.get(&current_dir);
        dir.files
            .iter()
            .find(|f| f.name.as_str() == filename)
            .map(|f| f.entry)
    }

    pub fn root_dir(&self) -> DirectoryId {
        DirectoryId {
            indices: Vec::new(),
        }
    }

    pub fn root_refs(&self) -> &BTreeMap<EntryType, DirectoryRef> {
        &self.root.entries
    }

    pub fn get(&self, id: &DirectoryId) -> &WrittenDirectory {
        let mut dir = &self.root;
        for index in &id.indices {
            dir = &dir.dirs[*index];
        }
        dir
    }

    pub fn get_mut(&mut self, id: &DirectoryId) -> &mut WrittenDirectory {
        let mut dir = &mut self.root;
        for index in &id.indices {
            dir = &mut dir.dirs[*index];
        }
        dir
    }
}

#[derive(Debug)]
pub struct WrittenDirectory {
    pub name: Arc<String>,
    pub entries: BTreeMap<EntryType, DirectoryRef>,
    pub dirs: Vec<WrittenDirectory>,
    pub files: Vec<WrittenFile>,
}

impl WrittenDirectory {
    pub fn new(name: Arc<String>) -> Self {
        Self {
            name,
            entries: BTreeMap::new(),
            dirs: Vec::new(),
            files: Vec::new(),
        }
    }

    pub fn push_dir(&mut self, name: Arc<String>) -> usize {
        self.dirs.push(Self::new(name));
        self.dirs.len() - 1
    }
}

#[derive(Debug)]
pub struct WrittenFile {
    pub name: Arc<String>,
    pub entry: DirectoryRef,
}

pub(crate) struct PathTableWriter<'a> {
    pub written_files: &'a WrittenFiles,
    pub ty: EntryType,
    pub endian: EndianType,
}

io_transform! {

/// Write a single path table record.
async fn write_pt_record<DATA: Write>(
    data: &mut DATA,
    endian: &EndianType,
    parent_number: u16,
    extent: LogicalSector,
    name: &[u8],
) -> io::Result<()> {
    let header = PathTableEntryHeader {
        len: name.len() as u8,
        extended_attr_record: 0,
        parent_directory_number: endian.u16_bytes(parent_number),
        parent_lba: endian.u32_bytes(extent.0 as u32),
    };
    data.write_all(bytemuck::bytes_of(&header)).await?;
    data.write_all(name).await?;
    if !name.len().is_multiple_of(2) {
        data.write_all(&[0x00]).await?; // padding to even
    }
    Ok(())
}

impl PathTableWriter<'_> {
    pub async fn write<DATA: Write>(&mut self, data: &mut DATA) -> io::Result<()> {
        // BFS queue: (directory_ref, parent_number)
        // ISO 9660 requires path table entries in breadth-first order.
        let mut queue: VecDeque<(&WrittenDirectory, u16)> = VecDeque::new();
        let mut current_number: u16 = 1;

        // Root entry (parent = 1, i.e. itself)
        let root = &self.written_files.root;
        let root_extent = *root.entries.get(&self.ty).unwrap();
        write_pt_record(data, &self.endian, 1, root_extent.extent, &[0x00]).await?;
        queue.push_back((root, 1));

        while let Some((dir, parent_num)) = queue.pop_front() {
            let my_number = parent_num;
            for child_dir in &dir.dirs {
                current_number += 1;
                let name = self.ty.convert_name(&child_dir.name);
                let name_bytes = name.as_bytes();
                let extent = child_dir.entries.get(&self.ty).unwrap().extent;
                write_pt_record(data, &self.endian, my_number, extent, name_bytes).await?;
                queue.push_back((child_dir, current_number));
            }
        }
        Ok(())
    }
}

} // io_transform!

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;
    use alloc::format;

    #[test]
    fn test_convert_l1() {
        let orig = "this-is-the-original-file.@very-long-ext";
        let converted = convert_l1(orig, false);
        assert_eq!(converted.as_str(), "THIS_IS_._VE;1");
        let converted = convert_l1(orig, true);
        assert_eq!(converted.as_str(), "this_is_._ve;1");
    }

    #[test]
    fn test_convert_l2_short_name() {
        let orig = "readme.txt";
        let converted = convert_l2(orig, false);
        assert_eq!(converted.as_str(), "README.TXT;1");
    }

    #[test]
    fn test_convert_l2_long_name_truncation() {
        // Max is 30 bytes for name + 2 for ";1" = 32 total
        let orig = "this-is-a-very-long-filename-that-should-be-truncated.extension";
        let converted = convert_l2(orig, false);
        // Should be truncated to 30 bytes total (basename + dot + ext) + ";1"
        assert!(
            converted.len() <= 32,
            "L2 name too long: {}",
            converted.len()
        );
        assert!(converted.as_str().ends_with(";1"));
    }

    #[test]
    fn test_convert_l2_no_extension() {
        let orig = "this-is-a-very-long-directory-name-without-extension";
        let converted = convert_l2(orig, false);
        assert!(
            converted.len() <= 32,
            "L2 name too long: {}",
            converted.len()
        );
        assert!(converted.as_str().ends_with(";1"));
        // First 30 characters + ";1"
        assert_eq!(converted.as_str(), "THIS_IS_A_VERY_LONG_DIRECTORY_;1");
    }

    #[test]
    fn test_convert_l3_short_name() {
        let orig = "readme.txt";
        let converted = convert_l3(orig, false);
        assert_eq!(converted.as_str(), "README.TXT");
    }

    #[test]
    fn test_convert_l3_long_name_truncation() {
        // Max is 207 bytes for L3
        let long_name = "a".repeat(250);
        let converted = convert_l3(&long_name, false);
        assert!(
            converted.len() <= 207,
            "L3 name too long: {}",
            converted.len()
        );
        assert_eq!(converted.len(), 207);
    }

    #[test]
    fn test_convert_l3_with_extension() {
        // Create a name that exceeds 207 bytes with extension
        let basename = "a".repeat(200);
        let orig = format!("{}.txt", basename);
        let converted = convert_l3(&orig, false);
        assert!(
            converted.len() <= 207,
            "L3 name too long: {}",
            converted.len()
        );
    }

    // Edge-case tests for convert_l1

    #[test]
    fn test_convert_l1_empty_extension() {
        let converted = convert_l1("file.", false);
        assert_eq!(converted.as_str(), "FILE.;1");
    }

    #[test]
    fn test_convert_l1_dot_only() {
        let converted = convert_l1(".", false);
        assert_eq!(converted.as_str(), ".;1");
    }

    #[test]
    fn test_convert_l1_dot_dot() {
        // ".." → basename empty, dot, ext "." substituted to "_"
        let converted = convert_l1("..", false);
        assert_eq!(converted.as_str(), "._;1");
    }

    #[test]
    fn test_convert_l1_no_dot() {
        let converted = convert_l1("README", false);
        assert_eq!(converted.as_str(), "README;1");
    }

    #[test]
    fn test_convert_l1_no_dot_long() {
        let converted = convert_l1("LONGFILENAME", false);
        assert_eq!(converted.as_str(), "LONGFILE;1");
    }

    #[test]
    fn test_convert_l1_exact_8_3() {
        let converted = convert_l1("12345678.abc", false);
        assert_eq!(converted.as_str(), "12345678.ABC;1");
    }

    #[test]
    fn test_convert_l1_oversized() {
        let converted = convert_l1("longname1.longext", false);
        assert_eq!(converted.as_str(), "LONGNAME.LON;1");
    }

    #[test]
    fn test_convert_l1_single_char() {
        let converted = convert_l1("a.b", false);
        assert_eq!(converted.as_str(), "A.B;1");
    }

    #[test]
    fn test_convert_l1_multibyte_utf8() {
        // "café.txt" — 'é' is 2 bytes in UTF-8, basename "café" = 5 bytes
        let converted = convert_l1("café.txt", false);
        // Should not panic; multi-byte chars get substituted by CharsetD
        assert!(converted.len() <= 14, "L1 overflow: {}", converted.len());
        assert!(converted.as_str().ends_with(";1"));
    }

    // Edge-case tests for convert_l2

    #[test]
    fn test_convert_l2_empty_extension() {
        let converted = convert_l2("file.", false);
        assert_eq!(converted.as_str(), "FILE.;1");
    }

    #[test]
    fn test_convert_l2_no_dot() {
        let converted = convert_l2("README", false);
        assert_eq!(converted.as_str(), "README;1");
    }

    #[test]
    fn test_convert_l2_single_char() {
        let converted = convert_l2("a.b", false);
        assert_eq!(converted.as_str(), "A.B;1");
    }

    // Edge-case tests for convert_l3

    #[test]
    fn test_convert_l3_empty_extension() {
        let converted = convert_l3("file.", false);
        assert_eq!(converted.as_str(), "FILE.");
    }

    #[test]
    fn test_convert_l3_no_dot() {
        let converted = convert_l3("README", false);
        assert_eq!(converted.as_str(), "README");
    }

    #[test]
    fn test_convert_l3_single_char() {
        let converted = convert_l3("a.b", false);
        assert_eq!(converted.as_str(), "A.B");
    }

    // Edge-case tests for convert_joliet3

    #[test]
    fn test_convert_joliet3_short_name() {
        let converted = convert_joliet3("readme.txt");
        // UTF-16 BE: each char is 2 bytes, "readme.txt" = 10 chars = 20 bytes
        assert_eq!(converted.len(), 20);
    }

    #[test]
    fn test_convert_joliet3_long_name_truncation() {
        // 207 bytes / 2 = 103 UTF-16 code units max
        let long_name = "a".repeat(150);
        let converted = convert_joliet3(&long_name);
        // 103 code units * 2 bytes = 206 bytes
        assert!(
            converted.len() <= 207,
            "Joliet overflow: {}",
            converted.len()
        );
        assert_eq!(converted.len(), 206);
    }

    #[test]
    fn test_convert_joliet3_multibyte_utf8() {
        // "café.txt" — 'é' is one UTF-16 code unit, 8 code units total
        let converted = convert_joliet3("café.txt");
        // 8 code units * 2 bytes = 16 bytes
        assert_eq!(converted.len(), 16);
    }
}