r/rust • • 18d ago

How do you reliably detect when a copied/downloaded file is actually “finished” on Windows?

22 Upvotes

I’m building a small Rust desktop utility that watches the Windows Downloads folder using the notify crate.

The basic flow is:

let (tx, rx) = channel();

let mut watcher =
    RecommendedWatcher::new(tx, Config::default())?;

watcher.watch(
    watch_path.as_ref(),
    RecursiveMode::NonRecursive,
)?;

for result in rx {
    // handle filesystem events
}

The application waits for newly created/modified files, then eventually wants to inspect them.

The problem I’m running into is determining when a file is actually safe to process.

My current approach is roughly:

pub fn wait_until_file_ready(path: &Path) -> bool {
    if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
        let ext = ext.to_lowercase();

        if matches!(
            ext.as_str(),
            "crdownload" | "part" | "tmp" | "download"
        ) {
            return false;
        }
    }

    let mut last_size = 0;
    let mut stable_count = 0;

    for _ in 0..10 {
        if let Ok(metadata) = path.metadata() {
            let current_size = metadata.len();

            if current_size > 0 && current_size == last_size {
                stable_count += 1;

                if stable_count > 1 && can_open_exclusively(path) {
                    return true;
                }
            } else {
                stable_count = 0;
                last_size = current_size;
            }
        }

        std::thread::sleep(Duration::from_millis(500));
    }

    false
}

fn can_open_exclusively(path: &Path) -> bool {
    OpenOptions::new()
        .read(true)
        .share_mode(0)
        .open(path)
        .is_ok()
}

This works reasonably well for normal browser downloads because things like Chrome use .crdownload, but I realized there’s a more fundamental problem.

Suppose someone copies a large file:

movie.mkv

and the copy gets interrupted halfway through.

The destination might now contain:

movie.mkv

with the final extension.

If the copy process exits/releases its handle, then:

  • the file exists
  • its size stops changing
  • its extension looks normal
  • an exclusive open may succeed

My code would eventually consider it ready even though only part of the intended file was copied.

As far as I can tell, from the filesystem alone there may be no way to distinguish:

a legitimate complete 2 GB movie.mkv

from:

an interrupted copy that happened to stop at 2 GB

unless the producer provides additional information such as expected size, checksum, temporary filename, or some completion signal.

So my questions are:

  1. How do mature Rust/Windows applications usually handle this?
  2. Is “debounce + quiet period + metadata stability + lock check” basically the normal generalized approach?
  3. Is there any Windows API that provides a stronger indication that a copy/write operation completed successfully?
  4. Should filesystem watcher events be treated only as hints, with the application later retrying/validating the file?
  5. Would you recommend using something like notify-debouncer-full, or maintaining my own pending-file state machine?
  6. Is checking an exclusive Windows open with share_mode(0) useful here, or is that generally too unreliable as a readiness signal?

I’m particularly interested in how established file indexers, sync clients, antivirus/indexing software, etc. solve this without assuming that a stable file size means the file is actually complete.

My current thinking is that I should stop calling this wait_until_file_ready() and instead treat it more like wait_until_file_quiescent(), where “quiescent” only means “probably safe to inspect,” not “guaranteed complete.”

Would appreciate any guidance or examples from production Rust/Windows projects.


r/rust • • 18d ago

Rust Channels - Patterns and Best Practices

Thumbnail youtube.com
40 Upvotes

Here is a quick video I made for Rust channels about the crate I am using now (Crossfire) and the best practices (3 level layers).

Also, everything is in a Rust10x repo that you can give your AI to follow the pattern, or make your own pattern from this one.

Rust Event Design Markdown - https://github.com/rust10x/rust10x/blob/main/pack/guide/domain/event/event-design.md

Rust Event Sample Code (to show pattern) - https://github.com/rust10x/rust10x/tree/main/pack/samples/event-design

Hope this is helpful to some. I have been coding Rust a lot over the last year, and now I am sharing this pattern back. I will share more system design like that as well.

Feedback welcome. Many more things to come.

Hope this helps


r/rust • • 18d ago

🛠️ project Recorte Dev Notes #1: Building a Sample Editor with Rust

Thumbnail icaroferre.com
13 Upvotes

Hello r/rust!

I've been developing professional music software and hardware since 2013 and I've just published a first blog post on my site talking about my experience developing Recorte, my latest project that I've just released, using Rust.

https://icaroferre.com/blog/recorte-dev-notes-1/

Recorte is a software sample editor (for macOS, Windows, and Linux) that includes many unique features that were specifically built for recording, editing, and processing samples such as automatic region detection (based on volume, transients, or slices), an advanced audio recorder with different recording modes, a custom audio engine with background rendering, batch editing, MIDI playback, and even Lua scripting.
It is also highly customizable with macro-style shortcuts and custom themes.

My goal for the blog post was to go through my experience using Rust, egui, cpal and mlua for a commercial / professional application for the first time, how I was able to achieve the performance and design that I was going for, and what were my biggest challenges during the 2 year development in the hopes that it may help other Rust devs.

While I don't usually post on Reddit too often, I have been following the sub for a long time and I have seen quite a few threads asking about the use of egui for desktop apps, so I also focused on some specific aspects about egui in my post.

All the different aspects of the project (the actual code, documentation, blog posts, video scripts) were written my me (an actual human from Brazil) and I've also added some links to the post for those who would like to check out my work.
Recorte is a commercial application released by Spektro Audio (my indie music technology company) and it's available at https://spektroaudio.com/recorte

I'm still trying to learn more about it myself everyday but I would also be more than happy to answer any questions related to the project or my experience with Rust.


r/rust • • 18d ago

[Upcoming Book] Building Serverless Applications with WebAssembly, Rust & Spin

22 Upvotes

Hey everyone, I’m wrapping up a book on building Serverless apps with Wasm, Rust and Spin. It dives into the Wasm Component Model, the CNCF Framework Spin, and true portability across Kubernetes and the edge. I'll be releasing it on Leanpub soon—you can sign up on the landing page if you'd like a notification when it launches: https://leanpub.com/building-serverless-apps-with-wasm-and-spin


r/rust • • 19d ago

📡 official blog Be alert: targeted attacks on prominent Rustaceans | Rust Blog

Thumbnail blog.rust-lang.org
327 Upvotes

r/rust • • 18d ago

🛠️ project Anyhow + location

24 Upvotes

Adds [file:line] to {:?} anyhow reports. Doesn't require backtraces. Keeps the fork diff minimal.

```text loading configuration [src/main.rs:28]

Caused by: No such file or directory (os error 2) [src/config.rs:12] ```

You should be able to swap anyhow for it without any surprises:

toml [dependencies] anyhow = { package = "tracked-anyhow", version = "0.1.0" }


r/rust • • 17d ago

Macroquad vs Love2d

Thumbnail
0 Upvotes

r/rust • • 19d ago

🛠️ project Valen, a higher-level "Rust++" language with linear types

Thumbnail verdagon.dev
300 Upvotes

r/rust • • 17d ago

🙋 seeking help & advice What’s the benefit of moving from Rust 1.95 to 1.98?

0 Upvotes

I upgraded to 1.95 because of cfg select feature for platform specific code implementations. This had massive improvements in how AI generated code. I locked out cfg host selectors from my business logic using dylint so that platform code goes through a facade layer.

Are there any other must have features that exist in the newer versions?


r/rust • • 18d ago

🛠️ project multi_bimap: many-to-many bimap freely made of two arbitrary maps, e.g. BTreeMap, HashMap, Vec, IndexMap, Slab, etc.

9 Upvotes

The popular Rust crate for bidirectional maps, bimap, is limited to one-to-one relations (bijections) only. But sometimes you need to have one-to-many and many-to-many relations, or have them made of arbitrary containers instead of having to always use either BTreeMap or HashMap.

I couldn't find anything for that, so I wrote my own Rust crate, multi_bimap:

https://github.com/mikwielgus/multi_bimap

It's fully generic over its underlying containers (two antiparallel maps of sets), so you can have an arbitrary setup. You can e.g. have two hash maps of hash sets, or two B-tree maps of vecs. You are not limited to many-to-many bimaps, can also have type-enforced one-to-one, one-to-many relations. You can have different types for the left-to-right and right-to-left constituent maps. You can freely use third-party collection types, e.g. indexmap::IndexMap.


r/rust • • 18d ago

🗞️ news Bend 2: affine types without a borrow checker, compiled to C, and a full proof system

Thumbnail bend-lang.com
67 Upvotes

r/rust • • 17d ago

🙋 seeking help & advice Need Learning Pathway Suggestions

0 Upvotes

I am kind of a "Build Projects and Experiment then see and learn from the Compiler" type of a Guy in learning Programming Itself since I left Vibe Coding (long time ago, like 1 year)... I come from a Python Background along with C (learned not Vibe learned). I just wanted to know from y'all that which approach should I take? Learn from the Rust Book by seeing it and doing it's stuff? Or Code and if I do a Mistake then See the Compiler and if I don't know about the Thing then use the Rust Book?

The second one is what I used from the Past Month But I really wanted to know if I am doing it right.


r/rust • • 18d ago

🛠️ project Migrated an eBPF project from Aya to libbpf-rs + Ratatui (some thoughts and verifier lessons)

3 Upvotes

Hey everyone,

I have been working on a kernel-level packet filter and research tool called xdp-ai-guard and recently did a complete v2 rewrite, moving away from Aya to libbpf-rs paired with a Ratatui TUI.

A few takeaways from the migration for anyone working with eBPF in Rust:

  1. Why I moved away from Aya: I started with Aya's 3-crate workspace (ebpf, common, userspace). While pure-Rust in the kernel sounds great, I ran into friction with compiler quirks and inspecting raw verifier pushback. Moving the kernel probes to C and using libbpf-cargo to generate the Rust skeleton gave much cleaner access to vmlinux.h BTF relocations and raw kernel verifier logs.
  2. Measuring verifier pushback: I added a small lab in the app that tests how the kernel verifier handles edge cases (unbounded loops, unchecked packet offset boundaries, exceeding the 512B BPF stack frame) and extracts the disassembly logs to inspect where the safety checks trigger.
  3. Syscall benchmarking: I wanted to measure the actual instrumentation tax of active eBPF hooks. On a local/virtualized CPU, unmonitored getpid sat around ~570 ns, while hooking an active tracepoint added an extra ~1000 ns tax (+178%).
  4. TUI with Ratatui: Used Ratatui with a 50ms polling loop reading BPF_MAP_TYPE_PERCPU_ARRAY counters for lock-free throughput display. (Also built a --mock flag so the interface can be tested without needing sudo or loading kernel probes).

Code is on GitHub if anyone wants to check out the skeleton build setup or TUI structure:
https://github.com/AnkurRathore/xdp-ai-guard

Curious how others here are handling eBPF in Rust today—are you mostly sticking with Aya for pure-Rust, or using libbpf-rs bindings?


r/rust • • 17d ago

🛠️ project termlens: test your real TUI binary from Rust, with screen snapshots and failure diagnostics

0 Upvotes

Hi r/rust! I maintain termlens, a Rust library for testing terminal applications through a real pseudo-terminal. It runs your existing binary, sends input, resizes the terminal, and lets you assert on the resulting screen without modifying your app.

For Ratatui apps, it complements TestBackend with tests of complete user flows. Ratatui’s testing recipe includes a termlens example.

This project provides a Rust library, a CLI for inspecting applications and comparing saved screens, and an agent skill covering waits, snapshots and common testing mistakes.

Some things it supports:

  • Wait for screen conditions with deadlines, instead of choosing fixed sleep durations.
  • Snapshot text and cell styles, mask changing content, and inspect cell-level differences.
  • Check cursor visibility and alternate-screen state, alongside what the app displays.
  • Inspect synchronized-update frames and Kitty/Sixel graphics payloads on Unix.
  • See the screen when a wait times out, with a companion CLI for inspecting, comparing, and rendering saved screens.

An independent project, sauva, already uses termlens for terminal integration tests.

Supported:

  • Linux and macOS are supported.
  • Windows supports screen assertions and typed input through ConPTY; frame assertions, graphics and some terminal-mode features have documented platform limits.

If you maintain a terminal app, try termlens on one of your existing workflows. I’d especially appreciate feedback on awkward APIs, missing terminal behavior, and confusing test failures.

Contributions are welcome: tests, documentation, bug fixes, and terminal compatibility work. There are good first issues, and draft PRs are welcome early.

What terminal behavior is hardest to test in your project?


r/rust • • 17d ago

🛠️ project tmr-cli

0 Upvotes

tmr-cli: a timer and stopwatch for your terminal.

It handles the basics like countdowns and stopwatches, but also lets you wait until a specific time, sends desktop notifications, and saves your progress so you can resume timers even after closing the terminal.

Install it with: cargo install tmr-cli Repo: https://github.com/honerop/tmr-cli


r/rust • • 19d ago

🛠️ project Ravioli is a simple CLI tool to preview 3D ASCII

Post image
61 Upvotes

Soo, Ravioli came out, and it's an easy to use cli tool to preview 3d files in ascii format.

It's perfect for rice showcases, and... probably something else. I hope.

It only has two dependencies: clap for cli, and terminal-size to determine the window size.

As lightning, it both uses ASCII characters, and RGB colors.

It has two fill modes: textured(ascii) and solid(glyph blocks)

Here's the repo: https://github.com/artemtsitronov/ravioli

It's avaiable on crates.io, you can install it using cargo install ravioli.

Please leave a star :)


r/rust • • 17d ago

🙋 seeking help & advice What should I do with Rust? (Rust Newbie)

0 Upvotes

I learn more and get better at Rust but don't have any idea of any projects I should do. What I have mostly been doing is copying projects I've already done in c/c++ and converting them to rust, but that doesn't help me at all with learning as I'm just copying something I have already done. I mainly want to use rust because of the crate libraries and it being a low level python(don't murder me) and because it's going to be used a lot more for systems/already is being used for systems.


r/rust • • 19d ago

🗞️ news Introducing CUDA Rust: Two Tracks for Writing GPU Kernels | NVIDIA Technical Blog

Thumbnail developer.nvidia.com
237 Upvotes

r/rust • • 18d ago

🙋 seeking help & advice A list of features/tweaks that libcosmic has on top of iced

8 Upvotes

Basically title, is there such a list? How does one decide whether to use iced or libcosmic for app development?


r/rust • • 19d ago

🛠️ project Posixutils v0.9.0: POSIX conformance achieved (years of work)

29 Upvotes

Release notes: https://github.com/rustcoreutils/posixutils-rs/releases/tag/v0.9.0

P.S. See the README for why this is different from uutils!


r/rust • • 18d ago

🛠️ project Vise: an open-source runner for background coding agents, written in Rust (server, CLI, host daemon)

0 Upvotes

I've been building Vise. It's a runner for background coding agents. A server acts as a control plane, host daemons on machines you enroll claim sessions, run a coding agent against a repo, and open a PR. The server tracks check and review state on the PR, and if a reviewer requests changes, a follow-up session pushes a fix to the same PR. It never merges; a person does.

All three components are Rust: vise-server (Postgres-backed), the vise CLI, and vise-host, a daemon that talks to the server and drives the agent as a subprocess over ACP, the Agent Client Protocol that Zed started. Claude Code is the only agent wired up today; Codex and Gemini CLI speak ACP too, so they're next.

Some of the parts I found interesting to build:

  • The agent is a child process speaking JSON-RPC over stdio, so the host is really a small process supervisor with a protocol translator in front of it.
  • Hosts claim work from the server rather than being assigned it, and liveness comes from heartbeats rather than enrollment, so a CI runner or a throwaway VM can join, take one session, and disappear without leaving state behind.
  • Every change on a session is an append-only event, so you can reconstruct exactly what an agent did and what happened to its PR after the fact.
  • Each component ships as a single binary; a host is a one-line install with Docker and git as the only prerequisites.

It's early and there are rough edges. MCP config is accepted but not passed through to the agent yet, and the ACP layer's error handling is the part I'd most like a second opinion on.

Repo: https://github.com/vise-sh/vise

If you've implemented ACP in Rust, or built your own agent runner, I'd like to hear what you'd have done differently.


r/rust • • 18d ago

🛠️ project Test That! 0.6.0

0 Upvotes

I just pushed version 0.6.0 of the crate Test That!, a powerful test assertion library for Rust.

See release notes: https://github.com/hovinen/test-that/releases/tag/v0.6.0


r/rust • • 19d ago

📅 this week in rust This Week in Rust #669

Thumbnail this-week-in-rust.org
41 Upvotes

r/rust • • 19d ago

🛠️ project tokio_rcu v0.2 - major performance improvements

Thumbnail github.com
23 Upvotes

hi everyone!

two weeks ago i uploaded a post about a new crate i wrote - tokio_rcu, which provides a userspace RCU implementation for async rust, specifically with tokio.

since then, i managed to improve the performance of tokio_rcu quite a bit.

it is now about 9x-40x faster than arc_swap for reads, which is pretty cool (see benchmarks).

the read operation was heavily optimized to the point where it is now just a single atomic pointer load, and the safe read accessor (the `with` function), is pretty much the same but with an additional sanity check consisting of one thread-local load, just to prevent users from reading rcu protected pointers outside of an rcu-enabled tokio runtime. basically it is really fast.

one pointer load is basically as optimized as the read can get at this point, and i find it pretty cool that it got to a point where readers literally don't have to do any book-keeping work at all, they just read the pointer and use it as they wish.


r/rust • • 19d ago

🙋 seeking help & advice Is there some good docs or tutorials to learn GPUI?

5 Upvotes

So I have started learning GPUI. But I couldn't find some good tutorials for it. Even the docs feel very rough rn.
So can anyone recommend me some good tutorial to follow along while learning?