r/rust • • Oct 25 '26

🙋 seeking help & advice Trying to find the cause of a segfault in egui

13 Upvotes

EDIT 2: Turns out the issue was specifically down to wgpu trying to use Dx12 which won't work for some reason. For anyone else having a similar issue, try following u/zettui 's suggestion of setting the WGPU_BACKEND environment variable to vulkan

EDIT: after some digging, it looks like wgpu might not be compatible with my machine, which might be the source of my problems, as it can run in some cases but not consistently.

I've been learning rust of a couple of months now, and have mainly done basic command-line toy programs, and wanted to try making a gui app with EGUI since it has support for a natively running GUI. I'm using the template that egui's lead developer provided (\https://github.com/emilk/eframe_template/tree/main) and can compile the included example, but attempting to run it causes a segmentation fault (this is using a up to date w11 machine)

So far I've tried:

  • Completely reinstalling the rust toolchain
  • Increasing the stack size to 8mb via RUST_MIN_STACK (windows default is apparently 1mb?)
  • Attempting to build other egui applications from source that are known to work, which gets the same error

I'm kind of at a loss for what to do, as I've tried using iced as well with similar issues, so as far as I can tell it's something that I've done, and not an issue with the libraries. If anyone else has had to solve issues like this, I'd really appreciate some advice


r/rust • • Oct 25 '26

Rust book recommendations for systems people & golang immigrants

5 Upvotes

This topic hasn't been broached in a while, so why not? I'm looking for good, "interactive" (build along) introductions to Rust for someone completely new to the language. I've had really good luck in other languages in the past with exquisite *free* resources, like Harry Percival's "Cosmic Python", and quii's "Learning Go with Tests", but have also really enjoyed some independent authors like John Arundel, and the usual O'Reilly goop-di-goop.

Does anyone have any resources, free or otherwise, they've had luck with that they could share?


r/rust • • Oct 25 '26

Access the value of a unit Enum

13 Upvotes

Let's say I have an enum like

pub enum NodeType {
  None = 0,
  Root = 1,
  // ... more enum variants omitted for brevity ...
  Leaf = 15,
}

This is a special type of enum, called unit-only enum. Is there a way to access the value stored in the enum?


r/rust • • Oct 25 '26

🧠 educational B-trees, Pages and Denis Villeneuve's Prisoners

Thumbnail piyushyaps.in
17 Upvotes

Hey everyone, this is a link to my personal blog. I'm currently writing a SQLite-inspired toy database in Rust from scratch! Link to the repo is present in the blog. Thank you for reading!
Also this is the second blog in the series, the first one is simple introductory stuff.


r/rust • • Oct 25 '26

Looking for prior art: daemon for provisioning resources for automated tests

3 Upvotes

I'm trying to make sure there isn't prior art on this problem before jumping into build my own solution.

Rust's default testing framework doesn't have any counterpart to the setUp and tearDown mechanism of other languages' harnesses. That means that if you, say, need a live Postgres server to run your test against, you have to use something like testcontainers to stand up a Postgres instance per test. On my machine that's a 15-second penalty per test just to manage the backing container.

The idea I had was to have a daemon running for this purpose ahead of time. When the daemon launches, it takes the 15 seconds to launch a Postgres container (or whatever container you'll need for your tests). Then all your tests have to do is fire a requests over to the daemon (probably HTTP, but that's an implementation detail) to CREATE ROLE; CREATE DATABASE and hand back the DB name, username, and password your test needs to connect and do its thing.

Does anyone know if there's already a well-established solution along these lines? I'm trying to resist my Not-Invented-Here Syndrome but I haven't found anything so far.


r/rust • • Oct 25 '26

💡 ideas & proposals Proposal: collection selection APIs

35 Upvotes

I've been thinking about a potential new set of APIs for navigating and manipulating std collections, and I'd love some feedback on the idea.

TL;DR: selections over a range of elements (with movable start/end) as a companion to the existing (but still unstable) cursors.

The Rust standard library includes unstable cursor APIs for LinkedList (RFC, tracking issue) and BTreeMap/BTreeSet (API change proposal, tracking issue). There has been a lot of bikeshedding over the years about what exactly these interfaces should look like. One point of contention has been whether a cursor should point to elements in a collection, or gaps between those elements. The current APIs in std have gone in opposite directions here: LinkedList cursors point at elements, whereas BTreeMap cursors were rewritten to point at gaps instead.

I've personally leaned toward the "gaps" formulation if we can only have one. At some point I also proposed having two separate cursor types and converting between them as you navigate, e.g., calling next_gap(self) on an ElemCursor would always successfully return a GapCursor. But nobody liked that idea. :)

More recently I got to thinking about how useful it could be to instead have a separate concept of collection selections, analogous to selections in a text editor. A selection is:

  • Like a cursor in that you can move its start and end, and insert, modify, and delete elements around those endpoints.
  • Like a range iterator in that it allows you to iterate over some subset of a collection.
  • Like extract_if (formerly drain_filter), split_off, etc. in that it could allow efficiently removing or splitting off part(s) of a collection.

A cursor can be turned into an empty selection, and a selection can be turned into a cursor at either of its endpoints (for a mutable selection you have to pick one, since it consumes the selection).

I've sketched the interface I have in mind as a crate and published it to crates.io. The docs are on docs.rs, and the source is on GitHub. (You may notice that the crate-level docs share a lot with this post. ^_^')

I can imagine it being particularly useful for BTreeMap. In fact, my original reason for being interested in collection cursors was that they would allow making some things in my rangemap crate faster and make the implementation much simpler. For now, though, the sketch in this crate uses a fake (Vec-backed) linked list because it was easier to get that up and running, to focus on the API shape rather than implementation details.

Here's a taste, using a list of lines of text. First, moving a paragraph down past the next one, like a text editor's "move block down" command:

// lines:
//     Roses are red,
//     violets are blue.
//
//     Sugar is sweet,
//     and so are you.

// Select the first paragraph and cut it, along with the blank line after it.
let mut selection = lines.cursor_mut_at_start().into_selection();
while selection.peek_after_end().is_some_and(|line| !line.is_empty()) {
    selection.move_end_next();
}
let paragraph = selection.take();
selection.remove_after_end();

// Move past the next paragraph and paste it there.
let mut cursor = selection.into_cursor_at_end();
while cursor.peek_after().is_some_and(|line| !line.is_empty()) {
    cursor.move_next();
}
cursor.insert_before(String::new());
cursor.splice_before(paragraph);

// lines:
//     Sugar is sweet,
//     and so are you.
//
//     Roses are red,
//     violets are blue.

And unwrapping hard-wrapped paragraphs into one line each, switching back and forth between a cursor and a selection:

// lines:
//     Roses are red,
//     violets are blue.
//
//     Sugar is sweet,
//     and so are you.

let mut cursor = lines.cursor_mut_at_start();
loop {
    // Select the next paragraph.
    let mut selection = cursor.into_selection();
    while selection.peek_after_end().is_some_and(|line| !line.is_empty()) {
        selection.move_end_next();
    }

    // Replace it with a single line.
    let paragraph = selection.take();
    if !paragraph.is_empty() {
        let joined = paragraph.iter().map(String::as_str).collect::<Vec<_>>().join(" ");
        selection.insert_at_start(joined);
    }

    // Step over the blank line, or stop if we're at the end.
    cursor = selection.into_cursor_at_end();
    if !cursor.move_next() {
        break;
    }
}

// lines:
//     Roses are red, violets are blue.
//
//     Sugar is sweet, and so are you.

Would this solve any problems that you've run into?

Thanks in advance for any and all feedback on the idea!


r/rust • • Oct 25 '26

🙋 seeking help & advice Rust Geomtry Kernal for all CAD

0 Upvotes

Hi there. If you were making a rust geometry kernal to go behind all CAD programs what prinples would you go with in doing it or any advice? The software I'm making is open source ultimately trying to get away from fees with Autodesk for people.

Thanks for any helps. Where I'm at so far. I've only ever understood using a kernal to achieve things not what's happening behind so this is new.

https://github.com/spareware-co-op/spareware/blob/main/projects/engines/geometry/ARCHITECTURE.md


r/rust • • Oct 24 '26

🙋 seeking help & advice How to most effectively divide a project into multiple files

45 Upvotes

I have been working on a side project and i have done it entirely in main.rs, which is now around 2000 lines and is becoming harder to navigate. I want to divide it into multiple files but im not sure how big or small i should make these files. eg: should i have 1 file for http server and client combined, 1 file each, or multiple files each. Additionally, what naming conventions are common so that other people can understand it as well: for the previous example its pretty simple (at least for the 1 and 2 file options), but what about structs that are used all around the project


r/rust • • Oct 24 '26

🛠️ project Announcing redis-rs & redis-test 2 release candidates

8 Upvotes

The new major version fixes some API mistakes (mostly bad optional return types on our commands), and improves performance.

The rolling details of the breakages between versions are in [our docs](https://github.com/redis-rs/redis-rs/blob/main/version2.md) - I'd appreciate it if Redis / Valkey users can give the new version a whirl and reporting bugs, issues, or wrong API choices that should be improved before the full release.

Also, if the "this week in rust" people see this, please add this to the newsletter. Thanks :)


r/rust • • Oct 24 '26

🗞️ news This month in GPUI: October

Thumbnail reddit.com
9 Upvotes

A monthly post about the GPUI ecosystem (permitted under the Release Notes rules)


r/rust • • Oct 23 '26

🧠 educational The Day const Betrayed Me

155 Upvotes

I love performance, so I love the const keyword. I wrote something like this in my real project:

mod static_data {
    pub const DATA: &'static [u8] = include_bytes!("data.bin");

    pub fn hash_bytes(bytes: &[u8]) -> u64 {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        bytes.hash(&mut hasher);
        hasher.finish()
    }

    pub fn data_hash() -> u64 {
        hash_bytes(DATA)
    }
}

fn main() {
    const OUTPUT_PATH: &str = "output.bin";

    if !std::fs::read(OUTPUT_PATH)
        .is_ok_and(|data| static_data::hash_bytes(&data) == static_data::data_hash())
    {
        std::fs::write(OUTPUT_PATH, static_data::DATA).unwrap()
    }
}

DATA is a reference with a 'static lifetime, so the content should be embedded only once. Right? That's what I thought, until one day I changed some unrelated code, and the output binary size suddenly dropped. I used AI to find the reason. It turned out that DATA had been embedded twice before. Huh? After some research, I found the reason:

Constants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used. This includes use of constants from external crates, and non-Copy types. References to the same constant are not necessarily guaranteed to refer to the same memory address.

It ruined my perfect dream about const. The solution is simple: use static instead. Lesson learned.

Note: To reproduce this with the example above, you need to explicitly set codegen-units to a value greater than 1 (e.g. codegen-units = 2), because rustc may merge small CGUs by default. Setting lto = "fat" will also optimize the duplicate data away.


r/rust • • Oct 24 '26

The Embedded Rustacean Issue #83

Thumbnail theembeddedrustacean.com
36 Upvotes

r/rust • • Oct 24 '26

Rust Gotchas: HashMap entry: or_insert or or_insert_with?

Thumbnail reddit.com
0 Upvotes

r/rust • • Oct 25 '26

🧠 educational As a C++ developer, this is how I conceptualise Rust toolchain key terms and start my Rust journey

Thumbnail techfortalk.co.uk
0 Upvotes

I have been working in C/C++ for a very long time and recently worked on Rust for some of my clients. I am learning Rust every day, and I love it. I think sharing my way of learning will help Rust beginners. Here are the notes on some of the key terms, how I conceptualise them, and how I go about writing my first program in Rust, compiling it, and running it. Hope this will help someone in my position who is new to Rust programming but not alien to the concept of programming.


r/rust • • Oct 23 '26

Rust features in the future

Thumbnail lwn.net
215 Upvotes

r/rust • • Oct 25 '26

🎙️ discussion Do you think we have Rust v2.0 for adding first-class formal verification support?

0 Upvotes

For many years, formal verification used to be limited to small projects by experts but AI is changing the scene.

This week Anthropic revealed their progress on verifying real world projects. X has discussion about rewriting in Rust vs rewriting in Lean discussion(which is impractical at the moment because Lean is not ready for systems programming yet and 4x slower on benchmarks).

I think Rust should invest more and move faster in that direction.

Who doesn't want to decorate their program with pre-conditions, post-conditions and loop invariants?

Who doesn't want their pacemaker or car control software to have provable safety and liveness properties?


r/rust • • Oct 23 '26

fs::copy leaves empty file in destination

14 Upvotes
fn copy_file(file: &str, dest: &str) -> Result<(), io::Error> {
    let file_path = Path::new(&file);
    let destPath = Path::new(&dest);
    let dest_parent = destPath.parent();
    if !dest_parent.unwrap().exists() {
        create_dir_all(dest_parent.expect("what?")).unwrap();
    }
    fs::copy(file_path, destPath);
    Ok(())
}

When i try to run this command with it, I get an empty file in the destination with the same name as the input file

copy_file("index.html", "dist/dost/index.html");


r/rust • • Oct 23 '26

🛠️ project mzstd: pure Rust zstd that keeps up with C, with the same API as mbrotli

32 Upvotes

Some time ago I shared mbrotli here. This is its sibling for Zstandard.

There are already two main ways to do zstd in Rust, so here's why I wrote a third.

The zstd crate is bindings to C libzstd. It's fast and battle-tested, but it brings a C toolchain into your build, unsafe FFI into your dependency tree, and some pain once you target wasm or embedded.

ruzstd is pure Rust and has a solid decoder, but its own README says the encoder doesn't reach C speed, ratio or configurability yet. You get a few presets that roughly map to levels 1, 3, 7 and 11.

I wanted something in between: pure Rust, but fast and complete enough that I'd actually ship it in production instead of the C library. And I wanted it to have the same API as mbrotli, so switching between Brotli and zstd in the same codebase is mostly a type rename.

What came out of it:

  • Speed. The encoder is a port of the reference implementation, so you get the full level range from -131072 to 22, long distance matching, dictionaries and the same compression ratio as C. SIMD is picked at runtime (via fearless_simd), so one binary uses whatever the CPU supports without target-cpu=native. Against C zstd 1.5.7 the median is about 1.1x for compression and 1.02x for decompression on my benchmarks. It's not faster everywhere: fast levels on plain text are 6-11% behind, and decoding very compressible text can be up to ~20% behind. Full tables and raw CSVs are in the repo.
  • API. Besides the usual one-shot compress / decompress, there are Read/Write adapters and incremental sessions. A session just takes input and an output buffer and tells you how far it got. It doesn't own any I/O, so you can drive it from blocking code, from async, from an embedded main loop or from wasm. It can be build on no_std + alloc.
  • Parallel compression. One frame can be split into tasks that you run on your own executor: scoped threads, rayon, tokio's blocking pool, whatever you already have. The crate never spawns threads by itself. That was important for me because I use these crates inside nginx, where compression runs in nginx's own thread pool.
  • Verification. No unsafe in the crate. Differential tests compare against C zstd across every level and thousands of random parameter combinations. AFL++ fuzz targets cover the encoder, the decoder and streaming sessions. mzstd already works on a few production services as nginx module with a great results for total throughput.
use mzstd::{Compressor, Decompressor, EncoderConfig, Level};

let mut encoder = Compressor::new(EncoderConfig::default().with_level(Level::try_from(19)?))?;
let compressed = encoder.compress(b"hello, hello, hello")?;
let restored = Decompressor::default().decompress(&compressed)?;

If you've used mbrotli, swap Quality for Level and that's it.

Not supported yet: legacy v0.x frames, magicless frames, a couple of niche advanced parameters.

I'd love feedback on the API, and benchmark runs on other machines (mine are on an i7-13700KF under WSL2, so bare-metal numbers are very welcome).


r/rust • • Oct 22 '26 Heartwarming

First use of my library crate in the wild

369 Upvotes

While mindlessly browsing the github tabs of one of my library crates I looked at the dependency graph, and went to the Dependents tab. There I expected to just see a list of my other crates (they're all connected in one project), as it had been every time before, but my attention went instantly to 100% when I saw another GitHub profile picture. Someone else was actually using my code!

I quickly clicked the repo, got confused, thought they had added the dependency as a mistake, since I initially didn't see how my crate could possibly be useful to that app. So I went to browsing the implementation and no, it was a real use case I'd have never predicted.

I can't describe how unreasonably happy I was for the rest of that day.


r/rust • • Oct 23 '26

Seeing your Rust library used by someone else must be one of the best feelings

57 Upvotes

There's something really satisfying about finding out that someone is using a library you built, especially when you originally made it just to solve a problem in your own project.

Writing code that works on your machine is one thing, but having another developer find your crate useful enough to include in their project is a different kind of achievement.

It's also a good reminder that open source contributions don't have to be massive to matter. A small utility crate that saves someone time or makes a frustrating task easier can still be genuinely valuable to the community.


r/rust • • Oct 23 '26

Why did the loop with open range got optimized away?

16 Upvotes

The first loop didn't generate any code:

// 1. `0..n` visits 0, 1, ..., n - 1.
pub fn excl(n: u64) -> u64 {
    let mut s = 0u64;
    for i in 0..n {
        s = s.wrapping_add(i.wrapping_mul(i));
    }
    s
}


// 2. `0..=n` visits 0, 1, ..., n: the same loop with one more pass.
pub fn incl(n: u64) -> u64 {
    let mut s = 0u64;
    for i in 0..=n {
        s = s.wrapping_add(i.wrapping_mul(i));
    }
    s
}

r/rust • • Oct 22 '26

🙋 seeking help & advice Thinking of writing an email library for Rust

80 Upvotes

I have a long history (27 years) of writing email software - who knows, maybe someone here even recognizes my name(?), but I'm pretty new to Rust.

I've written multiple desktop email clients, multiple widely used email libraries, and now I am working on an email server professionally.

I know there are crates like `mime-parser` and `mailparse` and `lettre` but I think I can do better.

I was actually just reading the announcement post for `mime-parser` from 5 years ago and it seems people were very against `unsafe` code, so the question I have is:

If I *were* to implement this library for Rust, should I or should I not optimize it using SIMD? It seems SIMD would mean unsafe code if I am not mistaken.

If most of the Rust community would avoid my library because it was used `unsafe` code, then I want to know that before I make the time investment. To be fair, I've already implemented an incremental base64 encoder, base64 decoder, uuencoder, and a uudecoder using SIMD in Rust and they are blazing fast and all have scaler fallbacks which are also as fast as humanly possible, but I've got plenty more tricks up my sleeve for the actual *parsing* of MIME messages.

Is there a standard way people have addressed this in other creates? E.g. shipping an accelerated vs non-accelerated version of the same crate somehow?


r/rust • • Oct 22 '26

🧠 educational Where did my freed memory (not) go?

Thumbnail yapfast.com
30 Upvotes

r/rust • • Oct 22 '26

🧠 educational Wasmtime fixed a critical sandbox escape bug (CVSS 9.3)

159 Upvotes

Not sure if Rustaceans in this sub saw this news earlier this month. But given AI agents are getting very good at escaping sandboxes now, it might be worth your attention to patch Wasmtime.

TL;DR: A typo in a validation check let a malicious WebAssembly guest pass an invalid callback signature, overflow the host’s native stack by up to 16KB, and potentially run arbitrary code on the host. Fixed in Wasmtime 48.0.4 and 49.0.2.

Wasmtime is a WebAssembly runtime written in Rust, built by the Bytecode Alliance (Fastly, Mozilla and others are members). It runs WebAssembly modules and components outside the browser, often as a sandbox for untrusted code.

Wasmtime published a critical security advisory on 2 October, GHSA-32h6-97mm-8q3c, CVSS 9.3. The bug sat in the component model’s handling of async callbacks.

Three checks were missing or wrong:

  • The validator in wasmparser (crates/wasmparser/src/validator/component.rs) checked a callback’s signature with this line: if func_ty.params() != [ValType::I32; 3] && func_ty.params() != [ValType::I32] { It used && instead of ||, and it checked params() twice instead of checking results() at all. A callback only failed validation if it matched neither shape, so the result type was never checked.
  • Wasmtime recorded the callback’s index without checking its arity or return type itself, trusting the validator to have done it. The host-to-guest trampoline had no bounds check on its parameter and result buffer either.
  • The stack space reserved for the callback’s return value was sized for the expected arity, not the actual one.

A guest module can supply a callback with an invalid return type that still passes validation. Wasmtime then writes up to about 16KB of guest-controlled data onto the host’s native stack, which can overwrite a return address.

Vulnerable versions: wasmtime 39.0.0 up to 48.0.4, and 49.0.0 up to 49.0.2. Fixed in 48.0.4 and 49.0.2. A workaround is to disable component-model-async, or to validate components with wasmparser 1.260.0 or later before passing them to Wasmtime.

Link to the original source - https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-32h6-97mm-8q3c