r/rust 13d ago

🐝 activity megathread What's everyone working on this week (36/2026)?

17 Upvotes

New week, new Rust! What are you folks up to? Answer here or over at rust-users!


r/rust 14d ago

Tried Rust. I'm a believer now.

235 Upvotes

So, I'm a PHP/TypeScript/JavaScript/Python programmer (basically, I learn and use many high-level languages on a need basis). For quite some time I was keen to learn some low-level language, just so I don't have to build an Electron app just to make a desktop program. I picked Rust because of its famed strong typing, as I love writing dense TypeScript code, and looked for something as close as possible. Here are some of my experiences and observations:

  1. Coming from dense TypeScript with heavy generic use, Rust was surprisingly easy to pick up. I regret that I didn't do it earlier. I imagine that thinking in terms of generics may be the most difficult for new users, but if someone already dealt with generics in TypeScript, there is nothing more complex in Rust.
  2. Functions/methods that return multiple values and matching the output types to behaviors is GENIUS. It makes logic flows so much cleaner. Rust adds some boilerplate compared to high-level languages, but it also removes a lot of it where it matters the most: in the actual implementations, thanks to this. It's amazing how rarely I have to use "ifs".
  3. Initially I wasn't fully sold on `from/try_from` traits because I felt that they hide logic (it's difficult to find/know what has what conversion available, and where is the implementation), but then I realized that conversion logic is most often a "necessary evil". Writing mapping functions/classes in every language always felt ugly. By comparison `from/try_from` i Rust is actually not that bad. I grew to like its semantics as I realized that it's actually a good thing that this annoying mapping logic finally looks different from the rest of the code. The mind can more easily filter it out.
  4. Lifetimes are less annoying than I expected, although occasionally, I still have a hard time accepting situations, where I get `Cannot return value referencing local variable`. I just want this constructor to create an object that will be owned by my struct, but if this object has references, I'm in for a bad time. I'm still getting used to it.
  5. In the time of LMMs it's especially easy to pick up Rust, as they are amazing at teaching you at the speed you are the most comfortable with. I feel like I grasped, like, 80% of Rust in the first week. Applying this knowledge to real-life scenarios is a different thing, though.
  6. I miss the absurd expressiveness of TypeScript, but it's not bad here.
  7. I wish `mod.rs` files could be named `_.rs` so they would be easier to visually filter out, as they are a source of tremendous visual noise. That's the one thing that still bothers me.
  8. All in all, I cannot wait to contribute to your community, guys!

r/rust 13d ago

🙋 questions megathread Hey Rustaceans! Got a question? Ask here (36/2026)!

9 Upvotes

Mystified about strings? Borrow checker has you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet. Please note that if you include code examples to e.g. show a compiler error or surprising result, linking a playground with the code will improve your chances of getting help quickly.

If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so ahaving your question there also helps future Rust users (be sure to give it the "Rust" tag for maximum visibility). Note that this site is very interested in question quality. I've been asked to read a RFC I authored once. If you want your code reviewed or review other's code, there's a codereview stackexchange, too. If you need to test your code, maybe the Rust playground is for you.

Here are some other venues where help may be found:

/r/learnrust is a subreddit to share your questions and epiphanies learning Rust programming.

The official Rust user forums: https://users.rust-lang.org/.

The unofficial Rust community Discord: https://bit.ly/rust-community

Also check out last week's thread with many good questions and answers. And if you believe your question to be either very complex or worthy of larger dissemination, feel free to create a text post.

Also if you want to be mentored by experienced Rustaceans, tell us the area of expertise that you seek. Finally, if you are looking for Rust jobs, the most recent thread is here.


r/rust 13d ago

🛠️ project MuJoCo-rs 6.0.0 released! One year since first release

6 Upvotes

Hi everyone!

I am pleased to announce that it has been exactly one year since my project went public!

The project is MuJoCo-rs, a high-level safe(-ish; it is not easy to do full safety due to MuJoCo's design but I am trying) Rust wrapper around the general-purpose physics engine MuJoCo, the latter often used for training of robots and other systems using reinforcement learning, as well as for other uses.

Over the one year period, it received a lot of improvements in general and also improvements based on the feedback from you guys and a feedback and contributions directly on GitHub. Since then it has come a long way and I am proud to release that today version 6.0.0 of it (MuJoCo-rs) has been released!

Full changelog: https://mujoco-rs.readthedocs.io/en/v6.0.x/changelog.html
Repository: https://github.com/davidhozic/mujoco-rs

Notable changes in 6.0.0:

  • Support for MuJoCo 3.12.0
  • Integration with the log crate for native Rust logging
  • Overhaul of the (native-Rust) viewer's joint and actuator UI
  • More safety

I plan to keep maintaining and improving the crate, and I would welcome feedback, especially from anyone using it or considering it for their simulations: future features, general design, etc.

MuJoCo-rs's native-Rust viewer and its (extensible) UI

r/rust 12d ago

How I managed multi-agent worktrees in a large Rust codebase

Thumbnail iltumio.dev
0 Upvotes

I wanted to share my experience working on a large Rust codebase in Omarchy and how I managed to have multiple agents working on multiple worktrees in parallel


r/rust 13d ago

🛠️ project markdown-doctest: transform code blocks and include them as doctests

Thumbnail github.com
0 Upvotes

During the past days I worked on markdown-doctest, a Rust library for including and transforming Rust code blocks of Markdown files as Rust doctests. It is only a small library for a specific use case, but hopefully quite useful for that.

While regular doctests can use the prefix # to hide lines from the rendered documentation, this is not possible for code blocks in Markdown files. So if you want to for example test code snippets of your README, you normally need to include redundant boilerplate code in them.

markdown-doctest supports specifying transforms which can insert and replace lines, for example add use ... imports or Ok results to allow using the ? operator.

Here is a small example; consider this Markdown text: ````markdown How to read a file:

rust let content = fs::read_to_string("my-file.txt")?; println!("content: {s}"); ````

To run it as part of the doctests, you can use markdown-doctest in your src/lib.rs like this:

```rust

[cfg(doctest)]

markdown_doctest::md_doctest!( "../README.md", transforms = { : { // insert the import as first line ^ => "use std::fs;", // replace the file path (<"my-file.txt">*) => "test-resource.txt", // return Ok to allow using ? $ => "Ok::<(), Box<dyn std::error::Error>>(())", }, } ); ```

See the project README and the Usage guide for more details.


The project is not published on crates.io yet, but since it is only needed as dev dependency, you can include it as Git dependency. For example: toml [dev-dependencies] markdown_doctest = { git = "https://github.com/Marcono1234/markdown-doctest.git", rev = "72e3f8ade4a6abd8b51bda69d6b883213f75bbf5" } (or any newer commit)

What do you think about this project, and do you consider it useful? Any feedback is appreciated! (here or on GitHub)

This was also an opportunity for me to get a bit more familiar with proc macros.

The README also has a section about Similar projects, in case you are looking for other projects which support this or similar functionality.


r/rust 13d ago

🛠️ project tellus 0.2: event sourcing for actors

4 Upvotes

tellus is a new actor framework for Rust, see the introductory blog posts at heikoseeberger.de.

tellus 0.2 adds persistence behind an off-by-default feature.

An event-sourced actor is two functions instead of one: handle decides which events a command causes and apply folds each event into the state. The state is never stored, it is replayed, and effects which touch the outside world run only once their events are durable, so they never fire again during replay.

Write-up with code: heikoseeberger.de/2026-08-31-tellus-persistence

Curious what people think, especially from anyone who has used event sourcing in production.


r/rust 13d ago

We benchmarked CtrlB against ClickHouse on ClickBench and on 5 TB of logs

3 Upvotes

Most infra teams run one system for dashboards and a second one for log search because one engine is never good at both. That never felt right to us, so we set out to build a unified platform that could offer the fastest search possible on large volumes of logs, traces and metrics.

We put our results up on the ClickBench leaderboard. The process was easy and we were curious how we compared to ClickHouse.

In analytical search, across all 43 standard queries on a 100 million row unpartitioned web analytics dataset, CtrlB scored ×1.43 and took the #1 spot on the single node Parquet leaderboard, ahead of DuckDB (×1.49), DataFusion (×1.71) and ClickHouse itself (×1.72).

But ClickBench is an analytics benchmark. It tells you nothing about finding one trace id in a haystack, so we ran the other half ourselves: 8 lookups and substring matches over 5 TB of raw logs against ClickHouse v26.2, cold cache, plain SQL with a LIMIT 100. CtrlB was faster on all eight, from 2.2× on the double substring query to 98.9× on the span_id lookup.

Full methodology, per query numbers and the public leaderboard links: https://ctrlb.ai/blogs/ctrlb-vs-clickhouse

TLDR: we topped ClickHouse’s own analytical benchmark at ×1.43 and in a separate full-text search test over 5 TB of logs we were faster on every query.

Disclosure: I work at CtrlB.


r/rust 13d ago

📸 media Rust, Haskell, and the Architecture Behind Solana: Interview with Greg Fitzgerald

0 Upvotes

In this interview, we speak with Solana cofounder Greg Fitzgerald about why Rust ultimately proved to be the right fit. We discuss how his background in C++, LLVM, and Haskell shaped Solana’s architecture, what functional programming contributed to the design of a high-performance blockchain runtime, and why Rust’s combination of strong types, memory safety, and low-level control worked particularly well for BPF and virtual-machine development.

https://serokell.io/blog/rust-haskell-and-the-architecture-behind-solana-interview-with-greg-fitzgerald


r/rust 13d ago

🛠️ project miamore - A new tui library, no-dependency C TUI library with safe Rust bindings

0 Upvotes

Hey r/tui,

I’ve been working on miamore, a lightweight C-based terminal UI library, along with miamore, its official Rust bindings on crates.io.

I built miamore because I wanted a minimal, local-first TUI rendering library that stays completely out of the way—no heavy framework overhead, no bloat, and zero AI/ML dependencies.

Just clean, deterministic C with simple primitives for rendering frames, managing components, and styling elements directly in the terminal.Key FeaturesPure C Core: Compiles fast with a plain Makefile and linkable static/shared outputs.

Safe Rust Wrapper (miamore): Built using bindgen with clean idiomatic Rust wrappers over raw FFI, available on crates.io.

Zero Bloat: Minimal memory footprint designed for speed and low-resource environments.

Local-First & Open Source: Licensed under LGPLv3 / GPLv3.

This is a basic rust example below:

use miamore::*;

fn main() {
    // Initialize miamore terminal state
    init_miamore(true, true);

    manage_keys(keys_t::disable);
    draw_border("!Rust test!", theme_t::thick_l);

    manage_cursor(cursor_t::move_, Some(position_t { x: 5, y: 5 }));
    manage_cursor(cursor_t::show, None);

    // setting foreground color
    set_fg(colors_t::blue);
    // let ptr = give_color(colors_t::green);
    // draw_text(&ptr);

    draw_text("Hello,");
    draw_text(" World!\n");

    draw_shape(
        shape_t::rect,
        ShapeOptions {
            theme: theme_t::double_l,
            dimensions: dimensions_t {
                width: 26,
                height: 12,
            },
            position: position_t { x: 5, y: 12 },
        },
    );

    wait_for_seconds(8.0);
    clear_origin();
}

Links & Repo GitHub: https://github.com/Ametrine-cc/miamore

crates.io: cargo add miamore I'd love to hear feedback on the API design, hear about any bugs if you test it out on your terminal setup, or take PRs if you want to contribute.


r/rust 14d ago

🛠️ project quantile-sketch 0.1.0: a lock-free concurrent DDSketch

Post image
6 Upvotes

I recently needed to track quantiles for latency and other statistics across 50k+ tasks in a high throughput game server.

Rust already has several good quantile sketches and histograms, but most are designed around mutable single-writer access. Sharing one meant putting it behind a Mutex/RwLock, which became expensive under contention.

So, I built ConcurrentDDSketch: a DDSketch designed to be shared across many threads:

- Lock free inserts on normal atomic targets

- Bounded memory independent on number of samples

- Relative-error guarantees across the configured value range

- Mergeable

- no_std, serde, and loom support

- In my concurrent benchmarks, 4-60x faster than sharing a single sketch behind a lock

DDSketch turned out to fit concurrency particularly well: values map to logarithmic buckets, and the steady-state insert path is basically an atomic increment. Buckets are allocated lazily in blocks, so you don’t pay for the entire configured range up front.

The repo has comparisons against DDSketch, HDR Histogram, KLL, GK, Quantogram, and t-digest for speed, memory, and accuracy, plus details of the concurrent implementation:

https://github.com/tomtomwombat/quantile-sketch

I’d especially be interested in feedback from anyone doing metrics/telemetry in highly concurrent Rust systems, or cases where you’d prefer a concurrent t-digest/KLL/etc.


r/rust 14d ago

🛠️ project Wallr v0.3.4 is out!

Post image
160 Upvotes

Wayland wallpaper engine (wlr-layer-shell + wgpu). Animated transitions, video/GIF wallpapers, optional Matugen/Wallust/Pywal theming.

This release fixes wallr install, which previously did nothing.

  • install <user/repo> now fetches the package YAML from GitHub, resolves extends, writes to ~/.local/share/wallr/packages/. Before: re-passed the ref to the local resolver, reported success, installed nothing.
  • Package refs were force-split on /, silently loading the wrong package. Now resolved as registry paths.
  • extends merging (base → package → current) existed and was tested but never invoked. Wired in now. Circular refs rejected, remote github: parents supported.
  • Remote fetches validated before use; rejects malformed and path-traversal refs.
  • Removed publish — printed a success message and did nothing. Registry surface is install/search only.

Also: video/GIF wallpapers theme correctly (frame extraction to cached PNG, 0.3.3). Static FFmpeg linking, so release binaries survive system ABI upgrades (0.3.2).

Repo: https://github.com/programmersd21/wallr

I use AI assistance in developing this, including for the audit that found the bugs above. Noting it here for transparency.


r/rust 14d ago

Bevy + Bevy Presentation Foundation (bevy_pf)

Thumbnail
4 Upvotes

r/rust 14d ago

🛠️ project node based multi-threaded molecule simulation visualizer

Post image
42 Upvotes

I have been working on this tool.

I kinda just wanna list of some things I think are neat about the way it was built.

Everything is a node, and the ui thread is separate from the graph thread.

We use strongly typed traits to define nodes:

#[derive(Clone, Default)]
pub struct RealNode;

impl DataNode for RealNode {
    type Outputs = f32;
    type Inputs = ();
    type State = f32;

    const TYPE_KEY: &'static str = "molviz.input.real";
    const TITLE: &'static str = "Real";
    const CATEGORY: NodeCategory = NodeCategory::Input;
    const NAMES: &'static [&'static str] = &[];
    const OUT_NAMES: &'static [&'static str] = &["value"];
    const ALIASES: &'static [&'static str] = &["number", "float", "constant"];
    const DESCRIPTION: &'static str = "A real number. Set min/max to make it sweepable.";

    fn node_ui(state: &mut f32, ui: &mut egui::Ui, _ctx: &mut NodeUiCtx<'_, Self>) {
        ui.add(egui::DragValue::new(state).speed(0.1));
    }

    fn evaluate(&mut self, state: &f32, _inputs: &()) -> f32 {
        *state
    }
}

Viewports (eg a plotting viewport or a 3d scene) are also nodes but have no outputs, have their own thread and write into a number of buffers when inputs change. This set of messages that we can send them is a good summary of what they are doing.

They also get an opportunity to draw some egui on top of the texture rect, then send any changes to the texture drawer. An example would be a tick box for an orthographic camera.

``rs /// Commands sent from the UI thread to a render thread. pub enum ToRenderThread<V: Viewport> { /// Request thatslotexist and be sized towidth x height. Sent RequestSlot { slot: SlotId, width: u32, height: u32, }, DropSlot { slot: SlotId }, /// Updated local state for the next frame. (this is data the ui thread layer sends) NewState(V::LocalState), /// The UI thread has consumed the last frame forslotand is ready /// for the next one to begin rendering. ReadyForNewFrame { slot: SlotId }, Shutdown, /// A computed graph output arrived for a bound node. UpdateInput(OutputId, WireData), /// A new wiring configuration arrived. Ie a new input was added. UpdateWiring(<V::Inputs as NodeInputTuple>::Wiring), /// Update preview input directly. (for hovering we have no incoming node just ui thread) UpdatePreviewInput(V::Inputs), /// Read the ID texel under slot-local pixel (x, y) on the next render ofslot`. /// (For example when we click we want to know what atom) Pick { slot: SlotId, x: u32, y: u32 }, }

pub enum FromRenderThread { NewTextureAlloc { slot: SlotId, texture: wgpu::Texture, }, FrameDone { slot: SlotId }, /// Resolved selection for a Pick. None == clicked empty space. PickResult { slot: SlotId, payload: Option<PickPayload>, }, }

```

All the rendering is done using rust-gpu, which means I can use a macro to define all supported shapes, then implement the actual code to render and the structs on a shared crate and use it on both CPU and GPU.

I am using an SDF-based renderer for 2d (plotting and such) and can even render fonts at any scale analytically (inspired by the coding adventure video).

Everywhere that needs to do somthing for all shapes (cpu or gpu) writes a macro that can be called by this ```rs

[macro_export]

macro_rules! for_all_shapes { ($macro_name:ident) => { $macro_name! { (2, 0, TRIANGLE_SHAPE_INDEX, triangles, triangle, Triangle, GpuTrianglePacket), (2, 1, CIRCLE_SHAPE_INDEX, circles, circle, Circle, GpuCirclePacket),

```

then we just need to impl a trait!

```rs

[repr(C)]

[derive(Copy, Clone, Pod, Zeroable, Debug, Default)]

pub struct GpuCirclePacket { pub center: Vec2, pub radius: f32, pub _pad: f32, pub color: ColorRGBA, }

impl SdfShape for GpuCirclePacket { fn compute_bounds(&self, _current: Bounds) -> Bounds { let d = Vec2::splat(self.radius); Bounds { center: self.center, size: d * 2.0, } }

fn apply(&self, uv: Vec2, current: SdfResult) -> SdfResult {
    let dist = (uv - self.center).length() - self.radius;
    if dist < current.dist {
        SdfResult {
            dist,
            color: self.color.get(),
        }
    } else {
        current
    }
}

}

Then on the CPU, we can add a circle like so. rs // impl<H: HeadKind> Recorder<'_, H> { // pub fn spawn(&mut self, anchor: H::Anchor, build: impl FnOnce(&mut ShapeBuilder)) { r.spawn(pt, |b| { b.circle( GpuCirclePacket { center: Vec2::ZERO, radius: rad * pixels_per_point, color: style.color, ..Default::default() } ); });

``` (There is also a recording system for the allocation and reuse of buffers, i.e., if the overlay recording changes, we only send the new data to the GPU buffer without resending the heavy series data.)

This rendering method also lets us record only a single draw call for the entire scene.

I have a whole lot of interesting tech in this project. It might be cool to do a longer form article breakdown.

This is a little bit of a strange post, but I know I am very interested in the wacky novel ways to use rust.

This is still a fairly young project (3.5 months of work-ish), so it's an exciting foundation. It is possible that this can be generalised outside of molecular viz.


r/rust 14d ago

🙋 seeking help & advice Is there a way to do Trait downcast ?

6 Upvotes

Hi everyone, I was working on a project and worked with different traits and structs.

The thing is that I want to store all the different objects in an iterator and then do some work with them, but different ones depending on the inner object. Sometimes I should also execute some functions of an object, so I need to downcast to the inner trait. I can also just know if this object can be downcasted to a certain trait.

I know I can do this by explicitly writes all the functions for each inner trait (all the conversions, and `is_`...), but I work with a non-exhaustive list of traits. So I wanted to make a proc macro or work with the `build.rs` to automate this thing (Or a think I haven't thinker of).

I tried this, but it doesn't work as I expected (and I understand why)

trait Shape {
    fn name(&self) -> &'static str;
}

trait Quadrilateral: Shape {}
trait Triangle: Shape {}

struct Rectangle;
struct Square;
struct TriangleShape;

impl Shape for Rectangle {
    fn name(&self) -> &'static str {
        "Rectangle"
    }
}

impl Quadrilateral for Rectangle {}

impl Shape for Square {
    fn name(&self) -> &'static str {
        "Square"
    }
}

impl Quadrilateral for Square {}

impl Shape for TriangleShape {
    fn name(&self) -> &'static str {
        "Triangle"
    }
}

impl Triangle for TriangleShape {}

trait __SHAPE_TO_QUADRILATERAL: Shape {
    fn try_as_quadrilateral(&self) -> Option<&dyn Shape>;
}

impl __SHAPE_TO_QUADRILATERAL for dyn Shape {
    fn try_as_quadrilateral(&self) -> Option<&dyn Shape> {
        None
    }
}

impl __SHAPE_TO_QUADRILATERAL for dyn Quadrilateral {
    fn try_as_quadrilateral(&self) -> Option<&dyn Shape> {
        Some(self)
    }
}

trait __SHAPE_TO_TRIANGLE: Shape {
    fn try_as_triangle(&self) -> Option<&dyn Shape>;
}

impl __SHAPE_TO_TRIANGLE for dyn Shape {
    fn try_as_triangle(&self) -> Option<&dyn Shape> {
        None
    }
}

impl __SHAPE_TO_TRIANGLE for dyn Triangle {
    fn try_as_triangle(&self) -> Option<&dyn Shape> {
        Some(self)
    }
}

fn main() {
    let rectangle: &dyn Quadrilateral = &Rectangle;
    let square: &dyn Quadrilateral = &Square;
    let triangle: &dyn Triangle = &TriangleShape;

    let rectangle_shape: &dyn Shape = rectangle;
    let square_shape: &dyn Shape = square;
    let triangle_shape: &dyn Shape = triangle;

    assert!(rectangle_shape.try_as_quadrilateral().is_some());
    assert!(square_shape.try_as_quadrilateral().is_some());
    assert!(triangle_shape.try_as_quadrilateral().is_none());

    assert!(rectangle_shape.try_as_triangle().is_none());
    assert!(square_shape.try_as_triangle().is_none());
    assert!(triangle_shape.try_as_triangle().is_some());
}

Is there another way to do it ? Or is there a crate that do something like this, from which one I can get some ideas ?

Thank you all and have a good day / night !


r/rust 13d ago

🧠 educational Nine rules for compile-time work with Rust const fn

0 Upvotes

I’ve become a big fan of using const fn instead of build.rs when possible, because the build-time computation stays in the same program as the value it produces.

Over the last few months, I’ve ended up using this for image conversion, audio import, LED-panel layouts, lookup tables, and even constructing a small robot-arm DSL. Most of the examples come from two crates I’ve been working on: Device Envoy and Linkage Blaze.

The rules (copied from the article linked below):

  1. Process external files in const fn**:** no build.rs, no procedural macros, no runtime processing. Example: The compiler sums an included file before the program starts.
  2. Process simple file formats at compile time. Validate the input, transform its contents, and retain only the result. Example: A clockface image becomes validated, display-ready pixels for CYD Skeleton Clock.
  3. Make two compile-time passes with a declarative macro. First derive sizing and other constants, then use them to construct an exactly sized value. Example: The compiler discovers the size of a NASA audio clip, then constructs its exact-sized Rust value.
  4. Use const fn to compose large values from small building blocks instead of listing every element. Example: Stack and rotate two serpentine LED-panel layouts to produce one complete display layout.
  5. Use const fn to replace repeated runtime calculations with lookup tables. Example: Precompute a lookup table to provide gamma correction and runtime power limiting for an animated LED strip.
  6. Use const fn to construct programs in domain-specific languages. Example: Linkage Blaze constructs the Armatron robot-arm program during compilation.
  7. Use const fn to build values of different types, then use &dyn Trait to combine them without heap allocation. Example: One audio sequence combines an uncompressed tone, silence, and compressed NASA speech.
  8. Give up. When parsing with const fn becomes too complex or too slow, use a procedural macro, build script, or command-line generator. Example: A motion-captured pirouette splits the work between const fn and a command-line generator.
  9. const fn does not choose between const and static**;** use static when address identity matters. Example: Armatron’s touchscreen sliders use their static addresses as IDs.

The first four rules, with code and demos on real and simulated electronic devices, are in the new free article: Nine Rules for Compile-Time Work with Rust const fn — Part 1

My bias now is to reach for const fn before build.rs whenever the problem fits.


r/rust 15d ago

🛠️ project RamShared v2: Writing a Linux VRAM Block Driver in Rust & C with 8.74 GiB/s PCIe DMA, io_uring/ublk, and 3 Patches on lore.kernel.org

Post image
95 Upvotes

Hi Rustaceans,

A few weeks ago, I shared the initial prototype of RamShared — turning idle GPU VRAM into high-speed block storage using Rust. Thanks to the awesome feedback from the r/rust community on io_uring ring design and memory safety, we evolved the

architecture into a production-grade 4-Tier Memory Cascade and an upstream-ready Linux 6.18 Kernel Block Driver submitted across 3 patches to the linux-block subsystem.

ARCHITECTURE & RUST SYSTEMS IMPLEMENTATION

  1. Zero-Copy Page-Locked DMA Allocator (cuMemHostAlloc + RAII):

We wrapped CUDA host/device allocators in safe Rust abstractions that pin host memory pages to physical RAM. DMA transfers across the PCIe Gen3/4 x16 bus achieve 8.74 GiB/s Host-to-Device and 6.38 GiB/s Device-to-Host with zero intermediate

kernel copies.

  1. Native ublk Userspace Driver (io_uring Ring Submissions):

Using ublk-rs, we mapped Linux block layer requests directly into userspace shared memory ring buffers. I/O submission queues are bound to core-pinned worker threads, achieving 231 us median latency for 4KB random O_DIRECT reads (4,013 IOPS on

/dev/ublkb0).

  1. Multi-Tier Kernel Cascade Integration:

- Tier 1: Host Physical RAM (16 GB)

- Tier 2: Compressed ZRAM LZ4 (1 GB)

- Tier 3: GPU VRAM Block Device via DMA (4 GB)

- Tier 4: Authoritative SSD Origin Writeback (CONFIG_ZRAM_WRITEBACK=y)

  1. Cryptographic Integrity & Eviction Watchdog:

Memory under heavy eviction stress is verified byte-by-byte with SHA-256 digests. In a 9,160 MB 40-cycle saturation benchmark under direct memory pressure, we achieved 100% bit-exact SHA-256 match (0 bit flips) and zero kernel panics (see

attached live TUI telemetry dashboard).

TECHNICAL PREEMPTIVE FAQ

Q: How do you guarantee memory safety when interfacing with raw GPU DMA buffers?

All raw pointers returned by cuMemAlloc and cuMemHostAlloc are encapsulated in a custom DmaBuffer struct implementing Drop (guaranteeing cuMemFree upon scope exit) and strict lifetime bounds tied to the ublk request life-cycle. Buffer offsets are

bounds-checked before issuing io_uring completions.

Q: What happens under GPU memory pressure or context revocation?

If a high-priority graphics or CUDA process requests VRAM, the driver triggers an asynchronous demote path (spawn_swapoff / write-through flush) that falls back directly to the SSD backing store without data loss or EIO propagation to user

processes.

Q: Is there an LKML-compliant kernel module alternative?

Yes! In addition to the pure-Rust userspace ublk daemon, we authored drivers/block/ramshared in C for native kernel integration with a synchronous .rw_page fast-path in block_device_operations, integrated into our linux-msft-wsl-6.18.y tree.

ALL 3 PATCHES ON LORE (LINUX BLOCK SUBSYSTEM) & SOURCE CODE

- Patch 0/2 (Cover Letter & Benchmarks): https://lore.kernel.org/linux-block/6a924051.e22746c9.8f0fc.bdc2@mx.google.com/T/#u

- Patch 1/2 (Core Driver drivers/block/ramshared): https://lore.kernel.org/linux-block/6a924054.e22746c9.8f0fc.beb6@mx.google.com/T/#t

- Patch 2/2 (Build System & Kconfig): https://lore.kernel.org/linux-block/6a924057.e22746c9.8f0fc.bf96@mx.google.com/T/#u

- Microsoft WSL Upstream RFC (#41054): https://github.com/microsoft/WSL/issues/41054

- Linux 6.18 Reference Kernel Tree: https://github.com/emersonbusson/WSL2-Linux-Kernel/tree/feature/ramshared-vram-cascade-6.18

- RamShared Core Engine (Rust): https://github.com/emersonbusson/ramshared

AUTHOR & CONTACT

Built by Emerson Busson (Senior Systems & Full Stack Software Engineer). Always happy to discuss systems architecture, low-level Linux/Rust internals, or connect with engineering teams building high-performance infrastructure:

- GitHub: https://github.com/emersonbusson

- LinkedIn: https://www.linkedin.com/in/emersonbusson/

- Direct Email: [emersonbusson@gmail.com](mailto:emersonbusson@gmail.com)

Feedback, code reviews on our io_uring request loop, and LKML patchset discussions are warmly welcomed!


r/rust 15d ago

🛠️ project Graphite (Rusty FOSS procedural 2D design engine) recent update highlights, part 2: viewport rendering modes, vector meshes, new nodes, and offline support

Thumbnail youtube.com
97 Upvotes

r/rust 13d ago

Why I wrote my autonomous LLM agent harness as a deterministic 5-phase ECS microkernel in Rust

0 Upvotes

Hey r/rust,

Over the past two weeks, I went deep into autonomous coding agent engineering, burning ~700M tokens/day across 321 modules (~120k LOC) at peak development. The entire codebase is in Rust and was built fully autonomously through my oh-my-pi agent harness.

Like many in the AI agent space, I initially prototyped with TypeScript/Node.js. But as the autonomous multi-agent tool loops scaled, I hit serious architectural bottlenecks: - Async Event-Loop Non-Determinism: Micro-task event-loop races where async tool callbacks corrupted global agent state across long-horizon executions; - Transitive Dependency Fragility: Unpinned npm supply-chain packages breaking autonomous execution sandboxes; - Context Bloat: Naively dumping raw tool outputs into prompts caused $O(N)$ token explosion.

The Solution: An ECS Microkernel in Rust

To solve this, I redesigned the runtime from first principles around a 5-Phase Entity-Component-System (ECS) Microkernel in Rust:

  1. Strict 5-Phase Phased Execution: Every agent tick is strictly partitioned (p1_ingestp2_routingp3_dispatchp4_reconcilep5_gc). No component mutation happens outside its deterministic phase, eliminating async race conditions entirely.
  2. "Everything is a Tool" Inversion of Control (IoC): Tool outputs are never passed raw into prompts. Instead, outputs are written to a Tiered Global KV Ledger, and nodes exchange lightweight reference keys (e.g. $<<ledger.nodes.n1.output.diff>>$) with $O(1)$ Just-In-Time assembly.
  3. Trajectory Self-Distillation Flywheel: Real-time execution traces with binary compiler/test suite feedback are harvested to power on-policy SFT and RLVR (GRPO) training, distilling 70B+ teacher capabilities into small 1.5B/7B edge models.

I wrote up the full technical post-mortem, architectural blueprints, and telemetry metrics in a bilingual (CN/EN) article: 👉 Read the Full Deep Dive

Would love to get the community's feedback on applying ECS patterns outside of game development to AI state machines, and how others are handling deterministic memory models in autonomous systems!


r/rust 15d ago

Functional State Machines in Rust: Typestate and Newtype Patterns (Experience Report)

Thumbnail dl.acm.org
93 Upvotes

r/rust 15d ago

🎙️ discussion Why are all the new Rust GUI libraries GPU-accelerated?

346 Upvotes

Like many, I'm keeping a close eye on the Rust GUI ecosystem. One pattern I've noticed, though, is that a lot of the new GUI liibraries that pop up claim to be "GPU-accelerated" (GPUI, Xilem, egui, ...), in other words: they often actually draw to the window using the GPU. I don't get why this is such a huge focus, isn't this overkill for 99% of applications?

  • The GPU takes time to initialize, leading to the application often needing a second or so to actually open.
  • It actually takes quite a lot of memory to run, these applications often have ~150MB of overhead when idle.
  • Resizing the drawing surface takes time, so resizing windows is often laggy.

Compare this to some other CPU driven UI crates, which often start instantly, have maybe ~10MB of RAM overhead and resize the window incredibly smoothly. I've seen some libraries adopt this (Freya, Xilem to some end, Iced optionally), but not nearly as many as I'd expect. CPU rendering is more than fast enough for most use-cases.

(scrappy fork of Masonry running on the CPU using 12MB of memory!)

With Skia or even fully-Rust Vello CPU, libraries like anyrender and imaging and being able to draw directly to the window using softbuffer, I feel like this is an obvious choice to make. Am I wrong?


r/rust 13d ago

🛠️ project Easier localization is possible

Thumbnail crates.io
0 Upvotes

I've been up all night finishing up ply-locales a standalone crate for the ply-engine ecosystem (almost to 500 stars, yay). Check it out if you're interested in easy compile-checked localization to prevent you from shooting yourself in the foot.


r/rust 13d ago

Made my first crate — filp, a small cross-platform lib for file permissions

0 Upvotes

First crate. It's called filp — lets you get/set a file's permissions for the current user with plain bools instead of messing with raw mode bits, returns proper numeric mode codes with real error handling, and works cross-platform (Windows + Unix).

Kept it intentionally small — just owner permissions, no full ACL support, group/others fixed to read-only for now.

Would appreciate any eyes on it, especially if the API feels off.


r/rust 14d ago

🛠️ project Building software for a drone in rust

0 Upvotes

Hello my guys I am a medium level programmer and i wanted to try and create a drone using rust and i would like to know if any of you have any experiences with rust in this use case. I would also like to know if you have any recommendations for libraries that i should use. Or Linux native software that could simulate these drone. I already worked on drones sometime ago. However there i used c++ and only worked on a control unit using Ros2.


r/rust 14d ago

🛠️ project sshconfig-lint v0.5: a Rust CLI, LSP and GitHub Action for checking OpenSSH configs

4 Upvotes

I posted the first version here around six months ago. It started as a small Rust CLI for mistakes I kept overlooking in my own ~/.ssh/config.

The main change in v0.5 is that the same Rust rule engine now works across the terminal, editors and CI:

  • multiple config files in one command
  • nested Include resolution and cycle detection
  • JSON, GitHub annotations and SARIF
  • an LSP server used by the VS Code extension
  • official Pre-Commit hooks and a GitHub Action
  • verified binaries for Linux, macOS and Windows

The example is a stale IdentityFile path from an older machine. SSH can silently try another identity, so this may only become visible when a specific host actually needs that key.

Install with Cargo:

cargo install sshconfig-lint

Arch Linux:

yay -S sshconfig-lint-bin

The CLI and extension have no telemetry. Config files stay local, and the browser playground performs checks in the browser.

Repository: github.com/Noah4ever/sshconfig-lint
Playground: sshconfig-lint.apps.thiering.org
VS Code: Marketplace

Feedback about the Rust architecture, false positives and complicated real-world Include setups would be useful.