Skip to main content

which_fs/
magic.rs

1// SPDX-FileCopyrightText: 2026 Manuel Quarneti <mq1@ik.me>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4// https://github.com/torvalds/linux/blob/master/include/uapi/linux/magic.h
5
6#![allow(clippy::cast_possible_wrap)]
7
8use crate::FsKind;
9
10#[cfg(target_os = "macos")]
11pub type Magic = [i8; 16];
12
13#[cfg(target_os = "macos")]
14type CharType = i8;
15
16#[cfg(target_os = "linux")]
17pub type Magic = rustix::fs::FsWord;
18
19#[cfg(windows)]
20pub type Magic = [u16; 8];
21
22#[cfg(windows)]
23type Char = u16;
24
25#[cfg(any(target_os = "macos", target_os = "windows"))]
26const fn to_magic<const L: usize>(s: &'static [u8; L]) -> Magic {
27    let mut buf = [0; 16];
28
29    let mut i = 0;
30    while i < L {
31        buf[i] = s[i] as CharType;
32        i += 1;
33    }
34
35    buf
36}
37
38// FAT32
39// =====
40
41#[cfg(target_os = "linux")]
42const FAT32: Magic = 0x4d44; // MD
43
44#[cfg(target_os = "macos")]
45const FAT32: Magic = to_magic(b"msdos");
46
47#[cfg(windows)]
48const FAT32: Magic = to_magic(b"FAT32");
49
50// EXFAT
51// =====
52
53#[cfg(target_os = "linux")]
54const EXFAT: Magic = 0x2011BAB0;
55
56#[cfg(target_os = "macos")]
57const EXFAT: Magic = to_magic(b"exfat");
58
59#[cfg(windows)]
60const EXFAT: Magic = to_magic(b"exFAT");
61
62// APFS
63// ====
64
65#[cfg(target_os = "linux")]
66const APFS: Magic = 0x42535041;
67
68#[cfg(target_os = "macos")]
69const APFS: Magic = to_magic(b"apfs");
70
71#[cfg(windows)]
72const APFS: Magic = to_magic(b"APFS");
73
74pub fn which_kind(magic: Magic) -> FsKind {
75    match magic {
76        FAT32 => FsKind::Fat32,
77        EXFAT => FsKind::ExFat,
78        APFS => FsKind::Apfs,
79        idk => FsKind::Unknown(idk),
80    }
81}