Merge pull request #53 from joshgosse/scan-speed

Improves scan speed on macOS, better memory profile everywhere
This commit is contained in:
Tobias Lütke
2026-10-04 13:03:18 -04:00
committed by GitHub
7 changed files with 786 additions and 78 deletions
+14 -7
View File
@@ -62,18 +62,24 @@ and `cargo build --release` directly; CI runs the gate on both systems.
## Invariants
1. **Sizes come from `st_blocks * 512` unless apparent size was asked for.**
That is the number that comes back when a file is deleted. On Windows it
is the allocation the directory listing reports; see `windows.rs`. An
That is the number that comes back when a file is deleted. On macOS the
directory listing reports it and `st_size` for a whole buffer of entries:
every fork's allocation, and the data fork's length; see `macos.rs`. On
Windows it is the allocation the directory listing reports; see
`windows.rs`. An
elevated scan of a whole NTFS drive reads it from the master file table
instead, keeping the walk's rules for hidden entries, links, cloud
folders and depth; see `mft.rs`. That path counts every stream's
allocation, alternate data streams included since they go when the file
goes, so for a file with alternate streams it can exceed the walk's
number.
2. **`own_bytes`/`own_files` are derived, never tracked.** `tree::aggregate`
computes the totals from the children. Hardlink de-duplication zeroes a
duplicate leaf's weight while that pass runs; anything that patches
`bytes` directly will be overwritten.
2. **Totals are derived, never tracked.** A leaf's `bytes` is the only
input: `tree::aggregate` computes every directory's `bytes`, `files` and
`dirs` from its children, and `own_bytes()`/`own_files()` read the direct
children when asked. Hardlink de-duplication zeroes a duplicate leaf's
`bytes` while that pass runs; anything that patches a directory's `bytes`
directly will be overwritten. `Node` is paid for tens of millions of
times, so `a_node_stays_small` holds its size.
3. **A directory is only built when its own scan *and* every subdirectory task
has finished.** That is the `+1` sentinel in `PendingDir::pending`. Building
early silently drops whole subtrees — it has happened once.
@@ -106,7 +112,8 @@ and `cargo build --release` directly; CI runs the gate on both systems.
| tile geometry, nesting, the merged tail | `crates/disktree-core/src/treemap.rs` |
| anything that deletes, or refuses to | `crates/disktree-core/src/removal.rs` |
| free space and projections | `crates/disktree-core/src/space.rs` |
| what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — the only `unsafe` |
| what macOS lists and measures in bulk | `crates/disktree-core/src/macos.rs` — `unsafe` for `getattrlistbulk` |
| what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — `unsafe` for Win32 |
| reading a whole NTFS drive from its file table | `crates/disktree-core/src/mft.rs` |
| a key, a screen transition, a mark | `crates/disktree-app/src/state.rs` |
| spacing, type and size | `crates/disktree-app/src/ui.rs` — tokens only, no `px` in layout |
+4 -3
View File
@@ -1212,7 +1212,7 @@ fn scan_totals(app: &Disktree, theme: &Theme) -> Div {
let tree = app.tree();
let bytes = tree.map_or(app.progress.bytes, |node| node.bytes);
let files = tree.map_or(app.progress.files, |node| node.files);
let dirs = tree.map_or(app.progress.dirs, |node| node.dirs);
let dirs = tree.map_or(app.progress.dirs, |node| u64::from(node.dirs));
let errors = app.progress.errors;
div()
.flex()
@@ -3408,9 +3408,10 @@ fn node_card(
"{} files · {} dirs · {} direct",
widgets::human_count(node.files),
widgets::human_count(
node.dirs.saturating_sub(u64::from(node.is_dir()))
u64::from(node.dirs)
.saturating_sub(u64::from(node.is_dir()))
),
human_bytes(node.own_bytes)
human_bytes(node.own_bytes())
)),
);
+2
View File
@@ -10,6 +10,8 @@ pub mod classify;
pub mod export;
pub mod filter;
pub mod insights;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod mft;
pub mod removal;
+619
View File
@@ -0,0 +1,619 @@
//! What a walk on macOS needs beyond the standard library.
//!
//! `std::fs::read_dir` lists a directory with `readdir`, whose records carry
//! a name and a type, and `DirEntry::metadata` is then an `lstat` of each
//! entry's full path. `getattrlistbulk(2)` returns every entry's size,
//! identity, age and flags for a whole buffer of entries, without the kernel
//! setting up per-file state for each one as a stat must.
#![allow(
unsafe_code,
reason = "getattrlistbulk, which neither std nor rustix wraps; each block \
says why it is sound"
)]
use std::cell::RefCell;
use std::ffi::{OsStr, c_int, c_void};
use std::io;
use std::os::fd::{AsRawFd as _, OwnedFd};
use std::os::unix::ffi::OsStrExt as _;
use std::path::{Path, PathBuf};
use rustix::fs::{AtFlags, FileType, Mode, OFlags};
/// Bytes the kernel fills per call: some hundreds of entries.
const BUFFER_BYTES: usize = 64 * 1024;
// From <sys/attr.h> and <sys/vnode.h>, which the libc crate does not cover.
const ATTR_BIT_MAP_COUNT: u16 = 5;
const ATTR_CMN_NAME: u32 = 0x0000_0001;
const ATTR_CMN_DEVID: u32 = 0x0000_0002;
const ATTR_CMN_OBJTYPE: u32 = 0x0000_0008;
const ATTR_CMN_MODTIME: u32 = 0x0000_0400;
const ATTR_CMN_FLAGS: u32 = 0x0004_0000;
const ATTR_CMN_FILEID: u32 = 0x0200_0000;
const ATTR_CMN_ERROR: u32 = 0x2000_0000;
const ATTR_CMN_RETURNED_ATTRS: u32 = 0x8000_0000;
const ATTR_FILE_LINKCOUNT: u32 = 0x0000_0001;
/// Every fork, which is what `st_blocks` counts: a resource fork is on the
/// disk too.
const ATTR_FILE_ALLOCSIZE: u32 = 0x0000_0004;
/// The data fork alone, which is what `st_size` is.
const ATTR_FILE_DATALENGTH: u32 = 0x0000_0200;
const VREG: u32 = 1;
const VDIR: u32 = 2;
const VLNK: u32 = 5;
/// `SF_DATALESS` from <sys/stat.h>.
const SF_DATALESS: u32 = 0x4000_0000;
const COMMON_ATTRIBUTES: u32 = ATTR_CMN_RETURNED_ATTRS
| ATTR_CMN_NAME
| ATTR_CMN_DEVID
| ATTR_CMN_OBJTYPE
| ATTR_CMN_MODTIME
| ATTR_CMN_FLAGS
| ATTR_CMN_FILEID
| ATTR_CMN_ERROR;
const FILE_ATTRIBUTES: u32 =
ATTR_FILE_LINKCOUNT | ATTR_FILE_ALLOCSIZE | ATTR_FILE_DATALENGTH;
/// What [`Cursor::entry`] reads after the name; a file system may leave
/// any of them out.
const MEASURED: u32 = ATTR_CMN_DEVID
| ATTR_CMN_OBJTYPE
| ATTR_CMN_MODTIME
| ATTR_CMN_FLAGS
| ATTR_CMN_FILEID;
#[repr(C)]
struct AttrList {
bitmapcount: u16,
reserved: u16,
commonattr: u32,
volattr: u32,
dirattr: u32,
fileattr: u32,
forkattr: u32,
}
unsafe extern "C" {
fn getattrlistbulk(
dirfd: c_int,
attr_list: *mut AttrList,
attr_buf: *mut c_void,
attr_buf_size: usize,
options: u64,
) -> c_int;
}
thread_local! {
/// The last finished listing's buffer, for the next one on this thread:
/// a walk lists millions of directories, one at a time per thread.
static SPARE: RefCell<Option<Box<[u64]>>> = const { RefCell::new(None) };
}
/// What an entry is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Directory,
Link,
File,
/// A FIFO, a socket or a device node.
Other,
}
/// One directory entry, with what a measurement needs.
#[derive(Debug)]
pub struct Entry {
name: Box<str>,
/// The name as the file system spells it, only when `name` could not:
/// a name that is not UTF-8 is shown lossy but must still open.
exact: Option<Box<OsStr>>,
kind: Kind,
apparent: u64,
allocated: u64,
modified: i64,
device: u64,
inode: u64,
links: u32,
flags: u32,
}
impl Entry {
/// The entry's path inside `dir`, the directory it was listed from.
pub fn path(&self, dir: &Path) -> PathBuf {
dir.join(self.file_name())
}
pub fn file_name(&self) -> &OsStr {
self.exact
.as_deref()
.unwrap_or_else(|| OsStr::new(&*self.name))
}
/// The name as text; see [`Self::file_name`] for what it may lose.
pub fn name(&self) -> &str {
&self.name
}
/// The name, moved out: the tree keeps it, so nothing copies it. The
/// entry's other accessors keep working; `name`, `file_name` and
/// `path` do not.
pub fn take_name(&mut self) -> Box<str> {
std::mem::take(&mut self.name)
}
pub const fn kind(&self) -> Kind {
self.kind
}
/// `st_size`.
pub const fn apparent(&self) -> u64 {
self.apparent
}
/// `st_blocks * 512`.
pub const fn allocated(&self) -> u64 {
self.allocated
}
/// Last write, in Unix seconds.
pub const fn modified(&self) -> i64 {
self.modified
}
/// `(st_dev, st_ino)`: the same for two names of one file.
pub const fn identity(&self) -> (u64, u64) {
(self.device, self.inode)
}
pub const fn device(&self) -> u64 {
self.device
}
/// Whether the file has more than one name.
pub const fn shared(&self) -> bool {
self.links > 1
}
/// Whether this is a directory iCloud Drive or a File Provider has
/// evicted, which listing would make it fetch.
pub const fn evicted(&self) -> bool {
matches!(self.kind, Kind::Directory) && self.flags & SF_DATALESS != 0
}
fn named(name: &[u8]) -> (Box<str>, Option<Box<OsStr>>) {
match std::str::from_utf8(name) {
Ok(text) => (text.into(), None),
Err(_) => (
String::from_utf8_lossy(name).into(),
Some(OsStr::from_bytes(name).into()),
),
}
}
fn from_stat(name: &[u8], stat: &rustix::fs::Stat) -> Self {
let (name, exact) = Self::named(name);
let kind = match FileType::from_raw_mode(stat.st_mode) {
FileType::Directory => Kind::Directory,
FileType::Symlink => Kind::Link,
FileType::RegularFile => Kind::File,
_ => Kind::Other,
};
Self {
name,
exact,
kind,
apparent: stat.st_size.max(0) as u64,
allocated: (stat.st_blocks.max(0) as u64).saturating_mul(512),
modified: stat.st_mtime,
device: i64::from(stat.st_dev).cast_unsigned(),
inode: stat.st_ino,
links: u32::from(stat.st_nlink),
flags: stat.st_flags,
}
}
}
/// A directory being listed; like `std::fs::ReadDir`, it leaves out `.`
/// and `..`.
#[derive(Debug)]
pub struct ReadDir {
fd: OwnedFd,
/// `u64`s for alignment; the records themselves are 4-byte aligned.
buffer: Option<Box<[u64]>>,
/// Records in the buffer not yet handed out.
remaining: u32,
/// Where the next of them starts.
offset: usize,
done: bool,
}
/// List `dir`, with each entry's size, identity and age. A link at `dir`
/// itself is followed, as `std::fs::read_dir` follows it.
pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
let fd = rustix::fs::open(
dir,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?;
let buffer = SPARE
.with_borrow_mut(Option::take)
.unwrap_or_else(|| vec![0; BUFFER_BYTES / 8].into_boxed_slice());
Ok(ReadDir {
fd,
buffer: Some(buffer),
remaining: 0,
offset: 0,
done: false,
})
}
impl Drop for ReadDir {
fn drop(&mut self) {
if let Some(buffer) = self.buffer.take() {
SPARE.with_borrow_mut(|spare| *spare = Some(buffer));
}
}
}
impl Iterator for ReadDir {
type Item = io::Result<Entry>;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
if self.done {
return None;
}
match self.fill() {
Ok(0) => {
self.done = true;
return None;
}
Ok(count) => {
self.remaining = count;
self.offset = 0;
}
Err(error) => {
self.done = true;
return Some(Err(error));
}
}
}
self.remaining -= 1;
match self.record() {
Ok((entry, length)) => {
self.offset += length;
Some(entry)
}
Err(error) => {
self.remaining = 0;
self.done = true;
Some(Err(error))
}
}
}
}
impl ReadDir {
/// Ask the kernel for the next buffer of records; how many it wrote.
fn fill(&mut self) -> io::Result<u32> {
let buffer = self.buffer.as_mut().expect("held until drop");
let mut request = AttrList {
bitmapcount: ATTR_BIT_MAP_COUNT,
reserved: 0,
commonattr: COMMON_ATTRIBUTES,
volattr: 0,
dirattr: 0,
fileattr: FILE_ATTRIBUTES,
forkattr: 0,
};
loop {
// SAFETY: the descriptor is an open directory owned by `self`;
// `request` is a valid attrlist for the call's duration; and the
// pointer and length describe `buffer`, which is writable for
// that many bytes and not otherwise borrowed during the call.
let count = unsafe {
getattrlistbulk(
self.fd.as_raw_fd(),
&raw mut request,
buffer.as_mut_ptr().cast(),
BUFFER_BYTES,
0,
)
};
if let Ok(count) = u32::try_from(count) {
return Ok(count);
}
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(error);
}
}
}
/// The buffer as the bytes the kernel wrote.
fn bytes(&self) -> &[u8] {
let buffer = self.buffer.as_deref().expect("held until drop");
// SAFETY: `[u64]` can be read as `u8`s of eight times its length:
// one allocation, no alignment requirement for `u8`, and every byte
// initialized, since the buffer starts zeroed.
unsafe {
std::slice::from_raw_parts(
buffer.as_ptr().cast::<u8>(),
size_of_val(buffer),
)
}
}
/// The entry at `self.offset` and the record's length. Every length and
/// offset the kernel wrote is checked against the buffer before it is
/// used.
///
/// Layout per getattrlist(2): a `u32` length, the returned
/// `attribute_set_t`, `ATTR_CMN_ERROR` when it is set, then every other
/// attribute in bit order, each packed at 4-byte alignment.
fn record(&self) -> io::Result<(io::Result<Entry>, usize)> {
let bytes = self.bytes();
let length = read_u32(bytes, self.offset)? as usize;
let record = bytes
.get(self.offset..self.offset + length)
.ok_or_else(malformed)?;
let mut cursor = Cursor { record, at: 4 };
let common = cursor.u32()?;
cursor.at += 8;
let file = cursor.u32()?;
cursor.at += 4;
let error = if common & ATTR_CMN_ERROR == 0 {
0
} else {
cursor.u32()?
};
let name = cursor.name()?;
if error != 0 {
let error = io::Error::from_raw_os_error(error.cast_signed());
return Ok((Err(error), length));
}
let entry = if common & MEASURED == MEASURED {
cursor.entry(file, name)?
} else {
None
};
Ok((entry.map_or_else(|| self.stat(name), Ok), length))
}
/// An entry the file system described only in part, read the ordinary
/// way, relative to the directory already open.
fn stat(&self, name: &[u8]) -> io::Result<Entry> {
let stat =
rustix::fs::statat(&self.fd, name, AtFlags::SYMLINK_NOFOLLOW)?;
Ok(Entry::from_stat(name, &stat))
}
}
fn malformed() -> io::Error {
io::Error::other("the kernel returned a malformed record")
}
fn read_u32(bytes: &[u8], at: usize) -> io::Result<u32> {
let field = at
.checked_add(4)
.and_then(|end| bytes.get(at..end))
.ok_or_else(malformed)?;
Ok(u32::from_ne_bytes(
field.try_into().map_err(|_| malformed())?,
))
}
/// Reads a record's attributes in order; reading past its end is a
/// malformed record.
struct Cursor<'a> {
record: &'a [u8],
at: usize,
}
impl<'a> Cursor<'a> {
fn u32(&mut self) -> io::Result<u32> {
let value = read_u32(self.record, self.at)?;
self.at += 4;
Ok(value)
}
fn u64(&mut self) -> io::Result<u64> {
let field = self
.at
.checked_add(8)
.and_then(|end| self.record.get(self.at..end))
.ok_or_else(malformed)?;
self.at += 8;
Ok(u64::from_ne_bytes(
field.try_into().map_err(|_| malformed())?,
))
}
/// An `attrreference_t`: an offset from itself and a length that counts
/// the terminating NUL.
fn name(&mut self) -> io::Result<&'a [u8]> {
let reference = self.at;
let offset = isize::try_from(self.u32()?.cast_signed())
.map_err(|_| malformed())?;
let length = self.u32()? as usize;
reference
.checked_add_signed(offset)
.zip(length.checked_sub(1))
.and_then(|(start, length)| {
self.record.get(start..start.checked_add(length)?)
})
.ok_or_else(malformed)
}
/// The attributes after the name, every one of them asked for; `None`
/// for a file whose sizes the file system left out.
fn entry(&mut self, file: u32, name: &[u8]) -> io::Result<Option<Entry>> {
let device = self.u32()?.cast_signed();
let kind = match self.u32()? {
VDIR => Kind::Directory,
VLNK => Kind::Link,
VREG => Kind::File,
_ => Kind::Other,
};
let modified = self.u64()?.cast_signed();
self.at += 8;
let flags = self.u32()?;
let inode = self.u64()?;
// A directory's own size is never measured; its entries are.
let (links, allocated, apparent) = if kind == Kind::Directory {
(1, 0, 0)
} else if file & FILE_ATTRIBUTES == FILE_ATTRIBUTES {
(self.u32()?, self.u64()?, self.u64()?)
} else {
return Ok(None);
};
let (name, exact) = Entry::named(name);
Ok(Some(Entry {
name,
exact,
kind,
apparent,
allocated,
modified,
device: i64::from(device).cast_unsigned(),
inode,
links,
flags,
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::os::unix::fs::symlink;
use tempfile::TempDir;
fn listed(dir: &Path) -> Vec<Entry> {
let mut entries: Vec<Entry> = read_dir(dir)
.expect("list")
.collect::<io::Result<_>>()
.expect("entries");
entries.sort_by(|left, right| left.name.cmp(&right.name));
entries
}
/// What `lstat` says of each entry, the way the standard listing reads it.
fn stated(dir: &Path) -> Vec<Entry> {
let mut entries: Vec<Entry> = fs::read_dir(dir)
.expect("list")
.map(|entry| {
let entry = entry.expect("entry");
let stat = rustix::fs::lstat(entry.path()).expect("lstat");
Entry::from_stat(entry.file_name().as_bytes(), &stat)
})
.collect();
entries.sort_by(|left, right| left.name.cmp(&right.name));
entries
}
type Fields = (String, Kind, u64, u64, i64, (u64, u64), bool, bool);
/// What the walk reads of a leaf.
fn fields(entry: &Entry) -> Fields {
(
entry.name.to_string(),
entry.kind,
entry.apparent,
entry.allocated,
entry.modified,
entry.identity(),
entry.shared(),
entry.evicted(),
)
}
#[test]
fn a_listing_has_names_kinds_lengths_and_no_dot_entries() {
let temp = TempDir::new().expect("tempdir");
fs::create_dir(temp.path().join("sub")).expect("mkdir");
fs::write(temp.path().join("data.bin"), vec![7_u8; 100_000])
.expect("write");
symlink("data.bin", temp.path().join("link")).expect("symlink");
let entries = listed(temp.path());
let names: Vec<&OsStr> = entries.iter().map(Entry::file_name).collect();
assert_eq!(names, ["data.bin", "link", "sub"]);
assert_eq!(entries[0].kind(), Kind::File);
assert_eq!(entries[0].apparent(), 100_000);
assert_eq!(entries[0].path(temp.path()), temp.path().join("data.bin"));
assert_eq!(entries[1].kind(), Kind::Link);
assert_eq!(entries[2].kind(), Kind::Directory);
assert!(entries[0].modified() > 0, "written just now");
}
#[test]
fn every_leaf_reads_as_lstat_reads_it() {
let temp = TempDir::new().expect("tempdir");
let root = temp.path();
fs::write(root.join("plain"), b"hi").expect("write");
fs::hard_link(root.join("plain"), root.join("hard")).expect("link");
// Ten megabytes long, nothing written: no blocks.
fs::File::create(root.join("sparse"))
.and_then(|file| file.set_len(10 << 20))
.expect("sparse");
symlink("plain", root.join("link")).expect("symlink");
// A resource fork, which `st_blocks` counts and `st_size` does not.
let forked = root.join("forked");
fs::write(&forked, b"data").expect("write");
rustix::fs::setxattr(
&forked,
"com.apple.ResourceFork",
&vec![b'r'; 20_000],
rustix::fs::XattrFlags::empty(),
)
.expect("resource fork");
let listed: Vec<Fields> = listed(root).iter().map(fields).collect();
let stated: Vec<Fields> = stated(root).iter().map(fields).collect();
assert_eq!(listed, stated);
let forked = listed.iter().find(|leaf| leaf.0 == "forked").unwrap();
assert_eq!(forked.2, 4, "the data fork's length");
assert!(forked.3 >= 20_000, "the fork's blocks: {}", forked.3);
let plain = listed.iter().find(|leaf| leaf.0 == "plain").unwrap();
assert!(plain.6, "two names");
}
#[test]
fn a_directory_larger_than_the_buffer_is_listed_whole() {
let temp = TempDir::new().expect("tempdir");
// About a hundred bytes a record: several fills.
let count = 3 * BUFFER_BYTES / 100;
for index in 0..count {
fs::write(temp.path().join(format!("file-{index:05}")), b"")
.expect("write");
}
let entries = listed(temp.path());
assert_eq!(entries.len(), count);
assert_eq!(entries[0].name(), "file-00000");
assert_eq!(entries[count - 1].name(), format!("file-{:05}", count - 1));
}
#[test]
fn names_are_text_and_open() {
let temp = TempDir::new().expect("tempdir");
for name in ["café", "日本語", "with space", "a\nb"] {
fs::write(temp.path().join(name), b"x").expect("write");
}
let entries = listed(temp.path());
assert_eq!(entries.len(), 4);
for entry in entries {
assert!(entry.exact.is_none(), "{}", entry.name());
assert!(fs::metadata(entry.path(temp.path())).is_ok());
}
}
#[test]
fn a_missing_directory_is_an_error() {
let temp = TempDir::new().expect("tempdir");
let error = read_dir(&temp.path().join("gone")).expect_err("missing");
assert_eq!(error.kind(), io::ErrorKind::NotFound);
}
}
+4 -2
View File
@@ -20,6 +20,7 @@
use std::fs::{File, OpenOptions};
use std::io;
use std::num::NonZeroU64;
use std::os::windows::fs::{FileExt as _, OpenOptionsExt as _};
use std::path::Path;
@@ -1145,7 +1146,8 @@ impl Table<'_> {
let mut node = Node::entry(name, kind, size);
node.modified = info.modified;
if info.names > 1 {
node.inode = Some((0, u64::from(entry.child)));
node.inode = NonZeroU64::new(u64::from(entry.child))
.map(|record| (0, record));
}
Ok(Some(node))
}
@@ -1685,7 +1687,7 @@ mod tests {
assert_eq!(found, expected, "include_hidden {include_hidden}");
// Only a file with a second name needs its identity kept.
let inode = |name: &str| root.child_named(name).unwrap().inode;
let inode = |name: &str| root.child_named(name).unwrap().identity();
assert_eq!(inode("linked.txt"), Some((0, 31)));
assert_eq!(inode("visible.txt"), None);
}
+76 -20
View File
@@ -15,10 +15,11 @@
//! poll without locking, and cooperative cancellation so a re-scan can abandon
//! a walk of a large home directory instead of queueing behind it.
#[cfg(not(windows))]
#[cfg(not(any(windows, target_os = "macos")))]
use std::fs::DirEntry;
use std::fs::{self, Metadata};
use std::io;
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, TryRecvError};
@@ -494,10 +495,12 @@ impl WalkContext {
/// What the walk reads about one directory entry.
///
/// `std::fs::DirEntry` everywhere but Windows. There the standard listing
/// has neither the allocated size nor a file id, so measuring like `du`
/// would cost an open per file; [`crate::windows`] lists a directory with
/// both instead.
/// `std::fs::DirEntry` everywhere but Windows and macOS. On Windows the
/// standard listing has neither the allocated size nor a file id, so
/// measuring like `du` would cost an open per file; [`crate::windows`] lists
/// a directory with both instead. On macOS it would cost an `lstat` per
/// entry, and [`crate::macos`] lists a directory with everything a stat
/// says.
trait Listed {
/// The entry's path inside `dir`, the directory it was listed from.
fn entry_path(&self, dir: &Path) -> PathBuf;
@@ -514,7 +517,8 @@ trait Listed {
fn directory(&self) -> io::Result<Directory>;
/// Hidden by an attribute rather than by a leading dot: on Windows,
/// where the listing carries it, so `AppData` is hidden as Explorer
/// hides it. macOS's `UF_HIDDEN` would cost a stat per entry.
/// hides it. Finder's `UF_HIDDEN` is not asked for: on macOS, hidden
/// means a leading dot, as on Linux.
fn hidden(&self) -> bool {
false
}
@@ -565,13 +569,13 @@ impl Facts {
}
/// A standard directory entry with its name decoded once, up front.
#[cfg(not(windows))]
#[cfg(not(any(windows, target_os = "macos")))]
struct Named {
entry: DirEntry,
name: Box<str>,
}
#[cfg(not(windows))]
#[cfg(not(any(windows, target_os = "macos")))]
impl Listed for Named {
fn entry_path(&self, _dir: &Path) -> PathBuf {
self.entry.path()
@@ -612,6 +616,50 @@ impl Listed for Named {
}
}
#[cfg(target_os = "macos")]
impl Listed for crate::macos::Entry {
fn entry_path(&self, dir: &Path) -> PathBuf {
self.path(dir)
}
fn name(&self) -> &str {
self.name()
}
fn take_name(&mut self) -> Box<str> {
self.take_name()
}
fn listing(&self) -> io::Result<Listing> {
Ok(match self.kind() {
crate::macos::Kind::Link => Listing::Symlink,
crate::macos::Kind::Directory => Listing::Directory,
crate::macos::Kind::File => Listing::Leaf(NodeKind::File),
crate::macos::Kind::Other => Listing::Leaf(NodeKind::Other),
})
}
fn facts(&self, apparent_size: bool) -> io::Result<Facts> {
Ok(Facts {
size: if apparent_size {
self.apparent()
} else {
self.allocated()
},
identity: Some(self.identity()),
modified: self.modified(),
shared: self.shared(),
})
}
fn directory(&self) -> io::Result<Directory> {
Ok(Directory {
device: self.device(),
evicted: self.evicted(),
})
}
}
#[cfg(windows)]
impl Listed for crate::windows::Entry {
fn entry_path(&self, dir: &Path) -> PathBuf {
@@ -665,7 +713,7 @@ impl Listed for crate::windows::Entry {
}
/// List a directory the way [`Listed`] describes.
#[cfg(not(windows))]
#[cfg(not(any(windows, target_os = "macos")))]
fn list(
path: &Path,
_volume: Option<u64>,
@@ -681,6 +729,14 @@ fn list(
}))
}
#[cfg(target_os = "macos")]
fn list(
path: &Path,
_volume: Option<u64>,
) -> io::Result<crate::macos::ReadDir> {
crate::macos::read_dir(path)
}
#[cfg(windows)]
fn list(
path: &Path,
@@ -745,18 +801,16 @@ impl PendingDir {
/// Turn a completed directory into a node. Only called when `pending` has
/// reached zero, so every child is already in `self.partial`.
///
/// `bytes` and `own_bytes` are left at zero on purpose: the walk cannot
/// know the aggregate, and [`crate::tree::aggregate`] derives both from the
/// children once every child is present.
/// `bytes` is left at zero on purpose: the walk cannot know the
/// aggregate, and [`crate::tree::aggregate`] derives it from the children
/// once every child is present.
fn build(&self) -> Node {
let partial = std::mem::take(&mut *lock(&self.partial));
Node {
name: partial.name,
kind: NodeKind::Directory,
bytes: 0,
own_bytes: 0,
files: 0,
own_files: 0,
dirs: 1,
inode: None,
read_error: self.read_error.load(Ordering::Relaxed),
@@ -839,7 +893,7 @@ fn scan_on_pool(
let node = finish_tree(node, &context.options, pool);
// The reader counted every file on the volume; the tree may
// hold fewer.
progress.settle(node.files, node.dirs, node.bytes);
progress.settle(node.files, u64::from(node.dirs), node.bytes);
return Ok(node);
}
// The reader gave up, or never started: the walk counts from nothing.
@@ -956,7 +1010,7 @@ impl Tally {
if node.is_dir() {
// A subtree taken whole from an earlier scan.
self.files += node.files;
self.dirs += node.dirs;
self.dirs += node.dirs as u64;
} else {
// A link counts as a file on the meter, as it always has,
// though the tree does not count it.
@@ -1146,7 +1200,9 @@ fn leaf_node(
) -> Node {
let mut node = Node::entry(name, kind, facts.size);
if track {
node.inode = facts.identity;
node.inode = facts
.identity
.and_then(|(device, file)| Some((device, NonZeroU64::new(file)?)));
}
node.modified = facts.modified;
node
@@ -1454,8 +1510,8 @@ mod tests {
write(root, "sub/deep.bin", 300);
let tree = scan_dir(root, &options());
assert_eq!(tree.own_bytes, 700);
assert_eq!(tree.own_files, 1);
assert_eq!(tree.own_bytes(), 700);
assert_eq!(tree.own_files(), 1);
assert_eq!(tree.bytes, 1000);
assert_eq!(tree.files, 2);
}
@@ -1614,7 +1670,7 @@ mod tests {
..options()
},
);
assert_eq!(tree.own_bytes, 10);
assert_eq!(tree.own_bytes(), 10);
let a = child(&tree, "a");
assert_eq!(
a.bytes, 20,
+67 -46
View File
@@ -1,5 +1,6 @@
//! The scanned tree.
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex, OnceLock};
@@ -54,28 +55,26 @@ impl Metric {
/// One entry in the scanned tree.
///
/// Totals and direct figures are both kept: `own_bytes` and `own_files` are
/// what sits directly in a directory, `bytes` and `files` are the subtree
/// totals the treemap draws. The selection line needs both, and keeping them means
/// no second traversal when one of them is displayed.
/// `bytes` and `files` are the subtree totals the treemap draws; what sits
/// directly in a directory is [`Self::own_bytes`] and [`Self::own_files`],
/// read from its children when the selection line asks. A disk holds tens
/// of millions of nodes, so every field is paid that many times: the size
/// is held by a test.
#[derive(Clone, Debug)]
pub struct Node {
pub name: Box<str>,
pub kind: NodeKind,
/// Subtree total: direct contents plus every descendant.
/// Subtree total: direct contents plus every descendant. A file's own
/// size, or nothing for a second name of a file already charged.
pub bytes: u64,
/// Bytes of the leaf entries directly in this directory, or this file's
/// own size. Derived by [`aggregate`].
pub own_bytes: u64,
/// Files at or beneath this node; `1` for a file.
pub files: u64,
/// Files directly in this directory; `1` for a file. Derived by
/// [`aggregate`].
pub own_files: u64,
/// Directories at or beneath this node; `1` for a directory.
pub dirs: u64,
/// `(device, inode)` for files, used to de-duplicate hardlinks.
pub inode: Option<(u64, u64)>,
/// Directories at or beneath this node; `1` for a directory. Four
/// billion is more than any volume holds.
pub dirs: u32,
/// `(device, inode)` for files, used to de-duplicate hardlinks. No file
/// has inode zero, which lets `None` cost nothing.
pub inode: Option<(u64, NonZeroU64)>,
/// The directory could not be read; its contents are unknown.
pub read_error: bool,
/// Newest write time at or beneath this node, in Unix seconds; `0` when
@@ -101,9 +100,7 @@ impl Node {
name: name.into(),
kind: NodeKind::Directory,
bytes: 0,
own_bytes: 0,
files: 0,
own_files: 0,
dirs: 1,
inode: None,
read_error: false,
@@ -124,9 +121,7 @@ impl Node {
name: name.into(),
kind,
bytes,
own_bytes: bytes,
files: u64::from(kind == NodeKind::File),
own_files: u64::from(kind == NodeKind::File),
dirs: 0,
inode: None,
read_error: false,
@@ -141,6 +136,35 @@ impl Node {
self.kind.is_dir()
}
/// Bytes of the leaf entries directly in this directory, or this file's
/// own size.
pub fn own_bytes(&self) -> u64 {
if !self.is_dir() {
return self.bytes;
}
self.children
.iter()
.filter(|child| !child.is_dir())
.fold(0, |sum, child| child.bytes.saturating_add(sum))
}
/// Files directly in this directory; `1` for a file.
pub fn own_files(&self) -> u64 {
if !self.is_dir() {
return self.files;
}
self.children
.iter()
.filter(|child| !child.is_dir())
.map(|child| child.files)
.sum()
}
/// [`Self::inode`] as the plain pair a platform reports.
pub fn identity(&self) -> Option<(u64, u64)> {
self.inode.map(|(device, file)| (device, file.get()))
}
/// The value a treemap should weight this node by.
pub const fn value(&self, metric: Metric) -> u64 {
match metric {
@@ -231,14 +255,14 @@ impl Node {
}
}
/// Recompute `bytes`, `files`, `dirs` and the direct totals bottom-up, then
/// order children by `metric`, largest first.
/// Recompute `bytes`, `files` and `dirs` bottom-up, then order children by
/// `metric`, largest first.
///
/// `bytes` and `files` are the subtree totals; `own_bytes` and `own_files` are
/// the direct contents, derived from the leaf children rather than tracked
/// separately. Deriving them is what keeps the two consistent: hardlink
/// de-duplication rewrites a leaf's weight, and every total above it —
/// including its parent's "direct" figure — follows without a second pass.
/// A leaf's `bytes` is its measured size and the only input; every total is
/// derived from the leaves, as are the direct figures [`Node::own_bytes`]
/// and [`Node::own_files`]. Deriving them is what keeps them consistent:
/// hardlink de-duplication rewrites a leaf's weight, and every total above
/// it follows without a second pass.
pub fn aggregate(node: &mut Node, metric: Metric) {
aggregate_at(node, metric, 0, None);
}
@@ -331,24 +355,19 @@ fn aggregate_at(
if !node.is_dir() {
// Every name of a file has the file's size, so one that weighs
// nothing need not be remembered to be charged once.
if node.own_bytes > 0
if node.bytes > 0
&& let Some(seen) = seen
&& let Some(key) = node.inode
&& let Some(key) = node.identity()
&& !seen.insert(key)
{
node.own_bytes = 0;
node.bytes = 0;
}
node.bytes = node.own_bytes;
node.files = node.own_files;
node.dirs = 0;
return;
}
let mut bytes = 0;
let mut files = 0;
let mut own_bytes = 0;
let mut own_files = 0;
let mut dirs: u64 = 1;
let mut dirs: u32 = 1;
let mut modified = 0;
if depth < PARALLEL_LEVELS {
node.children
@@ -365,15 +384,9 @@ fn aggregate_at(
bytes = child.bytes.saturating_add(bytes);
files += child.files;
dirs += child.dirs;
if !child.is_dir() {
own_bytes = child.bytes.saturating_add(own_bytes);
own_files += child.files;
}
}
node.bytes = bytes;
node.files = files;
node.own_bytes = own_bytes;
node.own_files = own_files;
node.dirs = dirs;
node.modified = modified;
@@ -414,6 +427,14 @@ mod tests {
Node::entry(name, NodeKind::File, bytes)
}
/// A home directory is tens of millions of nodes: every byte here is
/// tens of megabytes there.
#[test]
#[cfg(target_pointer_width = "64")]
fn a_node_stays_small() {
assert_eq!(size_of::<Node>(), 88);
}
#[test]
fn seen_charges_an_identity_once_in_either_store() {
let seen = Seen::new();
@@ -443,7 +464,7 @@ mod tests {
("newer again", 8192, newer),
] {
let mut file = leaf(name, bytes);
file.inode = Some(key);
file.inode = Some((key.0, NonZeroU64::new(key.1).unwrap()));
root.children.push(file);
}
aggregate_deduped(&mut root, Metric::Bytes, &Seen::new());
@@ -460,12 +481,12 @@ mod tests {
root.children.push(leaf("small", 9));
aggregate(&mut root, Metric::Bytes);
assert_eq!(root.own_bytes, 5 + 9, "direct leaves only");
assert_eq!(root.own_bytes(), 5 + 9, "direct leaves only");
assert_eq!(root.bytes, 5 + 9 + 7);
assert_eq!(root.files, 3);
assert_eq!(root.own_files, 2);
assert_eq!(root.own_files(), 2);
assert_eq!(root.dirs, 2);
assert_eq!(child_named(&root, "child").own_bytes, 7);
assert_eq!(child_named(&root, "child").own_bytes(), 7);
assert_eq!(&*root.children[0].name, "small", "9 bytes, largest first");
assert_eq!(&*root.children[2].name, "direct");
@@ -473,7 +494,7 @@ mod tests {
let mut single = leaf("solo", 3);
aggregate(&mut single, Metric::Bytes);
assert_eq!(single.bytes, 3);
assert_eq!(single.own_bytes, 3);
assert_eq!(single.own_bytes(), 3);
assert_eq!(single.files, 1);
assert_eq!(single.dirs, 0);
}