disk-core 0.2.1

Shared base for the rusty-backup filesystem, partition-table and disk-image crates
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
/// A file or directory entry within a partition's filesystem.
#[derive(Debug, Clone)]
pub struct FileEntry {
    pub name: String,
    pub path: String,
    pub entry_type: EntryType,
    pub size: u64,
    /// Starting cluster (FAT) or inode/extent for other filesystems.
    pub location: u64,
    /// Human-readable modification date string.
    pub modified: Option<String>,
    /// Modification time in seconds since UNIX epoch 1970-01-01. The numeric
    /// twin of `modified` — the display string is for the browser/`ls`, this
    /// is what `tar_export` writes into its headers and what a `stage_copy`
    /// passes into `CreateFileOptions.unix_times` so a cross-image copy
    /// preserves the source's date instead of stamping the current time.
    /// Populated by every filesystem driver whose on-disk format carries a
    /// per-file mtime (all Unix / Amiga / classic-Mac / DOS families);
    /// `None` on formats that don't (Apple DOS 3.3, TRS-80, etc.).
    pub modified_unix: Option<u64>,
    /// HFS/HFS+/MFS file type as the raw 4-byte Mac `OSType`, exactly as
    /// stored on disk (e.g. `*b"APPL"`, `*b"PICT"`). Kept as bytes — not text —
    /// because an `OSType` may hold non-ASCII bytes (e.g. Prince of Persia's
    /// `PoƒP` creator has `0xC4`), and round-trip writers (`get-binhex`, `cp`,
    /// `tar`, archives) must preserve them verbatim. For display, render via
    /// [`FileEntry::type_code_display`] (lossy) — never rebuild bytes from it.
    /// `None` on non-Mac filesystems (ProDOS uses [`prodos_file_type`]).
    pub type_code: Option<[u8; 4]>,
    /// HFS/HFS+/MFS creator as the raw 4-byte Mac `OSType`. See
    /// [`type_code`](FileEntry::type_code); display via
    /// [`creator_code_display`](FileEntry::creator_code_display).
    pub creator_code: Option<[u8; 4]>,
    /// HFS/HFS+/MFS Finder flags (`FInfo.fdFlags`): `hasBundle` (0x2000),
    /// `hasCustomIcon` (0x0400), `isInvisible` (0x4000), `nameLocked`,
    /// `isStationery`, the `kIsAlias` bit (0x8000), etc. The 2-byte field at
    /// offset 8 of the 16-byte Finder info. `None` on non-Mac filesystems.
    /// Carried so copy / `get-binhex` round-trips preserve a file's real icon
    /// (a dropped `hasBundle` makes an app and its documents show generic
    /// icons). See `docs/bug_binhex_finder_flags.md`.
    pub finder_flags: Option<u16>,
    /// Symlink target path (only set for `EntryType::Symlink`).
    pub symlink_target: Option<String>,
    /// Special file type description (e.g. "block device", "char device", "socket", "fifo").
    /// Only set for `EntryType::Special`.
    pub special_type: Option<String>,
    /// Raw Unix mode bits (e.g. 0o100755). Present on ext/btrfs/xfs/UFS filesystems.
    pub mode: Option<u32>,
    /// Unix user ID. Present on ext/btrfs/xfs/UFS filesystems.
    pub uid: Option<u32>,
    /// Unix group ID. Present on ext/btrfs/xfs/UFS filesystems.
    pub gid: Option<u32>,
    /// Resource fork size (HFS/HFS+ only). None or Some(0) means no resource fork.
    pub resource_fork_size: Option<u64>,
    /// ProDOS auxiliary type (16-bit). Semantics depend on the file type
    /// (e.g. `$0801` = Applesoft BASIC load address, load addr for BIN,
    /// record length for random-access TXT). Only set for ProDOS entries.
    pub aux_type: Option<u16>,
    /// ProDOS file type — the raw 1-byte type value (e.g. `$04` = TXT,
    /// `$06` = BIN, `$FF` = SYS). ProDOS has no Mac `OSType`, so it uses this
    /// instead of [`type_code`](FileEntry::type_code). Rendered for display by
    /// [`type_code_display`](FileEntry::type_code_display) via
    /// `prodos_types::format_type_code`. Only set for ProDOS entries.
    pub prodos_file_type: Option<u8>,
    /// HFS+ hardlink target inode CNID. Set on entries whose catalog row
    /// is a hardlink stub (`fdType='hlnk' fdCreator='hfs+'`); the link's
    /// data and resource forks live on the inode at this CNID under
    /// `HFS+ Private Data`. `read_file` / `write_file_to` follow the
    /// indirection automatically. `None` for ordinary files.
    pub link_target_cnid: Option<u64>,
    /// AmigaDOS protection word (`access` field of an AFFS file header).
    /// `0` displays as `----rwed`. Only set for AmigaDOS / Fast File
    /// System entries.
    pub amiga_protection: Option<u32>,
    /// AmigaDOS filenote (comment), up to 79 bytes. Only set for
    /// AmigaDOS / Fast File System entries; `None` outside that family.
    pub amiga_comment: Option<String>,
    /// AmigaDOS raw datestamp triple `(days, minutes, ticks)` from the
    /// on-disk entry. Days since 1978-01-01, minutes within the day,
    /// and ticks (1/50s) within the minute. Preserved verbatim for
    /// byte-exact round-trips through clone/restore. AFFS stores these
    /// as i32 on disk; PFS3 direntries narrow them to u16 — we widen
    /// to i32 so both round-trip losslessly. The display string lives
    /// in `modified`. Only set for AmigaDOS / PFS3 / SFS entries;
    /// `None` outside that family.
    pub amiga_date: Option<(i32, i32, i32)>,
    /// Standard DOS attribute bits (read-only `0x01`, hidden `0x02`,
    /// system `0x04`, archive `0x20`; the volume-label `0x08` and
    /// directory `0x10` bits are represented by `entry_type` and not
    /// carried here). Populated for FAT (the on-disk `u8` widened) and
    /// exFAT (the directory entry's `u16` FileAttributes). `None` for
    /// filesystems that have no DOS attribute concept. The copy engine
    /// carries this across FAT/exFAT destinations.
    pub dos_attributes: Option<u16>,
    /// HFS/HFS+/MFS raw catalog dates `(create, modify, backup)` in Mac-epoch
    /// seconds (since 1904-01-01 UTC). Kept raw so the detail pane can both
    /// display them (via `hfs_common::format_mac_date`) and stage an in-place
    /// edit (`StagedEdit::SetDates`). The `modify` value is also surfaced as a
    /// formatted string in `modified`. `None` outside the HFS family.
    pub mac_dates: Option<(u32, u32, u32)>,
    /// Owner in the filesystem's own notation (QNX 2 `group.member`); shown instead of uid:gid.
    pub owner_label: Option<String>,
    /// Native attribute/permission letters for formats whose bits do not map onto a Unix mode.
    pub native_attrs: Option<String>,
    /// QNX 2 permissions, owner and raw date words, so QNX 2 to QNX 2 copies keep them exactly.
    pub qnx2_attrs: Option<Qnx2Attrs>,
}

/// Raw QNX 2 attributes; the same fields as the `qnx2fs` crate's `Attributes`, which converts to and from it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Qnx2Attrs {
    /// Owner attributes (`rwaem` for files, `rcbm` for directories).
    pub attr: u8,
    pub group_perms: u8,
    pub other_perms: u8,
    pub member: u8,
    pub group: u8,
    /// The raw QNX 2 date word pair.
    pub date: [u16; 2],
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EntryType {
    File,
    Directory,
    /// Symbolic link. The target path is stored in `FileEntry::symlink_target`.
    Symlink,
    /// Special file: block device, char device, socket, or FIFO.
    /// The kind is stored in `FileEntry::special_type`.
    Special,
}

impl FileEntry {
    pub fn root() -> Self {
        Self {
            name: "/".into(),
            path: "/".into(),
            entry_type: EntryType::Directory,
            size: 0,
            location: 0,
            modified: None,
            modified_unix: None,
            type_code: None,
            creator_code: None,
            finder_flags: None,
            prodos_file_type: None,
            symlink_target: None,
            special_type: None,
            mode: None,
            uid: None,
            gid: None,
            resource_fork_size: None,
            aux_type: None,
            link_target_cnid: None,
            amiga_protection: None,
            amiga_comment: None,
            amiga_date: None,
            dos_attributes: None,
            mac_dates: None,
            owner_label: None,
            native_attrs: None,
            qnx2_attrs: None,
        }
    }

    pub fn new_directory(name: String, path: String, location: u64) -> Self {
        Self {
            name,
            path,
            entry_type: EntryType::Directory,
            size: 0,
            location,
            modified: None,
            modified_unix: None,
            type_code: None,
            creator_code: None,
            finder_flags: None,
            prodos_file_type: None,
            symlink_target: None,
            special_type: None,
            mode: None,
            uid: None,
            gid: None,
            resource_fork_size: None,
            aux_type: None,
            link_target_cnid: None,
            amiga_protection: None,
            amiga_comment: None,
            amiga_date: None,
            dos_attributes: None,
            mac_dates: None,
            owner_label: None,
            native_attrs: None,
            qnx2_attrs: None,
        }
    }

    pub fn new_file(name: String, path: String, size: u64, location: u64) -> Self {
        Self {
            name,
            path,
            entry_type: EntryType::File,
            size,
            location,
            modified: None,
            modified_unix: None,
            type_code: None,
            creator_code: None,
            finder_flags: None,
            prodos_file_type: None,
            symlink_target: None,
            special_type: None,
            mode: None,
            uid: None,
            gid: None,
            resource_fork_size: None,
            aux_type: None,
            link_target_cnid: None,
            amiga_protection: None,
            amiga_comment: None,
            amiga_date: None,
            dos_attributes: None,
            mac_dates: None,
            owner_label: None,
            native_attrs: None,
            qnx2_attrs: None,
        }
    }

    pub fn new_symlink(
        name: String,
        path: String,
        size: u64,
        location: u64,
        target: String,
    ) -> Self {
        Self {
            name,
            path,
            entry_type: EntryType::Symlink,
            size,
            location,
            modified: None,
            modified_unix: None,
            type_code: None,
            creator_code: None,
            finder_flags: None,
            prodos_file_type: None,
            symlink_target: Some(target),
            special_type: None,
            mode: None,
            uid: None,
            gid: None,
            resource_fork_size: None,
            aux_type: None,
            link_target_cnid: None,
            amiga_protection: None,
            amiga_comment: None,
            amiga_date: None,
            dos_attributes: None,
            mac_dates: None,
            owner_label: None,
            native_attrs: None,
            qnx2_attrs: None,
        }
    }

    pub fn new_special(
        name: String,
        path: String,
        location: u64,
        special_type_str: String,
    ) -> Self {
        Self {
            name,
            path,
            entry_type: EntryType::Special,
            size: 0,
            location,
            modified: None,
            modified_unix: None,
            type_code: None,
            creator_code: None,
            finder_flags: None,
            prodos_file_type: None,
            symlink_target: None,
            special_type: Some(special_type_str),
            mode: None,
            uid: None,
            gid: None,
            resource_fork_size: None,
            aux_type: None,
            link_target_cnid: None,
            amiga_protection: None,
            amiga_comment: None,
            amiga_date: None,
            dos_attributes: None,
            mac_dates: None,
            owner_label: None,
            native_attrs: None,
            qnx2_attrs: None,
        }
    }

    /// The name this entry should carry inside an archive or an extraction
    /// folder — or `None` when it is a volume root, which contributes its
    /// *children* rather than a member of its own.
    ///
    /// Every driver names the volume root `"/"` (the optical drivers map their
    /// empty root name onto it too), and that is not a usable member name:
    /// tar and zip both reject absolute paths, and `Path::join("/")` silently
    /// throws away the destination directory and hands back the **host** root.
    /// So an exporter handed a whole volume must ask here rather than reach for
    /// `name` — the answer is "this has no name, recurse into it at the same
    /// level", which is also what `tar -C / .` does.
    pub fn archive_name(&self) -> Option<&str> {
        let trimmed = self.name.trim_matches('/');
        // ".." would escape the destination on extraction, "." names the
        // directory an archive is already rooted at; neither is a member.
        if trimmed.is_empty() || trimmed == "." || trimmed == ".." {
            None
        } else {
            Some(trimmed)
        }
    }

    pub fn is_directory(&self) -> bool {
        self.entry_type == EntryType::Directory
    }

    pub fn is_file(&self) -> bool {
        self.entry_type == EntryType::File
    }

    pub fn is_symlink(&self) -> bool {
        self.entry_type == EntryType::Symlink
    }

    pub fn is_special(&self) -> bool {
        self.entry_type == EntryType::Special
    }

    /// Returns a human-readable Unix permission string (e.g. "drwxr-xr-x"),
    /// or `None` if mode bits are not available (non-Unix filesystems).
    pub fn mode_string(&self) -> Option<String> {
        self.mode.map(crate::display::unix_mode_string)
    }

    pub fn size_string(&self) -> String {
        if self.is_directory() || self.is_special() {
            return String::new();
        }
        crate::display::format_size(self.size)
    }

    /// Human-readable creator string for display. Mac `OSType` only (ProDOS
    /// has no creator), rendered lossily by [`crate::display::decode_ostype`].
    pub fn creator_code_display(&self) -> Option<String> {
        self.creator_code
            .as_ref()
            .map(crate::display::decode_ostype)
    }
}

/// Display order for a directory listing: directories first, then everything
/// else, each group by name case-insensitively.
///
/// Drivers return entries in on-disk order (insertion order on FAT, B-tree
/// order on HFS, and so on), which is why the browse tree looked unsorted.
/// This is display-only — `ls` and the archive writers keep the driver's order,
/// which is what the regression cases assert against.
pub fn sort_for_display(entries: &mut [FileEntry]) {
    entries.sort_by_cached_key(|e| (!e.is_directory(), e.name.to_lowercase()));
}

/// The directory part of an absolute entry path, "" for a top-level entry.
fn parent_dir(path: &str) -> &str {
    match path.trim_end_matches('/').rsplit_once('/') {
        Some((dir, _)) => dir,
        None => "",
    }
}

/// The deepest directory containing every selected entry, "" at the volume root.
///
/// Selections are named relative to this, so picking several files out of one
/// folder still yields bare names (what it always did) while a selection that
/// spans folders keeps enough path to stay unique. Without it every root was
/// named by `archive_name()` alone, so `/a/notes.txt` and `/b/notes.txt` both
/// became `notes.txt` and the second silently replaced the first.
pub fn common_parent(entries: &[FileEntry]) -> String {
    let mut it = entries.iter();
    let Some(first) = it.next() else {
        return String::new();
    };
    let mut base: Vec<&str> = parent_dir(&first.path)
        .split('/')
        .filter(|c| !c.is_empty())
        .collect();
    for e in it {
        let these: Vec<&str> = parent_dir(&e.path)
            .split('/')
            .filter(|c| !c.is_empty())
            .collect();
        let keep = base
            .iter()
            .zip(these.iter())
            .take_while(|(a, b)| a == b)
            .count();
        base.truncate(keep);
        if base.is_empty() {
            break;
        }
    }
    if base.is_empty() {
        String::new()
    } else {
        format!("/{}", base.join("/"))
    }
}

/// `entry`'s own directory relative to `base`; "" when it sits directly in it.
/// Always uses `/` separators — callers targeting the host filesystem convert.
pub fn relative_dir(entry: &FileEntry, base: &str) -> String {
    let dir = parent_dir(&entry.path);
    let rel = dir.strip_prefix(base).unwrap_or(dir);
    rel.trim_matches('/').to_string()
}

/// The child called `name`, matched the way the filesystem itself would
/// (`fold_case` is its `case_insensitive_lookup`); an exact match wins first.
pub fn select_child<'a>(
    children: &'a [FileEntry],
    fold_case: bool,
    name: &str,
) -> Option<&'a FileEntry> {
    children.iter().find(|c| c.name == name).or_else(|| {
        fold_case
            .then(|| children.iter().find(|c| c.name.eq_ignore_ascii_case(name)))
            .flatten()
    })
}

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

    fn e(name: &str, dir: bool) -> FileEntry {
        let mut x = FileEntry::root();
        x.name = name.to_string();
        x.path = format!("/{name}");
        x.entry_type = if dir {
            EntryType::Directory
        } else {
            EntryType::File
        };
        x
    }

    #[test]
    fn directories_come_first_then_case_insensitive_name() {
        let mut v = vec![
            e("zebra.txt", false),
            e("Apple", true),
            e("banana.TXT", false),
            e("apple.txt", false),
            e("Zoo", true),
        ];
        sort_for_display(&mut v);
        let got: Vec<&str> = v.iter().map(|x| x.name.as_str()).collect();
        assert_eq!(
            got,
            ["Apple", "Zoo", "apple.txt", "banana.TXT", "zebra.txt"],
            "folders first, then files, each case-insensitively by name"
        );
    }

    /// The bug this fixes: an uppercase name must not sort before every
    /// lowercase one, which is what a plain byte-order sort does.
    #[test]
    fn uppercase_does_not_sort_ahead_of_lowercase() {
        let mut v = vec![e("beta", false), e("Alpha", false), e("gamma", false)];
        sort_for_display(&mut v);
        let got: Vec<&str> = v.iter().map(|x| x.name.as_str()).collect();
        assert_eq!(got, ["Alpha", "beta", "gamma"]);
    }
}