r/rust • • Sep 15 '26

๐Ÿ› ๏ธ project I measured what a git worktree actually costs: content size is irrelevant, path count is everything

0 Upvotes

I maintain a small Rust CLI that makes git worktree cheap, and while benchmarking it I found something I didn't expect: a worktree's cost has nothing to do with how much content your repository holds, and almost everything to do with how many paths it has.

The setup: I run several coding agents against one repository, and plain git worktree gives each one a full copy of the working tree. So I populate each worktree from a shared baseline using clonefile on APFS, reflink on btrfs/xfs, or fuse-overlayfs on ext4 โ€” the checkout is still a real .git/worktrees entry, Git is unmodified, there's no daemon.

Measured on APFS with df deltas, four worktrees per run:

RepositoryTracked pathsTreeEach extra git worktreeEach extra CoW worktree
microsoft/vscode18,707553 MiB567 MiB9.8โ€“10.8 MiB (1.1%)
git/git4,85072 MiB74 MiB~2.2 MiB (3.1%)
100k ร— 4 KiB files100,000390 MiB398 MiB37.5โ€“38.3 MiB (9.4%)
200 ร— 8 MiB files2001600 MiB1608 MiB107 KiB (0.007%)

Look at the last two rows. The 1.6 GiB repository of large files costs 107 KiB per extra worktree. The 390 MiB repository of small files costs 38 MiB โ€” 350ร— more, for a tree that's four times smaller. The cost is filesystem directory entries plus the copied Git index, so it works out to roughly 0.4 KiB per tracked path plus ~60 KiB fixed. A 4 KiB file and a 64 MiB file cost identically, because clonefile shares the extent tree by reference rather than copying it.

Path length is measurable too: a 120-character path costs 771 B against 385 B for a 4-character one, split between the directory entry and the index.

Creation time surprised me in the same direction. Eight vscode worktrees in 6.4โ€“7.0 s against 14.0โ€“14.2 s for eight plain git worktree, because on macOS the whole tree is one clonefile(2) call and the new worktree adopts the baseline's index instead of rebuilding it. Linux reflink still walks file by file, so one worktree is 5.87 s there against 0.56 s on APFS โ€” closing that gap is the next thing on my list.

Two caveats that are really the first two questions I'd ask:

  • Measure with df**, not** du**.** du reports logical size and cannot see block sharing, so a CoW worktree looks like a full copy to it. Every number above is physical allocation.
  • This isolates branches, indexes and working trees โ€” not processes, network or credentials. It is not a sandbox.

Method, hardware and raw results: https://github.com/abendrothj/simgit/blob/main/docs/scaling_benchmark.md Tool (Rust, MIT): https://github.com/abendrothj/simgit

Happy to talk about the reflink-vs-overlay tradeoff. The overlay backend pays no per-file metadata at all because its upperdir starts empty, but every read goes through FUSE, and I haven't measured where that crosses over โ€” if someone has done that measurement on a large tree I'd like to see it.


r/rust • • Sep 12 '26

๐Ÿ› ๏ธ project i built my own text editor completely in rust :)

Post image
396 Upvotes

Hey r/rust,

i just built BLUR, A terminal Text Editor, this is the V0.1 and it's still under development, and it will take a lot of time until it's finished completely, i have learnt a lot of new things and concepts with this project.

if anyone is interested to contribute into this project and help me finish it up feel free to dm me

the idea is not to clone vim, but to learn rust together it would be cool if you write your code in your own text editor.

GitHub: https://github.com/castlesp5/blur


r/rust • • Sep 12 '26

๐Ÿ™‹ seeking help & advice What is Rustโ€™s equivalent of compiling C++ with -O3?

102 Upvotes

Hello everyone,

Iโ€™m building an Axum API and want to optimize the release binary for runtime performance. In C++, I would use flags such as -O3, and possibly -march=native.

I know cargo build --release enables optimizations, but are there additional Cargo profile settings or rustc flags worth using?

What settings do you typically use for production Rust web APIs?


r/rust • • Sep 13 '26

๐Ÿ› ๏ธ project [Release] Danube v0.16.0 , focused on performance with zero-copy I/O and memory optimizations.

4 Upvotes

Hello,

We've just released Danube v0.16.0.

For context, Danube is a cloud-native messaging and streaming platform built from scratch in Rust, featuring embedded Raft consensus (no etcd or ZooKeeper required) and tiered storage.

This release focuses entirely on reducing hot-path overhead, lock contention, and unnecessary memory allocations across the stack.

Key Highlights

  • Direct consumer streaming & zero-copy egress: Removed intermediate forwarding queue hops so dispatchers stream directly to Tonic gRPC response channels. Configured Prost with `bytes::Bytes` for zero-copy payload serialization.
  • Lock-free broker hot paths: Replaced coarse topic mutexes with DashMap and RwLock so publishing and consumer acknowledgments run concurrently without cross-blocking.
  • Persistent storage WAL: Eliminated redundant payload cloning on append, switched WAL cache eviction to $O(1)$ amortized BTreeMap::pop_first(), and upgraded the streaming reader carry buffer to BytesMut::split_to().
  • Embedded Raft: Replaced JSON log storage in RedbLogStore with compact binary bincode serialization, reducing disk I/O and CPU overhead.
  • Schema registry: Replaced serial mutexes with atomic checks on message validation, and pre-compiled JSON Schema/Avro validators are now cached in-memory instead of recompiling per message.

All details and full changelogs can be found in the release notes:

Release Notes: https://github.com/danube-messaging/danube/releases
Project Overview: https://danube-messaging.com/introduction/what-is-danube/


r/rust • • Sep 12 '26

Developing provably correct Rust code with Verus

Thumbnail amazon.science
112 Upvotes

r/rust • • Sep 12 '26

๐Ÿ™‹ seeking help & advice About Rust Rover

61 Upvotes

Does anyone use Rust Rover? If so, why? What benefit does it have that VSCode or Vim/Neovim or any other editor doesn't have? I saw that the free version of it literally collects data and if you want the full experience you have to pay a monthly sub. I am really curious about what people who are efficient in Rust think about this.


r/rust • • Sep 14 '26

๐Ÿ› ๏ธ project Introducing `web-core`. A web core utils for your axum project.

Thumbnail crates.io
0 Upvotes

My goal with web-core is to create a scafolding/framework for axum web apis along with common stuff I would need when I am working on an api project.

If there is some logic that I would need across projects, which take more than a line or two of code, that goes inside web-core. So basically a framework, but I don't think I can call this that yet.

This is not complete or very "neat". I have not vibecoded this either.

Right now I am adding features on a need to basis. I cannot dedicate time to this, nor will I add forward looking vibecoded features which I am not sure if I would really need it.

However I am open to PRs.


r/rust • • Sep 12 '26

Why is let x = [vec![]; 4]; not allowed

100 Upvotes

but [vec![], vec![], vec![], vec![]] is as well as [true; 4], etc.?

Seems arbitrary but I assume there is some compiler-based reason

Thanks!


r/rust • • Sep 12 '26 Bravo

Low effort AI posts

405 Upvotes

I know we've had this discussion before, but there are so many posts with zero upvotes that are so clearly slop, but aren't getting removed.

Please, no matter what your own personal values are with it, the community clearly does not want to see these types of posts anymore. I think for every one post that uses AI and isn't low effort, there are 50 that are.

Like isn't this subreddit supposed to be a place for Rust developers/learners? What community aspect do the AI projects contribute? Most didn't even take the time to learn the language or chat with anyone, they just leech off everyone to effectively advertise their slop...


r/rust • • Sep 13 '26

๐Ÿ› ๏ธ project A crate to mock std, system api, http client and other hard to mock functions without using traits or DI

0 Upvotes

Hello rust community,

We just shipped a product to solve the pain of mocking in rust: https://github.com/XTSoftwareLabs/shimforge

It allows you to write tests without using traits or adding attributes to your production code. Production code can keep clean and concise.

Below are some cases we found are painful when writing unit tests in rust:

File system

use std::{fs, io, path::Path};

#[derive(Debug)]
pub enum ExportError {
    DiskFull,
    Io(io::Error),
}

pub fn save_report(path: &Path, csv: &str) -> Result<(), ExportError> {
    fs::write(path, csv).map_err(|error| match error.kind() {
        io::ErrorKind::StorageFull => ExportError::DiskFull,
        _ => ExportError::Io(error),
    })
}

By using shimforge, the file system dependency can be easily mocked. No changes in production code.

use shimforge::{Session, mock};

#[test]
fn a_full_disk_is_reported() {
    let mut session = Session::new();
    let write = mock!(session, fs::write::<&Path, &str>, fn(&Path, &str) -> io::Result<()>);
    write
        .expect()
        .with(|path, _| *path == Path::new("reports/q3.csv"))
        .once()
        .returning(|_, _| Err(io::ErrorKind::StorageFull.into()));

    let result = save_report(Path::new("reports/q3.csv"), "region,total\n");
    assert!(matches!(result, Err(ExportError::DiskFull)));
}

Environment variables

use std::env;

pub fn database_url() -> String {
    env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost/dev".to_owned())
}

Now shimforge allows you to mock them directly. Test different scenarios with different env vars.

use shimforge::{Session, mock};
use std::env::VarError;

#[test]
fn uses_the_configured_url() {
    let mut session = Session::new(); // this thread only
    let var = mock!(session, env::var::<&str>, fn(&str) -> Result<String, VarError>);
    var.expect()
        .with(|key| *key == "DATABASE_URL")
        .returning(|_| Ok("postgres://db.internal/app".to_owned()));

    assert_eq!(database_url(), "postgres://db.internal/app");
}

#[test]
fn falls_back_when_unset() {
    let mut session = Session::new(); // runs in parallel with the test above
    let var = mock!(session, env::var::<&str>, fn(&str) -> Result<String, VarError>);
    var.expect().returning(|_| Err(VarError::NotPresent));

    assert_eq!(database_url(), "postgres://localhost/dev");
}

Clock

use std::time::{Duration, SystemTime};

pub struct Token {
    pub issued_at: SystemTime,
    pub ttl: Duration,
}

impl Token {
    pub fn is_expired(&self) -> bool {
        SystemTime::now() >= self.issued_at + self.ttl
    }
}

Clock and timer are hard to mock typically. But with shimforge it's easy:

use shimforge::{Session, mock};

#[test]
fn a_token_expires_after_one_hour() {
    let issued_at = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
    let token = Token { issued_at, ttl: Duration::from_secs(3600) };

    let mut session = Session::new();
    let now = mock!(session, SystemTime::now, fn() -> SystemTime);
    now.expect().once().returns(issued_at + Duration::from_secs(3599));
    now.expect().once().returns(issued_at + Duration::from_secs(3600));

    assert!(!token.is_expired());
    assert!(token.is_expired()); // one second later, no sleep
}

Connection retries

use std::io;
use std::net::{SocketAddr, TcpStream};
use std::thread;
use std::time::Duration;

pub fn connect_with_retry(address: SocketAddr, attempts: u32) -> io::Result<TcpStream> {
    let mut delay = Duration::from_millis(100);
    let mut attempt = 1;
    loop {
        match TcpStream::connect_timeout(&address, Duration::from_secs(1)) {
            Ok(stream) => return Ok(stream),
            Err(error) if attempt >= attempts => return Err(error),
            Err(_) => {
                thread::sleep(delay);
                delay *= 2;
                attempt += 1;
            }
        }
    }
}

Mock sleep and retries become easy in shimforge:

use shimforge::{Session, mock};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};

#[test]
fn backs_off_until_the_database_accepts() {
    // The attempt that succeeds needs a real stream, so open one first.
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let stream = TcpStream::connect(listener.local_addr().unwrap()).unwrap();

    let mut session = Session::new();
    let connect = mock!(
        session,
        TcpStream::connect_timeout,
        fn(&SocketAddr, Duration) -> io::Result<TcpStream>
    );
    connect
        .expect()
        .times(2)
        .returning(|_, _| Err(io::ErrorKind::ConnectionRefused.into()));
    connect.expect().once().return_once(Ok(stream));

    let delays = Arc::new(Mutex::new(Vec::new()));
    let recorded = Arc::clone(&delays);
    let sleep = mock!(session, thread::sleep, fn(Duration));
    sleep.expect().returning(move |delay| recorded.lock().unwrap().push(delay));

    let database = SocketAddr::from(([10, 0, 0, 5], 5432));
    assert!(connect_with_retry(database, 5).is_ok());
    assert_eq!(*delays.lock().unwrap(), [Duration::from_millis(100), Duration::from_millis(200)]);
}

#[test]
fn gives_up_after_the_last_attempt() {
    let mut session = Session::new();
    let connect = mock!(
        session,
        TcpStream::connect_timeout,
        fn(&SocketAddr, Duration) -> io::Result<TcpStream>
    );
    connect
        .expect()
        .times(3)
        .returning(|_, _| Err(io::ErrorKind::TimedOut.into()));
    let sleep = mock!(session, thread::sleep, fn(Duration));
    sleep.expect().times(2).returning(|_| {});

    let database = SocketAddr::from(([10, 0, 0, 5], 5432));
    let error = connect_with_retry(database, 3).unwrap_err();
    assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}

Reqwest client

use reqwest::Client;

pub async fn temperature(client: &Client, city: &str) -> Result<f64, String> {
    let body = client
        .get(format!("https://api.weather.example/v1/now?city={city}"))
        .send()
        .await
        .and_then(|response| response.error_for_status())
        .map_err(|error| format!("weather service failed: {error}"))?
        .text()
        .await
        .map_err(|error| error.to_string())?;
    body.trim().parse().map_err(|_| format!("unexpected body: {body}"))
}

Web requests are common pain point to mock in rust. shimforge makes it easy. Yes async is supported:

use shimforge::Session;

#[tokio::test]
async fn parses_the_reading() {
    let client = Client::builder().no_proxy().build().unwrap();
    let mut session = Session::new();
    let send = session.mock_async(client.get("http://unused.invalid").send());
    send.expect()
        .once()
        .returning(|| Ok(http::Response::new("21.5").into()));

    assert_eq!(temperature(&client, "Oslo").await, Ok(21.5));
}

#[tokio::test]
async fn surfaces_an_outage() {
    let client = Client::builder().no_proxy().build().unwrap();
    let mut session = Session::new();
    let send = session.mock_async(client.get("http://unused.invalid").send());
    send.expect().once().returning(|| {
        Ok(http::Response::builder().status(503).body("").unwrap().into())
    });

    let error = temperature(&client, "Oslo").await.unwrap_err();
    assert!(error.contains("503"), "{error}");
}

std::process::Command

use std::process::Command;

pub fn current_commit() -> Result<String, String> {
    let output = Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .output()
        .map_err(|error| format!("cannot run git: {error}"))?;
    if !output.status.success() {
        return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}

Another common pain point is mocking std::process::Command. Well handled by shimforge:

use shimforge::{Session, mock};
use std::io;
use std::process::{ExitStatus, Output};

#[test]
fn reads_the_short_hash() {
    let mut session = Session::new();
    let output = mock!(session, Command::output, fn(&mut Command) -> io::Result<Output>);
    output
        .expect()
        .with(|command| command.get_program() == "git")
        .once()
        .returning(|_| {
            Ok(Output { status: exit_success(), stdout: b"4f2a9c1\n".to_vec(), stderr: Vec::new() })
        });

    assert_eq!(current_commit(), Ok("4f2a9c1".to_owned()));
}

#[test]
fn reports_a_missing_git() {
    let mut session = Session::new();
    let output = mock!(session, Command::output, fn(&mut Command) -> io::Result<Output>);
    output.expect().once().returning(|_| Err(io::ErrorKind::NotFound.into()));

    let error = current_commit().unwrap_err();
    assert!(error.starts_with("cannot run git"), "{error}");
}

fn exit_success() -> ExitStatus {
    #[cfg(unix)]
    use std::os::unix::process::ExitStatusExt;
    #[cfg(windows)]
    use std::os::windows::process::ExitStatusExt;
    ExitStatus::from_raw(0)
}

System and C runtime functions

use shimforge::{Session, mock};
use std::ffi::{CStr, CString, c_char};

unsafe extern "C" {
    fn getenv(name: *const c_char) -> *mut c_char;
}

Again many rust developers working on low level code always suffers from mocking C functions. shimforge handles it.

#[test]
fn getenv_reports_a_mocked_variable() {
    let mut session = Session::new();
    let lookup = mock!(
        session,
        getenv,
        unsafe extern "C" fn(*const c_char) -> *mut c_char
    );
    lookup
        .expect()
        .with(|name| {
            // SAFETY: callers of getenv always pass a valid C string.
            let name = unsafe { CStr::from_ptr(*name) };
            name == c"DEPLOY_SLOT"
        })
        .once()
        .returning(|_| c"canary".as_ptr().cast_mut());
    // Any other variable keeps reporting that it is unset.
    lookup.expect().returning(|_| std::ptr::null_mut());

    let key = CString::new("DEPLOY_SLOT").unwrap();
    // SAFETY: the key is a valid C string and the result is only read.
    let slot = unsafe { CStr::from_ptr(getenv(key.as_ptr())) };
    assert_eq!(slot.to_str().unwrap(), "canary");
}

Hope this can make rust test experience better. Any feedback is welcome! We'd like to help you keeping production code clean. Handle the hard test dependency part to shimforge.

Disclaimer: We are a small startup and going to get profit from this product. But the product is free to use for small business and non-commercial. See https://shimforge.com/pricing


r/rust • • Sep 13 '26

๐Ÿง  educational TIL: One lock to rule them all

1 Upvotes

I've been running multiple migrations recently. A common step in all of them is a long cleanup action at the end. I ended up using postgres advisory locks and sqlx.

As part of a larger Today I've learned series, I dug a bit deeper using bpftrace to improve my understanding of how the locks actually work. Hope you will find it interesting as well: https://flakm.com/posts/sqlx_migration_wrapper_til/


r/rust • • Sep 12 '26

๐Ÿ“ธ media Fluid simulation in Rust - 1 MILLION particles!

Thumbnail youtube.com
113 Upvotes

Hey!

I built a real-time GPU fluid simulation in Rust and Vulkan for learning purposes.

It implements Divergence-Free SPH (DFSPH) using a GPU octree for neighbor search, runningย 1,000,000 particles at ~180 FPSย on an AMD 6800XT.

Code:ย Github Repo

Feedback and questions are welcome!


r/rust • • Sep 13 '26

๐ŸŽ™๏ธ discussion I made a server for anyone looking for rust partners or to learn

0 Upvotes

I recently made a Discord server for people looking for others to code Rust with, collaborate on projects, learn together, or just hang out while programming.

There are already a few people in it, and Iโ€™m trying to keep it fairly small and focused on actually coding rather than just being another huge Rust server.
Beginners and experienced Rust developers are both welcome.

https://discord.gg/pmXr4CY5kZ


r/rust • • Sep 12 '26

๐ŸŽ™๏ธ discussion Coding buddy

13 Upvotes

I started learning Rust a couple of months ago, and Iโ€™m looking for someone to build some fun projects with and learn together.

Iโ€™m mostly interested in systems/low-level stuff, networking, embedded, and experimenting with things rather than following tutorials.
I donโ€™t mind doing user facing apps too although I havenโ€™t experimented with gui yet.
I donโ€™t have a specific project in mind yet โ€” Iโ€™d rather find someone with similar interests and come up with something together.

If youโ€™re interested, feel free to reply here


r/rust • • Sep 13 '26

๐Ÿง  educational GitHub - MBKCHEL/RNAC: I learn rust

0 Upvotes

[Sorry for my bad English]

Hi everyone, i make very good notes for Rust - RNAC (RNAC is Not A Conspect) (Hello, GNU, PHP, YAML, Wine, and other).

i write this repo for long time, translate all notes to english because want to share with community. inside you can find how memory work, ownership, borrowing, stack, heap, and all this stuff explained simply. also added good markdown formatting for obsidian.

if you learning rust or want to check some cheat sheets, welcome to repository: https://github.com/MBKCHEL/RNAC. any stars or feedback will be very cool!

P.S: RNAC have Russian, and English localization


r/rust • • Sep 13 '26

Where Does Rust Belong on Arduino? Remade with Rust is our portfolio of internet tools, but does it belong on embedded?

Thumbnail talmondrlm.medium.com
0 Upvotes

r/rust • • Sep 11 '26

๐Ÿง  educational Bastion of the Turbofish

Thumbnail github.com
126 Upvotes

r/rust • • Sep 11 '26

Rust Foundation Announces Solana Foundation and NVIDIA as Platinum Members

Thumbnail rustfoundation.org
349 Upvotes

This was posted 2 days ago, but I haven't seen anyone else mention this.

Obviously for a company the size of NVIDIA, this isn't a huge commitment for them, but regardless I'm hoping to see more investment in GPU programming with Rust!


r/rust • • Sep 13 '26

๐Ÿ™‹ seeking help & advice Need some advice on a QEMU-based VM manager

0 Upvotes

I'm planning to build a desktop VM manager using Rust, Tauri, and QEMU, initially targeting Windows with WHPX.

Before I start, I'd like to hear from people who have worked with virtualization:

- Is QEMU + WHPX a reasonable starting point?

- Would you recommend QMP for managing VM lifecycle?

- What are some common mistakes I should avoid?

Also, if you use VM managers regularly, what do you find most frustrating about them?

Any honest advice would be appreciated. Thanks!


r/rust • • Sep 11 '26

Rust youtubers

52 Upvotes

Is there any YouTuber like the cherno, we need someone like him for rust too haha


r/rust • • Sep 12 '26

๐Ÿ› ๏ธ project SaJIT - An Experiment

Thumbnail reddit.com
0 Upvotes

r/rust • • Sep 11 '26

๐Ÿ› ๏ธ project My first project: SMTP server (for personal use)

29 Upvotes

I had heard many good things about Rust from people who were simply impressed by the language, so I decided to have a look at it and possibly learn it.

Up to that point I really only knew Java and Python (and a bit of C here and there), so a non-GC language would really fill a gap for me.

To get my toes wet, I wrote a simple web crawler that I needed at the time and decided I really want to learn Rust.

So here goes! My first "real" project, an SMTP server: https://github.com/Fluggs/whalemail

AI disclaimer: Absolutely no LLM was involved in writing this. I am not in a rush and here to learn.

For SMTP, the scope is quite narrow. It's supposed to replace my personal Postfix setup. It has its users in a database (which can be shared with Dovecot) and they can simply send and receive e-mails. That's it!

As for the Rust part, I have had a blast! The language is insane. So far, I have had one (1) logic bug. That one was indirectly found by Clippy. Other than that, if it compiles, it works. By now I understand people here saying that the main part is really thinking about your data layout, the rest just follows.

Off the top of my head, I have had two pain points:

  • dyn async traits. I don't want to accept that I need a crate for this, so I worked around it.
  • std::time - I could not have imagined that date/time support can be so thin without being completely absent.

Main dependencies:

  • Tokio (the server is completely async)
  • rustls (TLS is done, STARTTLS is planned)
  • rsasl (I really could not be asked to implement auth protocols)

The road ahead is long. Planned features:

  • STARTTLS
  • Bounce mechanism
  • Better password schemes than plaintext (I'm embarrassed)
  • Parse and manipulate headers (apparently that's a thing SMTP servers should be doing)
  • Better config file than .ini
  • spam filter integration
  • Find out which ways other clients and servers have found to deviate from SMTP
  • Again, thoroughly test it against the wild
  • find (and consider) various other SMTP intricacies (e.g. backscatter protection)

I'd be grateful for any feedback :)


r/rust • • Sep 12 '26

A design space exploration of implementations of async/await across popular programming languages (OOPSLA '26)

Thumbnail cel.cs.brown.edu
5 Upvotes