hadris-iso 2.0.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
use hadris_fixed::FixedBytes;

#[cfg(feature = "alloc")]
use crate::joliet::JolietLevel;

#[cfg(feature = "write")]
use crate::types::{Charset, CharsetD, CharsetD1};

/// The type of directory entry, indicating the ISO interchange level and features
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryType {
    /// The `Level1` variant.
    Level1 {
        /// The `supports_lowercase` field.
        supports_lowercase: bool,
        /// The `supports_rrip` field.
        supports_rrip: bool,
    },
    /// The `Level2` variant.
    Level2 {
        /// The `supports_lowercase` field.
        supports_lowercase: bool,
        /// The `supports_rrip` field.
        supports_rrip: bool,
    },
    /// The `Level3` variant.
    Level3 {
        /// The `supports_lowercase` field.
        supports_lowercase: bool,
        /// The `supports_rrip` field.
        supports_rrip: bool,
    },
    #[cfg(feature = "alloc")]
    /// The `Joliet` variant.
    Joliet {
        /// The `level` field.
        level: JolietLevel,
        /// The `supports_rrip` field.
        supports_rrip: bool,
    },
}

impl Default for EntryType {
    fn default() -> Self {
        Self::Level1 {
            supports_lowercase: false,
            supports_rrip: false,
        }
    }
}

impl EntryType {
    // Usefulness coefficient:
    // bits 0-3 = base level (lowercase = 4,5,6 Joliet = level 12, 13, 14)
    // bit 4 = rrip
    /// Performs the `supports_rrip` operation.
    pub fn supports_rrip(&self) -> bool {
        match self {
            Self::Level1 { supports_rrip, .. } => *supports_rrip,
            Self::Level2 { supports_rrip, .. } => *supports_rrip,
            Self::Level3 { supports_rrip, .. } => *supports_rrip,
            #[cfg(feature = "alloc")]
            Self::Joliet { supports_rrip, .. } => *supports_rrip,
        }
    }

    // Usefulness coefficient:
    // bits 0-3 = base level (lowercase = 4,5,6 Joliet = level 12, 13, 14)
    // bit 4 = rrip
    fn usefulness(self) -> u8 {
        match self {
            Self::Level1 {
                supports_lowercase,
                supports_rrip,
            } => (supports_lowercase as u8) << 2 | (supports_rrip as u8) << 4,
            Self::Level2 {
                supports_lowercase,
                supports_rrip,
            } => 0x01 | (supports_lowercase as u8) << 2 | (supports_rrip as u8) << 4,
            Self::Level3 {
                supports_lowercase,
                supports_rrip,
            } => 0x02 | (supports_lowercase as u8) << 2 | (supports_rrip as u8) << 4,
            #[cfg(feature = "alloc")]
            Self::Joliet {
                level,
                supports_rrip,
            } => (level as u8 + 11) | (supports_rrip as u8) << 4,
        }
    }
}

impl Ord for EntryType {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.usefulness().cmp(&other.usefulness())
    }
}

impl PartialOrd for EntryType {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

#[cfg(feature = "alloc")]
impl From<JolietLevel> for EntryType {
    fn from(value: JolietLevel) -> Self {
        Self::Joliet {
            level: value,
            supports_rrip: false,
        }
    }
}

/// Type alias for FilenameL1.
pub type FilenameL1 = FixedBytes<14>;
/// Type alias for FilenameL2.
pub type FilenameL2 = FixedBytes<32>;
/// Type alias for FilenameL3.
pub type FilenameL3 = FixedBytes<207>;

#[cfg(feature = "write")]
/// Identifies a ConvertedName value.
pub enum ConvertedName {
    /// The `Level1` variant.
    Level1(FilenameL1),
    /// The `Level2` variant.
    Level2(FilenameL2),
    /// The `Level3` variant.
    Level3(FilenameL3),
    /// The `Joliet` variant.
    Joliet(FixedBytes<207>),
}

#[cfg(feature = "write")]
impl ConvertedName {
    /// Performs the `as_bytes` operation.
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            Self::Level1(name) => name.as_bytes(),
            Self::Level2(name) => name.as_bytes(),
            Self::Level3(name) => name.as_bytes(),
            Self::Joliet(name) => name.as_bytes(),
        }
    }
}

#[cfg(feature = "write")]
impl EntryType {
    /// Performs the `convert_name` operation.
    pub fn convert_name(self, name: &str) -> ConvertedName {
        match self {
            Self::Level1 {
                supports_lowercase, ..
            } => ConvertedName::Level1(convert_l1(name, supports_lowercase)),
            Self::Level2 {
                supports_lowercase, ..
            } => ConvertedName::Level2(convert_l2(name, supports_lowercase)),
            Self::Level3 {
                supports_lowercase, ..
            } => ConvertedName::Level3(convert_l3(name, supports_lowercase)),
            Self::Joliet { level, .. } => match level {
                // All Joliet levels use UTF-16 BE encoding
                JolietLevel::Level1 | JolietLevel::Level2 | JolietLevel::Level3 => {
                    ConvertedName::Joliet(convert_joliet3(name))
                }
            },
        }
    }

    /// Converts a directory name without a file extension or version suffix.
    pub fn convert_directory_name(self, name: &str) -> ConvertedName {
        fn primary<const N: usize>(
            name: &str,
            max: usize,
            supports_lowercase: bool,
        ) -> FixedBytes<N> {
            let mut converted = FixedBytes::empty();
            let end = name
                .char_indices()
                .map(|(offset, _)| offset)
                .take_while(|offset| *offset <= max)
                .last()
                .unwrap_or(0);
            let end = if name.len() <= max { name.len() } else { end };
            let range = converted.push_slice(&name.as_bytes()[..end]);
            let bytes = converted.as_bytes_mut()[range].iter_mut();
            if supports_lowercase {
                CharsetD1::substitute_invalid(bytes);
            } else {
                CharsetD::substitute_invalid(bytes);
            }
            converted
        }

        match self {
            Self::Level1 {
                supports_lowercase, ..
            } => ConvertedName::Level1(primary(name, 8, supports_lowercase)),
            Self::Level2 {
                supports_lowercase, ..
            } => ConvertedName::Level2(primary(name, 31, supports_lowercase)),
            Self::Level3 {
                supports_lowercase, ..
            } => ConvertedName::Level3(primary(name, 31, supports_lowercase)),
            Self::Joliet { .. } => ConvertedName::Joliet(convert_joliet3(name)),
        }
    }
}

#[cfg(feature = "write")]
/// Performs the `convert_l1` operation.
pub fn convert_l1(name: &str, supports_lowercase: bool) -> FixedBytes<14> {
    let mut l1 = FixedBytes::empty();
    let name_bytes = name.as_bytes();
    match name.find('.') {
        Some(index) => {
            // We copy the basename, at most 8 bytes
            let basename = l1.push_slice(&name_bytes[0..index.min(8)]);
            let basename = l1.as_bytes_mut()[basename].iter_mut();
            if supports_lowercase {
                CharsetD1::substitute_invalid(basename);
            } else {
                CharsetD::substitute_invalid(basename);
            }
            // Extension length excluding the dot character
            let ext_len = (name.len() - index - 1).min(3);
            l1.push_byte(b'.');
            let ext = l1.push_slice(&name_bytes[index + 1..(index + 1 + ext_len).min(name.len())]);
            let ext = l1.as_bytes_mut()[ext].iter_mut();
            if supports_lowercase {
                CharsetD1::substitute_invalid(ext);
            } else {
                CharsetD::substitute_invalid(ext);
            }
        }
        None => {
            let len = name.len().min(8);
            let basename = l1.push_slice(&name_bytes[0..len]);
            let basename = l1.as_bytes_mut()[basename].iter_mut();
            if supports_lowercase {
                CharsetD1::substitute_invalid(basename);
            } else {
                CharsetD::substitute_invalid(basename);
            }
        }
    }
    l1.push_slice(b";1");
    l1
}

#[cfg(feature = "write")]
/// Performs the `convert_l2` operation.
pub fn convert_l2(name: &str, supports_lowercase: bool) -> FilenameL2 {
    let mut l2 = FilenameL2::empty();
    let name_bytes = name.as_bytes();
    // Max: 30 bytes for name (reserve 2 for ";1")
    const MAX_NAME_LEN: usize = 30;

    match name.find('.') {
        Some(index) => {
            let basename_end = index.min(MAX_NAME_LEN);
            let basename = l2.push_slice(&name_bytes[0..basename_end]);
            let basename = l2.as_bytes_mut()[basename].iter_mut();
            if supports_lowercase {
                CharsetD1::substitute_invalid(basename);
            } else {
                CharsetD::substitute_invalid(basename);
            }

            // Calculate remaining space for extension (subtract basename length and 1 for dot)
            let remaining = MAX_NAME_LEN.saturating_sub(basename_end + 1);
            if remaining > 0 {
                l2.push_byte(b'.');
                let ext_end = (index + 1 + remaining).min(name.len());
                let ext = l2.push_slice(&name_bytes[index + 1..ext_end]);
                let ext = l2.as_bytes_mut()[ext].iter_mut();
                if supports_lowercase {
                    CharsetD1::substitute_invalid(ext);
                } else {
                    CharsetD::substitute_invalid(ext);
                }
            }
        }
        None => {
            let len = name.len().min(MAX_NAME_LEN);
            let basename = l2.push_slice(&name_bytes[0..len]);
            let basename = l2.as_bytes_mut()[basename].iter_mut();
            if supports_lowercase {
                CharsetD1::substitute_invalid(basename);
            } else {
                CharsetD::substitute_invalid(basename);
            }
        }
    }
    l2.push_slice(b";1");
    l2
}

#[cfg(feature = "write")]
/// Performs the `convert_l3` operation.
pub fn convert_l3(name: &str, supports_lowercase: bool) -> FilenameL3 {
    let mut l3 = FilenameL3::empty();
    let name_bytes = name.as_bytes();
    // Max: 207 bytes for name (no version suffix in L3)
    const MAX_NAME_LEN: usize = 207;

    match name.find('.') {
        Some(index) => {
            let basename_end = index.min(MAX_NAME_LEN);
            let basename = l3.push_slice(&name_bytes[0..basename_end]);
            let basename = l3.as_bytes_mut()[basename].iter_mut();
            if supports_lowercase {
                CharsetD1::substitute_invalid(basename);
            } else {
                CharsetD::substitute_invalid(basename);
            }

            // Calculate remaining space for extension (subtract basename length and 1 for dot)
            let remaining = MAX_NAME_LEN.saturating_sub(basename_end + 1);
            if remaining > 0 {
                l3.push_byte(b'.');
                let ext_end = (index + 1 + remaining).min(name.len());
                let ext = l3.push_slice(&name_bytes[index + 1..ext_end]);
                let ext = l3.as_bytes_mut()[ext].iter_mut();
                if supports_lowercase {
                    CharsetD1::substitute_invalid(ext);
                } else {
                    CharsetD::substitute_invalid(ext);
                }
            }
        }
        None => {
            let len = name.len().min(MAX_NAME_LEN);
            let basename = l3.push_slice(&name_bytes[0..len]);
            let basename = l3.as_bytes_mut()[basename].iter_mut();
            if supports_lowercase {
                CharsetD1::substitute_invalid(basename);
            } else {
                CharsetD::substitute_invalid(basename);
            }
        }
    }
    l3
}

/// Maximum number of characters in a Joliet file identifier.
///
/// The Joliet specification limits a file identifier to 64 UCS-2 characters.
/// (A 255-byte directory record could physically hold up to 103, but 64 is the
/// conformant limit produced by default by reference tools.)
#[cfg(feature = "write")]
pub const JOLIET_MAX_NAME_CHARS: usize = 64;

#[cfg(feature = "write")]
/// Encode `name` as a big-endian UCS-2 Joliet file identifier.
///
/// Joliet identifiers are UCS-2 (Basic Multilingual Plane only), not UTF-16:
/// a character outside the BMP cannot be represented as a single UCS-2 code
/// unit, so it is substituted with `_` rather than emitting a surrogate pair
/// into the field. The identifier is limited to [`JOLIET_MAX_NAME_CHARS`]
/// characters; longer names are truncated.
pub fn convert_joliet3(name: &str) -> FixedBytes<207> {
    let mut j1 = FixedBytes::empty();
    for c in name.chars().take(JOLIET_MAX_NAME_CHARS) {
        let unit = if (c as u32) <= 0xFFFF {
            c as u16
        } else {
            b'_' as u16
        };
        j1.push_slice(&unit.to_be_bytes());
    }

    j1
}

#[cfg(all(test, feature = "write", feature = "alloc"))]
mod joliet_tests {
    use super::*;
    use crate::joliet::decode_joliet_name;

    #[test]
    fn joliet_name_is_truncated_to_the_conformant_limit() {
        let long = "a".repeat(200);
        let encoded = convert_joliet3(&long);
        // Two bytes per UCS-2 unit, capped at 64 characters.
        assert_eq!(encoded.as_bytes().len(), JOLIET_MAX_NAME_CHARS * 2);
        assert_eq!(decode_joliet_name(encoded.as_bytes()).chars().count(), 64);
    }

    #[test]
    fn joliet_substitutes_non_bmp_instead_of_emitting_surrogates() {
        // U+1F600 GRINNING FACE is outside the BMP and cannot be UCS-2 encoded.
        let encoded = convert_joliet3("a\u{1F600}b.txt");
        let decoded = decode_joliet_name(encoded.as_bytes());
        assert_eq!(decoded, "a_b.txt");
        // No byte pair may fall in the UTF-16 surrogate range 0xD800..=0xDFFF.
        for pair in encoded.as_bytes().chunks_exact(2) {
            let unit = u16::from_be_bytes([pair[0], pair[1]]);
            assert!(
                !(0xD800..=0xDFFF).contains(&unit),
                "surrogate leaked into UCS-2"
            );
        }
    }

    #[test]
    fn joliet_preserves_bmp_unicode() {
        let encoded = convert_joliet3("日本語.txt");
        assert_eq!(decode_joliet_name(encoded.as_bytes()), "日本語.txt");
    }
}