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.

Copy engine: small files twice as fast to another disk; USB HDDs one by one

gelenmedya9e6986a0c12c
diff --git a/crates/rf-win/examples/copy_bench.rs b/crates/rf-win/examples/copy_bench.rs
new file mode 100644
index 00000000..3ccdd95d
--- /dev/null
+++ b/crates/rf-win/examples/copy_bench.rs
@@ -0,0 +1,254 @@
+//! Copy engines side by side: rustyfiles' (`fastcopy`), Windows' own (what File Explorer and Files use), robocopy (one thread and
+//! 16), and FastCopy and TeraCopy when they are named, on sets of files from the C: drive to folders on other drives.
+//!
+//! cargo run --release -p rf-win --example copy_bench -- [--runs 3] [--sets small,mixed,big] [--to C:,E:,F:] [--tools ...]
+//!
+//! FastCopy and TeraCopy are named by `RF_BENCH_FASTCOPY` and `RF_BENCH_TERACOPY` (their .exe). The sets are made once in
+//! `%LOCALAPPDATA%\rf-bench-copy\src` (about 7 GB): `small` 10,000 files of 4 KB in 100 folders, `mixed` 150 files of 1 to 40 MB,
+//! `big` one 4 GB file. Each destination is `<drive>\rf-bench-copy-dst` (on C: under the source's folder); it is emptied before
+//! every copy and removed at the end. Before each set its files are read once, so every tool reads them from the cache alike, and
+//! the order of the tools turns every run. A copy counts when the tool says it is done (Windows may still be writing its cache to
+//! the disk then, for every tool alike); then the files and bytes at the destination are checked.
+//!
+//! Also prints what `rf_win::drives::disk_info` says about each drive (bus, model, seek penalty, NVMe host memory buffer).
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
+use std::time::{Duration, Instant};
+
+const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+
+fn arg(name: &str) -> Option<String> {
+ let args: Vec<String> = std::env::args().collect();
+ args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
+}
+
+/// Deterministic, incompressible-looking bytes.
+fn fill(buf: &mut [u8], seed: u64) {
+ let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
+ for chunk in buf.chunks_mut(8) {
+ x ^= x << 13;
+ x ^= x >> 7;
+ x ^= x << 17;
+ let b = x.to_le_bytes();
+ chunk.copy_from_slice(&b[..chunk.len()]);
+ }
+}
+
+fn make_set(root: &Path, name: &str) -> PathBuf {
+ let dir = root.join(name);
+ let done = root.join(format!(".{name}-done"));
+ if done.exists() {
+ return dir;
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ match name {
+ "small" => {
+ let mut buf = vec![0u8; 4096];
+ for i in 0..10_000u64 {
+ let sub = dir.join(format!("d{:03}", i % 100));
+ if i < 100 {
+ std::fs::create_dir_all(&sub).unwrap();
+ }
+ fill(&mut buf, i);
+ std::fs::write(sub.join(format!("file{i:05}.bin")), &buf).unwrap();
+ }
+ }
+ "mixed" => {
+ for i in 0..150u64 {
+ let mb = 1 + (i * 37 % 40);
+ let mut buf = vec![0u8; (mb * 1024 * 1024) as usize];
+ fill(&mut buf, 1000 + i);
+ std::fs::write(dir.join(format!("clip{i:03}.bin")), &buf).unwrap();
+ }
+ }
+ "big" => {
+ use std::io::Write;
+ let mut f = std::io::BufWriter::with_capacity(8 << 20, std::fs::File::create(dir.join("big.bin")).unwrap());
+ let mut buf = vec![0u8; 8 << 20];
+ for i in 0..512u64 {
+ fill(&mut buf, 5000 + i);
+ f.write_all(&buf).unwrap();
+ }
+ }
+ _ => panic!("unknown set {name}"),
+ }
+ std::fs::write(done, "").unwrap();
+ dir
+}
+
+/// Files and bytes under `dir`.
+fn tally(dir: &Path) -> (u64, u64) {
+ let (mut files, mut bytes) = (0, 0);
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(d) = stack.pop() {
+ for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
+ let Ok(m) = e.metadata() else { continue };
+ if m.is_dir() {
+ stack.push(e.path());
+ } else {
+ files += 1;
+ bytes += m.len();
+ }
+ }
+ }
+ (files, bytes)
+}
+
+/// Reads every file once, so that each tool finds them in the cache.
+fn warm(dir: &Path) {
+ let mut stack = vec![dir.to_path_buf()];
+ let mut buf = vec![0u8; 8 << 20];
+ while let Some(d) = stack.pop() {
+ for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
+ if e.path().is_dir() {
+ stack.push(e.path());
+ } else if let Ok(mut f) = std::fs::File::open(e.path()) {
+ use std::io::Read;
+ while f.read(&mut buf).is_ok_and(|n| n > 0) {}
+ }
+ }
+ }
+}
+
+fn run(cmd: &mut Command) -> anyhow::Result<std::process::ExitStatus> {
+ use std::os::windows::process::CommandExt;
+ Ok(cmd.creation_flags(CREATE_NO_WINDOW).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status()?)
+}
+
+/// Copies the folder `src` INTO `dst` (so that `dst\<name>` is the copy), the way of each tool.
+fn copy(tool: &str, src: &Path, dst: &Path) -> anyhow::Result<()> {
+ let name = src.file_name().unwrap();
+ match tool {
+ "rustyfiles" => {
+ let tracker = Arc::new(rf_win::fileops::Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
+ anyhow::ensure!(rf_win::fastcopy::transfer(rf_win::fileops::Transfer::Copy, &[src.to_path_buf()], dst, tracker)?, "stopped");
+ }
+ "windows" => rf_win::bench::shell_copy_quiet(&[src.to_path_buf()], dst)?,
+ "robocopy" | "robocopy-mt16" => {
+ let mut c = Command::new("robocopy");
+ c.arg(src).arg(dst.join(name)).args(["/E", "/NFL", "/NDL", "/NJH", "/NJS", "/NP", "/R:0", "/W:0"]);
+ if tool == "robocopy-mt16" {
+ c.arg("/MT:16");
+ }
+ let st = run(&mut c)?;
+ anyhow::ensure!(st.code().is_some_and(|c| c < 8), "robocopy exit {st}");
+ }
+ "fastcopy" => {
+ let exe = std::env::var("RF_BENCH_FASTCOPY")?;
+ // fcp.exe is FastCopy's own command-line copy (the window version takes /no_ui /auto_close for the same)
+ let console = Path::new(&exe).file_name().is_some_and(|n| n.eq_ignore_ascii_case("fcp.exe"));
+ let mut c = Command::new(&exe);
+ c.arg("/cmd=force_copy");
+ if !console {
+ c.args(["/no_ui", "/auto_close"]);
+ }
+ let st = run(c.arg(src).arg(format!("/to={}\\", dst.display())))?;
+ anyhow::ensure!(st.success(), "fastcopy exit {st}");
+ }
+ "teracopy" => {
+ let exe = std::env::var("RF_BENCH_TERACOPY")?;
+ let st = run(Command::new(exe).arg("Copy").arg(src).arg(dst).args(["/OverwriteAll", "/Close"]))?;
+ anyhow::ensure!(st.success(), "teracopy exit {st}");
+ }
+ t => anyhow::bail!("unknown tool {t}"),
+ }
+ Ok(())
+}
+
+fn median(mut v: Vec<f64>) -> Option<f64> {
+ v.sort_by(f64::total_cmp);
+ v.get(v.len() / 2).copied()
+}
+
+fn main() {
+ rf_win::shell::ensure_com();
+ let runs: usize = arg("--runs").and_then(|s| s.parse().ok()).unwrap_or(3);
+ let sets: Vec<String> = arg("--sets").unwrap_or("small,mixed,big".into()).split(',').filter(|s| !s.is_empty()).map(String::from).collect();
+ let drives: Vec<String> = arg("--to").unwrap_or("C:,E:,F:".into()).split(',').filter(|s| !s.is_empty()).map(String::from).collect();
+ let mut tools: Vec<String> = arg("--tools").map(|s| s.split(',').map(String::from).collect()).unwrap_or_else(|| {
+ vec!["rustyfiles".into(), "windows".into(), "robocopy".into(), "robocopy-mt16".into()]
+ });
+ if arg("--tools").is_none() {
+ for (t, var) in [("fastcopy", "RF_BENCH_FASTCOPY"), ("teracopy", "RF_BENCH_TERACOPY")] {
+ if std::env::var_os(var).is_some_and(|p| Path::new(&p).is_file()) {
+ tools.push(t.into());
+ }
+ }
+ }
+ let root = PathBuf::from(std::env::var("LOCALAPPDATA").unwrap()).join("rf-bench-copy");
+ let src_root = root.join("src");
+ std::fs::create_dir_all(&src_root).unwrap();
+
+ println!("drives:");
+ for d in &drives {
+ let i = rf_win::drives::disk_info(Path::new(&format!("{d}\\")));
+ println!(
+ " {d} {:?} {:?} seek penalty {:?} removable {} host memory buffer {:?} KiB -> DRAM-less {:?}",
+ i.bus,
+ i.model.clone().unwrap_or_default(),
+ i.seek_penalty,
+ i.removable,
+ i.host_memory_buffer_kib,
+ i.dramless()
+ );
+ }
+ println!("tools: {}", tools.join(", "));
+
+ let mut out = serde_json::Map::new();
+ for set in &sets {
+ let src = make_set(&src_root, set);
+ let (files, bytes) = tally(&src);
+ println!("\n== {set}: {files} files, {:.2} GB", bytes as f64 / 1e9);
+ let mut row = serde_json::Map::new();
+ for drive in &drives {
+ let dst = if drive.eq_ignore_ascii_case("C:") { root.join("dst") } else { PathBuf::from(format!("{drive}\\rf-bench-copy-dst")) };
+ let mut times: Vec<Vec<f64>> = vec![Vec::new(); tools.len()];
+ warm(&src);
+ for r in 0..runs {
+ for k in 0..tools.len() {
+ // the order turns every run
+ let k = (k + r) % tools.len();
+ let _ = std::fs::remove_dir_all(&dst);
+ std::fs::create_dir_all(&dst).unwrap();
+ std::thread::sleep(Duration::from_secs(2));
+ let t = Instant::now();
+ let res = copy(&tools[k], &src, &dst);
+ let ms = t.elapsed().as_secs_f64() * 1000.0;
+ match res {
+ Ok(()) => {
+ let got = tally(&dst.join(src.file_name().unwrap()));
+ if got == (files, bytes) {
+ times[k].push(ms);
+ } else {
+ println!(" {drive} {}: INCOMPLETE copy {got:?} of {:?}", tools[k], (files, bytes));
+ }
+ }
+ Err(e) => println!(" {drive} {}: {e:#}", tools[k]),
+ }
+ }
+ }
+ let _ = std::fs::remove_dir_all(&dst);
+ let mut cell = serde_json::Map::new();
+ print!(" to {drive}");
+ for (k, t) in tools.iter().enumerate() {
+ match median(times[k].clone()) {
+ Some(ms) => {
+ print!(" {t} {:.0} ms ({:.0} MB/s)", ms, bytes as f64 / 1e6 / (ms / 1000.0));
+ cell.insert(t.clone(), serde_json::json!({ "ms": ms, "runs": times[k] }));
+ }
+ None => print!(" {t} -"),
+ }
+ }
+ println!();
+ row.insert(drive.clone(), serde_json::Value::Object(cell));
+ }
+ out.insert(set.clone(), serde_json::Value::Object(row));
+ }
+ let path = std::env::temp_dir().join("rf-copy-bench.json");
+ std::fs::write(&path, serde_json::to_vec_pretty(&serde_json::Value::Object(out)).unwrap()).unwrap();
+ println!("\nwritten: {}", path.display());
+}
diff --git a/crates/rf-win/examples/copy_parts.rs b/crates/rf-win/examples/copy_parts.rs
new file mode 100644
index 00000000..d503ac3b
--- /dev/null
+++ b/crates/rf-win/examples/copy_parts.rs
@@ -0,0 +1,218 @@
+//! Where the time of a many-small-files copy goes: our engine whole (`fastcopy::transfer`) against bare copies on the same 16
+//! threads that add one of its per-file costs at a time, and robocopy /MT:16. Uses copy_bench's `small` set (run it once).
+//!
+//! cargo run --release -p rf-win --example copy_parts -- [E:] [runs]
+//!
+//! The variants: `bare` (CopyFile2, no callback, folders made beforehand, the file list made beforehand); `+hold` (the source held
+//! open while it is copied, as `hold_source`); `+callback` (CopyFile2's progress callback, doing nothing); `+both`; `listing` (only
+//! walking the set, what the plan costs before the first byte); `copyfileex` (CopyFileExW, no callback); `transfer` (our engine as
+//! a paste uses it); `robocopy-mt16`.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::time::{Duration, Instant};
+
+use windows::Win32::Storage::FileSystem::{
+ COPY_FILE_FAIL_IF_EXISTS, COPYFILE2_EXTENDED_PARAMETERS, COPYFILE2_MESSAGE, COPYFILE2_MESSAGE_ACTION, COPYFILE2_PROGRESS_CONTINUE,
+ CopyFile2, CopyFileExW,
+};
+use windows::core::PCWSTR;
+
+fn wide(p: &Path) -> Vec<u16> {
+ use std::os::windows::ffi::OsStrExt;
+ p.as_os_str().encode_wide().chain([0]).collect()
+}
+
+fn list(dir: &Path, base: &Path, files: &mut Vec<PathBuf>, dirs: &mut Vec<PathBuf>) {
+ for e in std::fs::read_dir(dir).unwrap().flatten() {
+ let p = e.path();
+ if e.file_type().unwrap().is_dir() {
+ dirs.push(p.strip_prefix(base).unwrap().to_path_buf());
+ list(&p, base, files, dirs);
+ } else {
+ files.push(p.strip_prefix(base).unwrap().to_path_buf());
+ }
+ }
+}
+
+unsafe extern "system" fn nothing(_: *const COPYFILE2_MESSAGE, _: *const core::ffi::c_void) -> COPYFILE2_MESSAGE_ACTION {
+ COPYFILE2_PROGRESS_CONTINUE
+}
+
+fn bare(src: &Path, dst: &Path, files: &[PathBuf], dirs: &[PathBuf], hold: bool, callback: bool, ex: bool) {
+ bare_with(src, dst, files, dirs, hold, callback, ex, false)
+}
+
+/// `own`: read the file whole and write it with one call, its times set on the same handle (small files only).
+fn bare_with(src: &Path, dst: &Path, files: &[PathBuf], dirs: &[PathBuf], hold: bool, callback: bool, ex: bool, own: bool) {
+ for d in dirs {
+ std::fs::create_dir_all(dst.join(d)).unwrap();
+ }
+ let next = AtomicUsize::new(0);
+ std::thread::scope(|s| {
+ for _ in 0..std::env::var("THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(16usize) {
+ s.spawn(|| {
+ loop {
+ let i = next.fetch_add(1, Ordering::Relaxed);
+ let Some(f) = files.get(i) else { return };
+ let (a, b) = (src.join(f), dst.join(f));
+ let _held = hold.then(|| {
+ use std::os::windows::fs::OpenOptionsExt;
+ std::fs::OpenOptions::new().read(true).share_mode(1 | 2).open(&a).ok()
+ });
+ if own {
+ use std::io::Write;
+ // OWN_STEPS: 0 create and close, 1 + write, 2 + times (default)
+ let steps: u8 = std::env::var("OWN_STEPS").ok().and_then(|v| v.parse().ok()).unwrap_or(2);
+ let data = std::fs::read(&a).unwrap();
+ let meta = std::fs::metadata(&a).unwrap();
+ if std::env::var_os("OWN_NOBUF").is_some() {
+ // past Windows' cache: the data goes to the disk with the write, so the close has nothing to wait for
+ use std::os::windows::fs::OpenOptionsExt;
+ let mut f = std::fs::OpenOptions::new().write(true).create_new(true).custom_flags(0x2000_0000).open(&b).unwrap();
+ let padded = data.len().div_ceil(4096) * 4096;
+ let mut raw = vec![0u8; padded + 4096];
+ let off = raw.as_ptr().align_offset(4096);
+ raw[off..off + data.len()].copy_from_slice(&data);
+ if padded > 0 {
+ f.write_all(&raw[off..off + padded]).unwrap();
+ }
+ drop(f);
+ if padded != data.len() {
+ let g = std::fs::OpenOptions::new().write(true).open(&b).unwrap();
+ g.set_len(data.len() as u64).unwrap();
+ }
+ let g = std::fs::OpenOptions::new().write(true).open(&b).unwrap();
+ let _ = g.set_times(std::fs::FileTimes::new().set_modified(meta.modified().unwrap()).set_accessed(meta.accessed().unwrap()));
+ continue;
+ }
+ let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&b).unwrap();
+ if std::env::var_os("OWN_PRESIZE").is_some() {
+ // the final size first, then the data
+ f.set_len(data.len() as u64).unwrap();
+ }
+ if steps >= 1 {
+ f.write_all(&data).unwrap();
+ }
+ if steps >= 2 {
+ let _ = f.set_times(std::fs::FileTimes::new().set_modified(meta.modified().unwrap()).set_accessed(meta.accessed().unwrap()));
+ }
+ continue;
+ }
+ let (wa, wb) = (wide(&a), wide(&b));
+ unsafe {
+ if ex {
+ let _ = CopyFileExW(PCWSTR(wa.as_ptr()), PCWSTR(wb.as_ptr()), None, None, None, COPY_FILE_FAIL_IF_EXISTS);
+ } else {
+ let params = COPYFILE2_EXTENDED_PARAMETERS {
+ dwSize: std::mem::size_of::<COPYFILE2_EXTENDED_PARAMETERS>() as u32,
+ dwCopyFlags: windows::Win32::Storage::FileSystem::COPYFILE_FLAGS(COPY_FILE_FAIL_IF_EXISTS.0),
+ pfCancel: std::ptr::null_mut(),
+ pProgressRoutine: if callback { Some(nothing) } else { None },
+ pvCallbackContext: std::ptr::null_mut(),
+ };
+ let _ = CopyFile2(PCWSTR(wa.as_ptr()), PCWSTR(wb.as_ptr()), Some(&params));
+ }
+ }
+ }
+ });
+ }
+ });
+}
+
+fn main() {
+ rf_win::shell::ensure_com();
+ let drive = std::env::args().nth(1).unwrap_or("E:".into());
+ let runs: usize = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(3);
+ let src = PathBuf::from(std::env::var("LOCALAPPDATA").unwrap()).join(r"rf-bench-copy\src\small");
+ assert!(src.is_dir(), "run copy_bench once first: {} is missing", src.display());
+ let root = if drive.eq_ignore_ascii_case("C:") { PathBuf::from(std::env::var("LOCALAPPDATA").unwrap()).join(r"rf-bench-copy\dst") } else { PathBuf::from(format!(r"{drive}\rf-bench-copy-dst")) };
+ let (mut files, mut dirs) = (Vec::new(), Vec::new());
+ list(&src, &src, &mut files, &mut dirs);
+ println!("{} files, {} folders, to {}", files.len(), dirs.len(), root.display());
+
+ let variants: Vec<&str> = std::env::args().nth(3).map(|v| v.split(',').map(|x| &*Box::leak(x.to_string().into_boxed_str())).collect()).unwrap_or_else(|| vec!["listing", "bare", "+hold", "+callback", "+both", "copyfileex", "own", "transfer", "robocopy-mt16"]);
+ let mut times: Vec<Vec<f64>> = vec![Vec::new(); variants.len()];
+ for r in 0..runs {
+ for k in 0..variants.len() {
+ let k = (k + r) % variants.len();
+ let _ = std::fs::remove_dir_all(&root);
+ std::fs::create_dir_all(&root).unwrap();
+ std::thread::sleep(Duration::from_secs(2));
+ let dst = root.join("small");
+ let t = Instant::now();
+ match variants[k] {
+ "listing" => {
+ let (mut f, mut d) = (Vec::new(), Vec::new());
+ list(&src, &src, &mut f, &mut d);
+ }
+ "bare" => bare(&src, &dst, &files, &dirs, false, false, false),
+ "+hold" => bare(&src, &dst, &files, &dirs, true, false, false),
+ "+callback" => bare(&src, &dst, &files, &dirs, false, true, false),
+ "+both" => bare(&src, &dst, &files, &dirs, true, true, false),
+ "copyfileex" => bare(&src, &dst, &files, &dirs, false, false, true),
+ "own" => bare_with(&src, &dst, &files, &dirs, false, false, false, true),
+ "spread" => {
+ // consecutive files in different folders: the threads never create in the same folder at once
+ let mut by_dir: std::collections::BTreeMap<PathBuf, Vec<PathBuf>> = Default::default();
+ for f in &files {
+ by_dir.entry(f.parent().unwrap().to_path_buf()).or_default().push(f.clone());
+ }
+ let lists: Vec<Vec<PathBuf>> = by_dir.into_values().collect();
+ let mut spread = Vec::with_capacity(files.len());
+ for i in 0..lists.iter().map(Vec::len).max().unwrap_or(0) {
+ for l in &lists {
+ if let Some(f) = l.get(i) {
+ spread.push(f.clone());
+ }
+ }
+ }
+ bare(&src, &dst, &spread, &dirs, false, false, false)
+ }
+ "transfer" => {
+ let tracker = Arc::new(rf_win::fileops::Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
+ let _ = rf_win::fastcopy::transfer(rf_win::fileops::Transfer::Copy, std::slice::from_ref(&src), &root, tracker);
+ }
+ "robocopy1" | "robocopyJ" => {
+ let mut c = std::process::Command::new("robocopy");
+ c.arg(&src).arg(&dst).args(["/E", "/NFL", "/NDL", "/NJH", "/NJS", "/NP", "/R:0", "/W:0"]);
+ if variants[k] == "robocopyJ" {
+ c.arg("/J");
+ }
+ let _ = c.stdout(std::process::Stdio::null()).status();
+ }
+ "pscopy" => {
+ let _ = std::process::Command::new("powershell")
+ .args(["-NoProfile", "-Command", &format!("Copy-Item -LiteralPath '{}' -Destination '{}' -Recurse", src.display(), dst.display())])
+ .stdout(std::process::Stdio::null())
+ .status();
+ }
+ "cmdcopy" => {
+ std::fs::create_dir_all(&dst).unwrap();
+ let script = format!(r#"for /d %d in ("{}\*") do @(mkdir "{}\%~nxd" & copy /y "%d\*.*" "{}\%~nxd" >nul)"#, src.display(), dst.display(), dst.display());
+ use std::os::windows::process::CommandExt;
+ let _ = std::process::Command::new("cmd").raw_arg(format!("/c {script}")).stdout(std::process::Stdio::null()).status();
+ }
+ "xcopy" => {
+ let _ = std::process::Command::new("xcopy").arg(&src).arg(format!("{}\\", dst.display())).args(["/E", "/I", "/Q", "/Y"]).stdout(std::process::Stdio::null()).status();
+ }
+ _ => {
+ let _ = std::process::Command::new("robocopy")
+ .arg(&src)
+ .arg(&dst)
+ .args(["/E", "/NFL", "/NDL", "/NJH", "/NJS", "/NP", "/R:0", "/W:0", "/MT:16"])
+ .stdout(std::process::Stdio::null())
+ .status();
+ }
+ }
+ times[k].push(t.elapsed().as_secs_f64() * 1000.0);
+ }
+ }
+ let _ = std::fs::remove_dir_all(&root);
+ for (k, v) in variants.iter().enumerate() {
+ let mut t = times[k].clone();
+ t.sort_by(f64::total_cmp);
+ println!(" {v:14} {:>7.0} ms runs {:?}", t[t.len() / 2], t.iter().map(|x| x.round()).collect::<Vec<_>>());
+ }
+}
diff --git a/crates/rf-win/examples/recycle_bench.rs b/crates/rf-win/examples/recycle_bench.rs
new file mode 100644
index 00000000..09a4fcb0
--- /dev/null
+++ b/crates/rf-win/examples/recycle_bench.rs
@@ -0,0 +1,88 @@
+//! Deleting a folder of many small files to the Recycle Bin: Windows' engine (what File Explorer does) against rustyfiles' rename
+//! into the bin (`fastrecycle`), on the C: drive.
+//!
+//! cargo run --release -p rf-win --example recycle_bench -- [files, default 20000]
+//!
+//! Each way gets a folder of its own under `%LOCALAPPDATA%\rf-bench-recycle` (files in 100 subfolders, a few hundred bytes each).
+//! Afterwards ONLY what this run put in the bin is removed from it for good: the bin's `$I` files are read and an item goes only
+//! when its original path is inside that test folder. Nothing else in the bin is touched.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
+use std::time::Instant;
+
+fn make(dir: &Path, n: usize) {
+ std::fs::create_dir_all(dir).unwrap();
+ for i in 0..n {
+ let sub = dir.join(format!("d{:03}", i % 100));
+ if i < 100 {
+ std::fs::create_dir_all(&sub).unwrap();
+ }
+ std::fs::write(sub.join(format!("file{i:06}.txt")), format!("rustyfiles recycle bench {i}\n").repeat(8)).unwrap();
+ }
+}
+
+/// The bin's items whose original path is under `root`: (`$I` file, `$R` item).
+fn ours_in_bin(root: &Path) -> Vec<(PathBuf, PathBuf)> {
+ let Some(sid) = rf_win::dock::startuser::current_sid() else { return Vec::new() };
+ let bin = PathBuf::from(format!(r"C:\$Recycle.Bin\{sid}"));
+ let want = root.to_string_lossy().to_lowercase();
+ let mut out = Vec::new();
+ for e in std::fs::read_dir(&bin).into_iter().flatten().flatten() {
+ let name = e.file_name().to_string_lossy().into_owned();
+ let Some(rest) = name.strip_prefix("$I") else { continue };
+ let Ok(b) = std::fs::read(e.path()) else { continue };
+ if b.len() < 28 {
+ continue;
+ }
+ let units: Vec<u16> = b[28..].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&u| u != 0).collect();
+ let original = String::from_utf16_lossy(&units).to_lowercase();
+ if original.starts_with(&want) {
+ out.push((e.path(), bin.join(format!("$R{rest}"))));
+ }
+ }
+ out
+}
+
+fn clean(root: &Path) -> usize {
+ let items = ours_in_bin(root);
+ for (i, r) in &items {
+ if r.is_dir() {
+ let _ = std::fs::remove_dir_all(r);
+ } else {
+ let _ = std::fs::remove_file(r);
+ }
+ let _ = std::fs::remove_file(i);
+ }
+ items.len()
+}
+
+fn main() {
+ let n: usize = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(20_000);
+ rf_win::shell::ensure_com();
+ let root = PathBuf::from(std::env::var("LOCALAPPDATA").unwrap()).join("rf-bench-recycle");
+ let _ = std::fs::remove_dir_all(&root);
+ println!("left in the bin from an earlier run, removed: {}", clean(&root));
+
+ // Windows' engine, as File Explorer deletes
+ let a = root.join("explorer-way");
+ make(&a, n);
+ let t = Instant::now();
+ let ok = rf_win::fileops::delete(std::slice::from_ref(&a), false);
+ let shell_s = t.elapsed().as_secs_f64();
+ println!("Windows' engine: {n} files in {shell_s:.2} s ({ok:?}), folder gone: {}", !a.exists());
+
+ // rustyfiles: the folder renamed into the bin
+ let b = root.join("rustyfiles-way");
+ make(&b, n);
+ let tracker = Arc::new(rf_win::fileops::Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
+ let t = Instant::now();
+ let left = rf_win::fastrecycle::recycle(std::slice::from_ref(&b), &tracker);
+ let ours_s = t.elapsed().as_secs_f64();
+ println!("rustyfiles: {n} files in {:.3} s, left for the engine: {}, folder gone: {}", ours_s, left.len(), !b.exists());
+ println!("{:.0}x faster", shell_s / ours_s.max(1e-6));
+
+ println!("this run's items removed from the bin: {}", clean(&root));
+ let _ = std::fs::remove_dir_all(&root);
+}
diff --git a/crates/rf-win/src/drives.rs b/crates/rf-win/src/drives.rs
index a0ee6d78..9eeda518 100644
--- a/crates/rf-win/src/drives.rs
+++ b/crates/rf-win/src/drives.rs
@@ -392,6 +392,135 @@ pub fn seek_penalty(path: &std::path::Path) -> Option<bool> {
}
}
+/// How a disk is attached, as Windows' storage stack reports it (`STORAGE_BUS_TYPE`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Bus {
+ Nvme,
+ Sata,
+ Usb,
+ Sd,
+ Raid,
+ Spaces,
+ Scsi,
+ Virtual,
+ Other(u32),
+}
+
+impl Bus {
+ fn from_raw(v: u32) -> Bus {
+ match v {
+ 17 => Bus::Nvme,
+ 11 | 3 => Bus::Sata,
+ 7 => Bus::Usb,
+ 12 | 13 => Bus::Sd,
+ 8 => Bus::Raid,
+ 16 => Bus::Spaces,
+ 1 | 10 => Bus::Scsi,
+ 14 | 15 => Bus::Virtual,
+ v => Bus::Other(v),
+ }
+ }
+}
+
+/// What the copy engine wants to know about the disk under a drive letter. Every part is `None` when Windows did not say.
+#[derive(Debug, Clone, Default)]
+pub struct DiskInfo {
+ pub bus: Option<Bus>,
+ /// The device's product name ("WD Blue SN5000 2TB").
+ pub model: Option<String>,
+ pub seek_penalty: Option<bool>,
+ pub removable: bool,
+ /// An NVMe drive's Host Memory Buffer wish, in KiB (preferred, minimum): a drive that asks for one has (almost always) no
+ /// DRAM of its own. `Some((0, 0))`: an NVMe drive that asks for none.
+ pub host_memory_buffer_kib: Option<(u32, u32)>,
+}
+
+impl DiskInfo {
+ /// A DRAM-less SSD: an NVMe drive that asks the PC for a host memory buffer.
+ pub fn dramless(&self) -> Option<bool> {
+ self.host_memory_buffer_kib.map(|(preferred, min)| preferred > 0 || min > 0)
+ }
+}
+
+/// One `IOCTL_STORAGE_QUERY_PROPERTY` on the volume of drive letter `path` (opened with no access rights: a property query needs
+/// none), `input` in, the bytes Windows wrote out.
+fn storage_query(path: &std::path::Path, input: &[u8], out_len: usize) -> Option<Vec<u8>> {
+ use windows::Win32::Foundation::CloseHandle;
+ use windows::Win32::Storage::FileSystem::{CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING};
+ use windows::Win32::System::IO::DeviceIoControl;
+ use windows::Win32::System::Ioctl::IOCTL_STORAGE_QUERY_PROPERTY;
+ let s = path.to_str()?;
+ let b = s.strip_prefix(r"\\?\").unwrap_or(s).as_bytes();
+ if b.len() < 2 || b[1] != b':' || !b[0].is_ascii_alphabetic() {
+ return None;
+ }
+ let dev = crate::wide::wide(format!(r"\\.\{}:", b[0] as char));
+ let mut out = vec![0u8; out_len.max(input.len())];
+ unsafe {
+ let h = CreateFileW(windows::core::PCWSTR(dev.as_ptr()), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES(0), None).ok()?;
+ let mut got = 0u32;
+ let ok = DeviceIoControl(
+ h,
+ IOCTL_STORAGE_QUERY_PROPERTY,
+ Some(input.as_ptr() as *const _),
+ input.len() as u32,
+ Some(out.as_mut_ptr() as *mut _),
+ out.len() as u32,
+ Some(&mut got),
+ None,
+ );
+ let _ = CloseHandle(h);
+ ok.map_err(|e| log::debug!("storage query: {e}")).ok()?;
+ out.truncate(got as usize);
+ }
+ Some(out)
+}
+
+fn u32_at(b: &[u8], at: usize) -> Option<u32> {
+ b.get(at..at + 4).map(|x| u32::from_le_bytes([x[0], x[1], x[2], x[3]]))
+}
+
+/// The disk under drive letter `path`: its bus, model, seek penalty and (NVMe) host memory buffer. No administrator rights.
+pub fn disk_info(path: &std::path::Path) -> DiskInfo {
+ let mut info = DiskInfo { seek_penalty: seek_penalty(path), removable: is_removable(path), ..Default::default() };
+ // StorageDeviceProperty (0), standard query: STORAGE_DEVICE_DESCRIPTOR
+ let q = [0u32.to_le_bytes(), 0u32.to_le_bytes(), [0; 4]].concat();
+ if let Some(d) = storage_query(path, &q, 1024) {
+ info.bus = u32_at(&d, 28).map(Bus::from_raw);
+ info.removable |= d.get(10).is_some_and(|&r| r != 0);
+ if let Some(off) = u32_at(&d, 16).filter(|&o| o > 0 && (o as usize) < d.len()) {
+ let name: Vec<u8> = d[off as usize..].iter().take_while(|&&c| c != 0).copied().collect();
+ let name = String::from_utf8_lossy(&name).trim().to_string();
+ info.model = (!name.is_empty()).then_some(name);
+ }
+ }
+ if info.bus == Some(Bus::Nvme) {
+ info.host_memory_buffer_kib = nvme_host_memory_buffer(path);
+ }
+ info
+}
+
+/// An NVMe drive's Identify Controller data, HMPRE and HMMIN (bytes 272 and 276, in 4 KiB units), through the storage stack's
+/// protocol-specific query (`StorageAdapterProtocolSpecificProperty`, `ProtocolTypeNvme`, `NVMeDataTypeIdentify`, CNS 1).
+fn nvme_host_memory_buffer(path: &std::path::Path) -> Option<(u32, u32)> {
+ const IDENTIFY_LEN: u32 = 4096;
+ const SPECIFIC_LEN: u32 = 40; // STORAGE_PROTOCOL_SPECIFIC_DATA
+ let mut q = Vec::with_capacity((8 + SPECIFIC_LEN + IDENTIFY_LEN) as usize);
+ q.extend_from_slice(&49u32.to_le_bytes()); // StorageAdapterProtocolSpecificProperty
+ q.extend_from_slice(&0u32.to_le_bytes()); // PropertyStandardQuery
+ for v in [3u32, 1, 1, 0, SPECIFIC_LEN, IDENTIFY_LEN, 0, 0, 0, 0] {
+ // ProtocolTypeNvme, NVMeDataTypeIdentify, CNS controller, sub value, data offset, data length, …
+ q.extend_from_slice(&v.to_le_bytes());
+ }
+ q.resize((8 + SPECIFIC_LEN + IDENTIFY_LEN) as usize, 0);
+ let d = storage_query(path, &q, q.len())?;
+ // STORAGE_PROTOCOL_DATA_DESCRIPTOR: Version, Size, then the specific data, whose offset counts from itself (byte 8)
+ let data_at = 8 + u32_at(&d, 8 + 16)? as usize;
+ let hmpre = u32_at(&d, data_at + 272)?;
+ let hmmin = u32_at(&d, data_at + 276)?;
+ Some((hmpre * 4, hmmin * 4))
+}
+
#[cfg(test)]
mod network_tests {
use super::is_network_path;
diff --git a/crates/rf-win/src/fastcopy.rs b/crates/rf-win/src/fastcopy.rs
index 7eea15dc..6e4dc495 100644
--- a/crates/rf-win/src/fastcopy.rs
+++ b/crates/rf-win/src/fastcopy.rs
@@ -496,10 +496,16 @@ fn hold_source(src: &Path) -> Option<std::fs::File> {
std::fs::OpenOptions::new().read(true).share_mode(FILE_SHARE_READ_WRITE).open(src).ok()
}
+/// Sources at least this big are held while they are copied ([`hold_source`]).
+const HOLD_MIN: u64 = 1 << 20;
+
/// `restart`: carry on a restartable copy into an existing partial `dst`.
fn copy_file(src: &Path, dst: &Path, size: u64, run: &Run, restart: bool) -> windows::core::Result<()> {
- // (let go when this returns: a move deletes the source after it)
- let _held = hold_source(src);
+ // (let go when this returns: a move deletes the source after it). Only a file big enough to take a while is held: the second
+ // handle more than doubled the time of each small file (10,000 files of 4 KB to another NVMe: 2.46 s held, 1.03 s not;
+ // robocopy /MT:16 0.97 s), most likely because CopyFile2 then can't take its oplock on the source, and a file copied in well
+ // under a millisecond has no time to be deleted halfway (issue 608 was about big files).
+ let _held = (size >= HOLD_MIN).then(|| hold_source(src)).flatten();
let (s, d) = (long_path(src), long_path(dst));
// Buffered, like Explorer: unbuffered writes of big files measured twice as slow
// (1 GB: 755 ms against Windows' 348 ms; buffered 285 against 265).
@@ -1261,7 +1267,8 @@ fn same_volume(a: &Path, b: &Path) -> bool {
/// Parallel copies pay off on SSDs. A spinning disk on either side copies ONE file at a time: two at once already make its head
/// jump between them, and the copy turns from sequential into random reads (issue 679: an HDD and an HDD-backed NAS were much slower
-/// than Explorer). Network shares (whose disks we can't ask about) and USB sticks take two.
+/// than Explorer). So does a USB disk that does not say what it is (most likely a spinning one in an enclosure). Network shares
+/// (whose disks we can't ask about) and USB sticks take two.
fn threads_for(sources: &[PathBuf], dest: &Path) -> usize {
let cores = std::thread::available_parallelism().map_or(4, |n| n.get());
let paths = sources.iter().map(PathBuf::as_path).chain(std::iter::once(dest));
@@ -1276,6 +1283,9 @@ fn threads_for(sources: &[PathBuf], dest: &Path) -> usize {
match crate::drives::seek_penalty(p) {
Some(true) => return 1,
Some(false) => {}
+ // A USB enclosure seldom passes the disk's answer on: there it is most likely a spinning disk, one file at a time (a USB
+ // HDD fell from MB/s to kB/s with two at once, Discord 2026-12-02; a USB stick says "removable" and keeps two)
+ None if !crate::drives::is_removable(p) && crate::drives::disk_info(p).bus == Some(crate::drives::Bus::Usb) => return 1,
None => slow = true,
}
slow |= crate::drives::is_removable(p);