Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

30.0 KB
Raw Blame
//! Reading an NTFS volume's Master File Table (MFT) directly: every file and folder of the volume, its name(s), the folder it is in,
//! its size, its dates and its attributes, from one sequential read of the table instead of listing every folder.
//!
//! WHY: the name index ([`crate::nameindex`]) is built by listing folders, about 60 thousand entries a second on a cold disk (a whole
//! C: drive of 1.4 million entries took 23 s). The MFT is one file the disk reads in a few seconds, and holds what the listing gives
//! and more (sizes and dates for every entry). Reading the volume needs administrator rights: the optional fast index helper does it
//! (see `crate::fastindex`), never the app itself.
//!
//! This module is the parsing, pure and tested on records made by hand: the boot sector ([`Boot`]), a record's update sequence fixups
//! ([`fixup`]), its attributes ([`parse_record`]) and the data runs of a non-resident attribute ([`runs`]). Merging extension records
//! into their base record is [`Table`]'s job.

/// What the volume's boot sector says about its layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Boot {
    pub bytes_per_sector: u32,
    pub bytes_per_cluster: u32,
    /// The cluster where the MFT starts.
    pub mft_lcn: u64,
    /// The size of one MFT record (1024 bytes on nearly every volume, 4096 on 4K-native disks).
    pub record_size: u32,
}

impl Boot {
    /// Reads an NTFS boot sector; `None` when it is not one (another file system, a damaged sector).
    pub fn parse(b: &[u8]) -> Option<Boot> {
        if b.len() < 512 || &b[3..11] != b"NTFS    " {
            return None;
        }
        let bytes_per_sector = u16::from_le_bytes([b[0x0B], b[0x0C]]) as u32;
        // sectors per cluster: a value above 0x80 is a power of two written negative (clusters of 64 KB and more)
        let spc = b[0x0D];
        let sectors_per_cluster = if spc > 0x80 {
            1u32.checked_shl(256 - spc as u32)?
        } else {
            spc as u32
        };
        let bytes_per_cluster = bytes_per_sector.checked_mul(sectors_per_cluster)?;
        let mft_lcn = u64::from_le_bytes(b[0x30..0x38].try_into().ok()?);
        // clusters per record: negative means the record is 2^-n bytes (smaller than a cluster), the usual case
        let cpr = b[0x40] as i8;
        let record_size = if cpr < 0 {
            1u32.checked_shl((-(cpr as i32)) as u32)?
        } else {
            bytes_per_cluster.checked_mul(cpr as u32)?
        };
        if bytes_per_sector < 256
            || bytes_per_cluster == 0
            || record_size < bytes_per_sector
            || record_size > 65536
        {
            return None;
        }
        Some(Boot {
            bytes_per_sector,
            bytes_per_cluster,
            mft_lcn,
            record_size,
        })
    }
}

/// Applies a record's update sequence: the last two bytes of each sector were replaced on disk by the sequence number (to catch a
/// torn write) and the real bytes are kept in the update sequence array. False when the record is damaged (a sector's check bytes
/// do not match) or not a record at all.
pub fn fixup(rec: &mut [u8], bytes_per_sector: usize) -> bool {
    if rec.len() < 48 || bytes_per_sector < 2 {
        return false;
    }
    let usa_off = u16::from_le_bytes([rec[4], rec[5]]) as usize;
    let usa_count = u16::from_le_bytes([rec[6], rec[7]]) as usize;
    if usa_count == 0
        || usa_off + usa_count * 2 > rec.len()
        || (usa_count - 1) * bytes_per_sector > rec.len()
    {
        return false;
    }
    let check = [rec[usa_off], rec[usa_off + 1]];
    for i in 1..usa_count {
        let end = i * bytes_per_sector;
        if rec[end - 2..end] != check {
            return false;
        }
        let real = [rec[usa_off + i * 2], rec[usa_off + i * 2 + 1]];
        rec[end - 2] = real[0];
        rec[end - 1] = real[1];
    }
    true
}

/// One name of an entry (a file with hard links has several): the folder it is in (its MFT record number) and the name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Name {
    pub parent: u64,
    pub name: String,
}

/// What one MFT record says, after [`fixup`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Record {
    /// The record's number in the table (the low 48 bits of a file reference).
    pub number: u64,
    /// The record's sequence number: with the number it makes the file reference (file id) the change journal names it by.
    pub seq: u16,
    /// The base record this extension record belongs to (`None` for a base record).
    pub base: Option<u64>,
    pub dir: bool,
    /// The names that count: Win32 and POSIX names; a DOS 8.3 short name is left out when a long one exists.
    pub names: Vec<Name>,
    /// The size of the unnamed data stream (0 for a folder).
    pub size: u64,
    /// Last written, as a FILETIME (100 ns since 1601), from the standard information.
    pub modified: u64,
    pub created: u64,
    /// The FILE_ATTRIBUTE_* bits from the standard information.
    pub attrs: u32,
    /// The record carries a size (an unnamed data attribute was in it): an extension record may carry it for its base.
    pub has_size: bool,
}

pub(crate) const ATTR_STANDARD_INFORMATION: u32 = 0x10;
pub(crate) const ATTR_FILE_NAME: u32 = 0x30;
pub(crate) const ATTR_DATA: u32 = 0x80;
const ATTR_END: u32 = 0xFFFF_FFFF;
pub(crate) const FLAG_IN_USE: u16 = 0x01;
pub(crate) const FLAG_DIRECTORY: u16 = 0x02;
const NAMESPACE_DOS: u8 = 2;
/// The low 48 bits of a file reference are the record number (the high 16 are its sequence number).
pub const REF_MASK: u64 = 0x0000_FFFF_FFFF_FFFF;

fn u16_at(b: &[u8], o: usize) -> Option<u16> {
    Some(u16::from_le_bytes(b.get(o..o + 2)?.try_into().ok()?))
}
fn u32_at(b: &[u8], o: usize) -> Option<u32> {
    Some(u32::from_le_bytes(b.get(o..o + 4)?.try_into().ok()?))
}
fn u64_at(b: &[u8], o: usize) -> Option<u64> {
    Some(u64::from_le_bytes(b.get(o..o + 8)?.try_into().ok()?))
}

/// Reads one record (already fixed up). `None` for a record that is not in use or not a record ("FILE" missing, damaged).
pub fn parse_record(rec: &[u8], number: u64) -> Option<Record> {
    if rec.get(0..4)? != b"FILE" {
        return None;
    }
    let flags = u16_at(rec, 0x16)?;
    if flags & FLAG_IN_USE == 0 {
        return None;
    }
    let used = (u32_at(rec, 0x18)? as usize).min(rec.len());
    let base = u64_at(rec, 0x20)? & REF_MASK;
    let seq = u16_at(rec, 0x10)?;
    let mut r = Record {
        number,
        seq,
        base: (base != 0).then_some(base),
        dir: flags & FLAG_DIRECTORY != 0,
        ..Default::default()
    };
    let mut dos: Vec<Name> = Vec::new();
    let mut at = u16_at(rec, 0x14)? as usize;
    while at + 16 <= used {
        let kind = u32_at(rec, at)?;
        if kind == ATTR_END {
            break;
        }
        let len = u32_at(rec, at + 4)? as usize;
        if len < 16 || at + len > used {
            break;
        }
        let a = &rec[at..at + len];
        let non_resident = a[8] != 0;
        let name_len = a[9];
        match kind {
            ATTR_STANDARD_INFORMATION if !non_resident => {
                if let Some(v) = resident_value(a) {
                    r.created = u64_at(v, 0).unwrap_or(0);
                    r.modified = u64_at(v, 8).unwrap_or(0);
                    r.attrs = u32_at(v, 0x20).unwrap_or(0);
                }
            }
            ATTR_FILE_NAME if !non_resident => {
                if let Some((n, ns)) = resident_value(a).and_then(file_name) {
                    if ns == NAMESPACE_DOS {
                        dos.push(n)
                    } else {
                        r.names.push(n)
                    }
                }
            }
            // the unnamed data stream (named ones are alternate data streams)
            ATTR_DATA if name_len == 0 => {
                r.has_size = true;
                r.size = if non_resident {
                    // only the first piece of a data attribute split over records says the size (its starting VCN is 0)
                    if u64_at(a, 0x10).unwrap_or(1) == 0 {
                        u64_at(a, 0x30).unwrap_or(0)
                    } else {
                        r.size
                    }
                } else {
                    u32_at(a, 0x10).unwrap_or(0) as u64
                };
            }
            _ => {}
        }
        at += len;
    }
    // a DOS name counts only when there is no other (a file created with an 8.3 name only)
    if r.names.is_empty() {
        r.names = dos;
    }
    Some(r)
}

fn resident_value(a: &[u8]) -> Option<&[u8]> {
    let len = u32_at(a, 0x10)? as usize;
    let off = u16_at(a, 0x14)? as usize;
    a.get(off..off + len)
}

/// A $FILE_NAME value: the parent's record number, the name and its namespace.
fn file_name(v: &[u8]) -> Option<(Name, u8)> {
    let parent = u64_at(v, 0)? & REF_MASK;
    let chars = *v.get(0x40)? as usize;
    let ns = *v.get(0x41)?;
    let raw = v.get(0x42..0x42 + chars * 2)?;
    let units: Vec<u16> = raw
        .as_chunks::<2>()
        .0
        .iter()
        .map(|c| u16::from_le_bytes(*c))
        .collect();
    Some((
        Name {
            parent,
            name: String::from_utf16_lossy(&units),
        },
        ns,
    ))
}

/// The data runs of a non-resident attribute: (first cluster on the volume, number of clusters) for each piece, in order. A sparse
/// piece (no clusters on the disk) has `None`. `None` overall for a malformed run list.
pub fn runs(list: &[u8]) -> Option<Vec<(Option<u64>, u64)>> {
    let mut out = Vec::new();
    let (mut i, mut lcn) = (0usize, 0i64);
    while let Some(&head) = list.get(i) {
        if head == 0 {
            return Some(out);
        }
        let (len_size, off_size) = ((head & 0x0F) as usize, (head >> 4) as usize);
        if len_size == 0 || len_size > 8 || off_size > 8 {
            return None;
        }
        let len_bytes = list.get(i + 1..i + 1 + len_size)?;
        let count = len_bytes
            .iter()
            .rev()
            .fold(0u64, |v, b| (v << 8) | *b as u64);
        let start = if off_size == 0 {
            None
        } else {
            let off_bytes = list.get(i + 1 + len_size..i + 1 + len_size + off_size)?;
            // signed, little-endian, relative to the previous piece's start
            let mut delta = off_bytes
                .iter()
                .rev()
                .fold(0i64, |v, b| (v << 8) | *b as i64);
            if off_bytes.last().is_some_and(|b| b & 0x80 != 0) {
                delta -= 1i64 << (8 * off_size);
            }
            lcn = lcn.checked_add(delta)?;
            Some(u64::try_from(lcn).ok()?)
        };
        out.push((start, count));
        i += 1 + len_size + off_size;
    }
    None
}

/// The run list of the unnamed data attribute of a record (the $MFT's own record tells where the table lies on the disk).
pub fn data_runs(rec: &[u8]) -> Option<Vec<(Option<u64>, u64)>> {
    let used = (u32_at(rec, 0x18)? as usize).min(rec.len());
    let mut at = u16_at(rec, 0x14)? as usize;
    while at + 16 <= used {
        let kind = u32_at(rec, at)?;
        let len = u32_at(rec, at + 4)? as usize;
        if kind == ATTR_END || len < 16 || at + len > used {
            return None;
        }
        let a = &rec[at..at + len];
        if kind == ATTR_DATA && a[9] == 0 && a[8] != 0 {
            let off = u16_at(a, 0x20)? as usize;
            return runs(a.get(off..)?);
        }
        at += len;
    }
    None
}

/// One entry of the volume, by its record number in [`Table::entries`]: what the index and the filters need, kept small (a C: drive
/// has some five million records).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Entry {
    /// The record's sequence number (with the number, the file id the change journal names it by).
    pub seq: u16,
    /// [`Entry::USED`], [`Entry::DIR`].
    pub flags: u8,
    /// FILE_ATTRIBUTE_* bits.
    pub attrs: u32,
    pub size: u64,
    /// Last written, as a FILETIME.
    pub modified: u64,
}

impl Entry {
    pub const USED: u8 = 1;
    pub const DIR: u8 = 2;
    /// The size came from this entry's own record (an extension record's size does not overwrite it).
    const SIZED: u8 = 4;

    pub fn used(&self) -> bool {
        self.flags & Self::USED != 0
    }

    pub fn dir(&self) -> bool {
        self.flags & Self::DIR != 0
    }
}

/// One name of an entry in a folder (an entry with hard links has several).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Link {
    pub record: u32,
    pub parent: u32,
    off: u32,
    len: u32,
}

/// The whole table: entries by record number, their names, extension records already merged into their base records (an entry with
/// many names or a fragmented file keeps attributes in further records).
#[derive(Default)]
pub struct Table {
    pub entries: Vec<Entry>,
    pub links: Vec<Link>,
    pool: String,
}

impl Table {
    /// Adds a parsed record (in any order: an extension record may come before its base).
    pub fn add(&mut self, r: Record) {
        let Ok(number) = u32::try_from(r.base.unwrap_or(r.number)) else {
            return;
        };
        let n = number as usize;
        if self.entries.len() <= n {
            self.entries.resize(n + 1, Entry::default());
        }
        let e = &mut self.entries[n];
        if r.base.is_none() {
            e.seq = r.seq;
            e.flags |= Entry::USED | if r.dir { Entry::DIR } else { 0 };
            e.attrs = r.attrs;
            e.modified = r.modified;
            if r.has_size {
                e.size = r.size;
                e.flags |= Entry::SIZED;
            }
        } else if r.has_size && e.flags & Entry::SIZED == 0 && e.size == 0 {
            e.size = r.size;
        }
        for name in r.names {
            let Ok(parent) = u32::try_from(name.parent) else {
                continue;
            };
            let off = self.pool.len() as u32;
            self.pool.push_str(&name.name);
            self.links.push(Link {
                record: number,
                parent,
                off,
                len: name.name.len() as u32,
            });
        }
    }

    pub fn name(&self, l: &Link) -> &str {
        &self.pool[l.off as usize..(l.off + l.len) as usize]
    }

    /// The file reference (file id) of record `number`: the number with its sequence number on top.
    pub fn file_id(&self, number: u32) -> u64 {
        number as u64 | ((self.entries.get(number as usize).map_or(0, |e| e.seq) as u64) << 48)
    }

    /// The links of each folder: `(starts, order)` where folder `p`'s links are `order[starts[p]..starts[p + 1]]` (indexes into
    /// [`Table::links`]).
    pub fn children(&self) -> (Vec<u32>, Vec<u32>) {
        let n = self.entries.len();
        let mut starts = vec![0u32; n + 2];
        for l in &self.links {
            if (l.parent as usize) < n {
                starts[l.parent as usize + 2] += 1;
            }
        }
        for i in 2..starts.len() {
            starts[i] += starts[i - 1];
        }
        let mut order = vec![0u32; starts[n + 1] as usize];
        for (k, l) in self.links.iter().enumerate() {
            if (l.parent as usize) < n {
                let at = &mut starts[l.parent as usize + 1];
                order[*at as usize] = k as u32;
                *at += 1;
            }
        }
        starts.pop();
        (starts, order)
    }

    /// The memory the table holds.
    pub fn memory(&self) -> usize {
        self.entries.capacity() * std::mem::size_of::<Entry>()
            + self.links.capacity() * std::mem::size_of::<Link>()
            + self.pool.capacity()
    }
}

/// Reads the whole MFT of a volume (`C:`, a drive letter with its colon) into a [`Table`]. Needs administrator rights (the volume is
/// opened for reading); `cancel` stops it. The records are read in large sequential pieces, the way the disk is fastest.
pub fn read_volume(volume: &str, cancel: &std::sync::atomic::AtomicBool) -> std::io::Result<Table> {
    use std::io::{Error, ErrorKind};
    use std::os::windows::fs::{FileExt, OpenOptionsExt};
    let file = std::fs::OpenOptions::new()
        .read(true)
        .share_mode(7)
        .open(format!(r"\\.\{volume}"))?;
    // reads on a volume go by whole sectors into memory aligned to them
    let mut boot = Aligned::new(4096);
    file.seek_read(boot.slice(4096), 0)?;
    let b = Boot::parse(boot.slice(4096))
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, "not an NTFS volume"))?;
    let rs = b.record_size as usize;
    let first_len = rs.div_ceil(b.bytes_per_sector as usize) * b.bytes_per_sector as usize;
    let mut first = Aligned::new(first_len.max(4096));
    file.seek_read(
        first.slice(first_len),
        b.mft_lcn * b.bytes_per_cluster as u64,
    )?;
    let rec0 = &mut first.slice(first_len)[..rs];
    if !fixup(rec0, b.bytes_per_sector as usize) {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "the MFT's first record is damaged",
        ));
    }
    let mft = parse_record(rec0, 0).ok_or_else(|| {
        Error::new(
            ErrorKind::InvalidData,
            "the MFT's first record is not in use",
        )
    })?;
    let pieces = data_runs(rec0).ok_or_else(|| {
        Error::new(
            ErrorKind::InvalidData,
            "the MFT's data runs could not be read",
        )
    })?;
    let cluster = b.bytes_per_cluster as u64;
    // records beyond the table's size are not records yet
    let total = (mft.size / rs as u64) as usize;
    let mut t = Table { entries: vec![Entry::default(); total], links: Vec::with_capacity(total + total / 8), pool: String::with_capacity(total * 12) };
    // The disk reads the next piece while the one before is parsed, and a piece is parsed on every core: one thread doing both took
    // 9 s for a C: drive of 5.4 million records, the disk alone can read the table in about two.
    const CHUNK: usize = 16 << 20;
    let sector = b.bytes_per_sector as usize;
    let (tx, rx) = std::sync::mpsc::sync_channel::<std::io::Result<(usize, Aligned, usize)>>(3);
    let read_all = move || -> std::io::Result<()> {
        let mut number = 0usize;
        for (start, count) in pieces {
            let mut left = count * cluster;
            let mut at = start.map(|s| s * cluster);
            while left > 0 && number < total {
                if cancel.load(std::sync::atomic::Ordering::Relaxed) {
                    return Err(Error::new(ErrorKind::Interrupted, "cancelled"));
                }
                let len = (left as usize).min(CHUNK);
                let Some(pos) = at else {
                    // a sparse piece holds no records
                    number += len / rs;
                    left -= len as u64;
                    continue;
                };
                let mut buf = Aligned::new(len);
                let got = file.seek_read(buf.slice(len), pos)?;
                if got == 0 {
                    return Ok(());
                }
                let first = number;
                number += got / rs;
                if tx.send(Ok((first, buf, got))).is_err() {
                    return Ok(());
                }
                left -= got as u64;
                at = Some(pos + got as u64);
            }
        }
        Ok(())
    };
    std::thread::scope(|sc| -> std::io::Result<()> {
        let reader = sc.spawn(read_all);
        for piece in rx {
            let (first, mut buf, got) = piece?;
            use rayon::prelude::*;
            let records: Vec<Record> = buf
                .slice(got)
                .par_chunks_exact_mut(rs)
                .enumerate()
                .filter_map(|(i, rec)| {
                    let n = first + i;
                    (n < total && fixup(rec, sector)).then(|| parse_record(rec, n as u64)).flatten()
                })
                .collect();
            for r in records {
                t.add(r);
            }
        }
        reader.join().unwrap_or_else(|e| std::panic::resume_unwind(e))
    })?;
    Ok(t)
}

/// A buffer aligned to 4096 bytes (any sector size divides it).
struct Aligned {
    mem: Vec<u8>,
    start: usize,
}

impl Aligned {
    fn new(len: usize) -> Aligned {
        let mem = vec![0u8; len + 4096];
        let start = mem.as_ptr().align_offset(4096);
        Aligned { mem, start }
    }

    fn slice(&mut self, len: usize) -> &mut [u8] {
        &mut self.mem[self.start..self.start + len]
    }
}

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

    /// The first records' numbers on every NTFS volume: the root folder is record 5.
    pub const ROOT: u64 = 5;

    /// A record made by hand: `attrs` are (type, non-resident, attribute name length, body after the 16-byte header), laid out as
    /// NTFS does, with the update sequence applied as on the disk (sector size 512, record 1024).
    pub fn make_record(flags: u16, base: u64, attrs: &[(u32, Vec<u8>)]) -> Vec<u8> {
        let mut r = vec![0u8; 1024];
        r[0..4].copy_from_slice(b"FILE");
        r[4..6].copy_from_slice(&0x30u16.to_le_bytes()); // update sequence array at 0x30
        r[6..8].copy_from_slice(&3u16.to_le_bytes()); // 1 check value + 2 sectors
        r[0x14..0x16].copy_from_slice(&0x38u16.to_le_bytes()); // first attribute
        r[0x16..0x18].copy_from_slice(&flags.to_le_bytes());
        r[0x20..0x28].copy_from_slice(&base.to_le_bytes());
        let mut at = 0x38usize;
        for (kind, a) in attrs {
            r[at..at + a.len()].copy_from_slice(a);
            r[at..at + 4].copy_from_slice(&kind.to_le_bytes());
            at += a.len();
        }
        r[at..at + 4].copy_from_slice(&ATTR_END.to_le_bytes());
        r[0x18..0x1C].copy_from_slice(&((at + 8) as u32).to_le_bytes());
        // the update sequence: check value 0x0A0B, the real last two bytes of each sector kept in the array
        r[0x30..0x32].copy_from_slice(&[0x0B, 0x0A]);
        for i in 1..=2 {
            let end = i * 512;
            let real = [r[end - 2], r[end - 1]];
            r[0x30 + i * 2] = real[0];
            r[0x30 + i * 2 + 1] = real[1];
            r[end - 2] = 0x0B;
            r[end - 1] = 0x0A;
        }
        r
    }

    /// A resident attribute: 24-byte header, value at 0x18.
    pub fn resident(value: &[u8], name_len: u8) -> Vec<u8> {
        let len = (0x18 + value.len()).div_ceil(8) * 8;
        let mut a = vec![0u8; len];
        a[4..8].copy_from_slice(&(len as u32).to_le_bytes());
        a[9] = name_len;
        a[0x10..0x14].copy_from_slice(&(value.len() as u32).to_le_bytes());
        a[0x14..0x16].copy_from_slice(&0x18u16.to_le_bytes());
        a[0x18..0x18 + value.len()].copy_from_slice(value);
        a
    }

    pub fn std_info(created: u64, modified: u64, attrs: u32) -> Vec<u8> {
        let mut v = vec![0u8; 0x30];
        v[0..8].copy_from_slice(&created.to_le_bytes());
        v[8..16].copy_from_slice(&modified.to_le_bytes());
        v[0x20..0x24].copy_from_slice(&attrs.to_le_bytes());
        resident(&v, 0)
    }

    pub fn file_name_attr(parent: u64, name: &str, ns: u8) -> Vec<u8> {
        let units: Vec<u16> = name.encode_utf16().collect();
        let mut v = vec![0u8; 0x42 + units.len() * 2];
        // (a sequence number in the high 16 bits, as on the disk: it must be masked off)
        v[0..8].copy_from_slice(&(parent | (7u64 << 48)).to_le_bytes());
        v[0x40] = units.len() as u8;
        v[0x41] = ns;
        for (i, u) in units.iter().enumerate() {
            v[0x42 + i * 2..0x44 + i * 2].copy_from_slice(&u.to_le_bytes());
        }
        resident(&v, 0)
    }

    pub fn non_resident_data(size: u64, start_vcn: u64, run_list: &[u8]) -> Vec<u8> {
        let len = (0x40 + run_list.len()).div_ceil(8) * 8;
        let mut a = vec![0u8; len];
        a[4..8].copy_from_slice(&(len as u32).to_le_bytes());
        a[8] = 1;
        a[0x10..0x18].copy_from_slice(&start_vcn.to_le_bytes());
        a[0x20..0x22].copy_from_slice(&0x40u16.to_le_bytes());
        a[0x30..0x38].copy_from_slice(&size.to_le_bytes());
        a[0x40..0x40 + run_list.len()].copy_from_slice(run_list);
        a
    }

    fn parse(mut rec: Vec<u8>, number: u64) -> Option<Record> {
        assert!(fixup(&mut rec, 512), "the update sequence checks");
        parse_record(&rec, number)
    }

    #[test]
    fn a_boot_sector_tells_the_layout() {
        let mut b = vec![0u8; 512];
        b[3..11].copy_from_slice(b"NTFS    ");
        b[0x0B..0x0D].copy_from_slice(&512u16.to_le_bytes());
        b[0x0D] = 8; // 4 KB clusters
        b[0x30..0x38].copy_from_slice(&786_432u64.to_le_bytes());
        b[0x40] = (-10i8) as u8; // 1024-byte records
        assert_eq!(
            Boot::parse(&b),
            Some(Boot {
                bytes_per_sector: 512,
                bytes_per_cluster: 4096,
                mft_lcn: 786_432,
                record_size: 1024
            })
        );
        b[0x0D] = 0xF4; // 2^12 sectors per cluster written negative: 2 MB clusters
        assert_eq!(
            Boot::parse(&b).map(|x| x.bytes_per_cluster),
            Some(2 * 1024 * 1024)
        );
        b[3] = b'F';
        assert_eq!(Boot::parse(&b), None, "another file system");
    }

    #[test]
    fn a_damaged_sector_is_refused() {
        let mut rec = make_record(FLAG_IN_USE, 0, &[]);
        rec[1023] ^= 0xFF;
        assert!(!fixup(&mut rec, 512));
    }

    #[test]
    fn a_file_gives_its_name_folder_size_and_dates() {
        let rec = make_record(
            FLAG_IN_USE,
            0,
            &[
                (ATTR_STANDARD_INFORMATION, std_info(111, 222, 0x20)),
                (
                    ATTR_FILE_NAME,
                    file_name_attr(ROOT, "RAPOR~1.TXT", NAMESPACE_DOS),
                ),
                (ATTR_FILE_NAME, file_name_attr(ROOT, "rapor 2026.txt", 1)),
                (ATTR_DATA, resident(b"hello", 0)),
            ],
        );
        let r = parse(rec, 40).unwrap();
        assert_eq!(
            r.names,
            vec![Name {
                parent: ROOT,
                name: "rapor 2026.txt".into()
            }],
            "the short name is left out"
        );
        assert_eq!(
            (r.size, r.created, r.modified, r.attrs, r.dir),
            (5, 111, 222, 0x20, false)
        );
    }

    #[test]
    fn hard_links_and_folders_and_streams() {
        let rec = make_record(
            FLAG_IN_USE | FLAG_DIRECTORY,
            0,
            &[
                (ATTR_FILE_NAME, file_name_attr(ROOT, "Belgeler", 1)),
                (ATTR_FILE_NAME, file_name_attr(9, "Docs", 0)),
            ],
        );
        let r = parse(rec, 41).unwrap();
        assert!(r.dir);
        assert_eq!(r.names.len(), 2, "both links");
        // a named stream (Zone.Identifier) is not the file's size; the unnamed one, non-resident, is
        let rec = make_record(
            FLAG_IN_USE,
            0,
            &[
                (ATTR_FILE_NAME, file_name_attr(ROOT, "film.mkv", 1)),
                (ATTR_DATA, resident(b"ZoneId=3", 15)),
                (
                    ATTR_DATA,
                    non_resident_data(4_000_000_000, 0, &[0x11, 0x10, 0x20, 0x00]),
                ),
            ],
        );
        assert_eq!(parse(rec, 42).unwrap().size, 4_000_000_000);
    }

    #[test]
    fn a_free_record_is_nothing() {
        assert_eq!(
            parse(
                make_record(
                    0,
                    0,
                    &[(ATTR_FILE_NAME, file_name_attr(ROOT, "gone.txt", 1))]
                ),
                43
            ),
            None
        );
    }

    #[test]
    fn extension_records_are_merged_into_their_base() {
        let mut t = Table::default();
        // the extension first: records are read in number order, but a base may have a higher number than its extension
        t.add(
            parse(
                make_record(
                    FLAG_IN_USE,
                    50,
                    &[
                        (
                            ATTR_DATA,
                            non_resident_data(9_999, 0, &[0x11, 0x01, 0x05, 0x00]),
                        ),
                        (ATTR_FILE_NAME, file_name_attr(9, "link.bin", 1)),
                    ],
                ),
                49,
            )
            .unwrap(),
        );
        t.add(
            parse(
                make_record(
                    FLAG_IN_USE,
                    0,
                    &[
                        (ATTR_STANDARD_INFORMATION, std_info(1, 2, 0x20)),
                        (ATTR_FILE_NAME, file_name_attr(ROOT, "big.bin", 1)),
                    ],
                ),
                50,
            )
            .unwrap(),
        );
        assert_eq!(
            t.entries[50],
            Entry {
                seq: 0,
                flags: Entry::USED,
                attrs: 0x20,
                size: 9_999,
                modified: 2
            }
        );
        assert!(
            !t.entries[49].used(),
            "the extension is no entry of its own"
        );
        let names: Vec<_> = t
            .links
            .iter()
            .map(|l| (l.record, l.parent, t.name(l)))
            .collect();
        assert_eq!(
            names,
            vec![(50, 9, "link.bin"), (50, ROOT as u32, "big.bin")]
        );
        let (starts, order) = t.children();
        let root_children: Vec<_> = order
            [starts[ROOT as usize] as usize..starts[ROOT as usize + 1] as usize]
            .iter()
            .map(|&k| t.name(&t.links[k as usize]))
            .collect();
        assert_eq!(root_children, vec!["big.bin"]);
    }

    #[test]
    fn data_runs_decode_relative_and_sparse_pieces() {
        // 0x10 clusters at 0x20; then 0x08 clusters 0x10 back (at 0x10, a negative offset); then a sparse piece of 4
        assert_eq!(
            runs(&[0x11, 0x10, 0x20, 0x11, 0x08, 0xF0, 0x01, 0x04, 0x00]),
            Some(vec![(Some(0x20), 0x10), (Some(0x10), 0x08), (None, 4)])
        );
        assert_eq!(runs(&[0x11, 0x10]), None, "cut short");
        let rec = make_record(
            FLAG_IN_USE,
            0,
            &[(
                ATTR_DATA,
                non_resident_data(1 << 20, 0, &[0x21, 0x40, 0x00, 0x01, 0x00]),
            )],
        );
        let mut rec = rec;
        assert!(fixup(&mut rec, 512));
        assert_eq!(data_runs(&rec), Some(vec![(Some(0x100), 0x40)]));
    }
}