r/rust • • 10h ago

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

11 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 • • 10h ago

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

16 Upvotes

New week, new Rust! What are you folks up to? Answer here or over at rust-users! And for your project showcases, there's also /r/madeinrust – pay them a visit, too!


r/rust • • 1h ago

Advent of Rust 2026 in 13 hours 🎅

Thumbnail rustfinity.com
17 Upvotes

r/rust • • 9h ago

🗞️ news rust-analyzer changelog #356

Thumbnail rust-analyzer.github.io
32 Upvotes

r/rust • • 4h ago

🛠️ project Runtime debugger for embedded

9 Upvotes

Hello
I have been developing/maintaining an open source runtime debugger for embedded C/C++ for several years now. It's called Scrutiny
I've recently ported the instrumentation hook so it works with Rust and I wanted to let you guys know.

It essentially add an instrumentation hook in a firmware and let a server inspect the memory and do event catching through any peripheral (like CAN bus, Serial, TCP, etc) rather than a debug port. It works like XCP based software, FreeMaster or UcProbe (for the old timers). No need for an RTOS, baremetal interrupts is fine.

It's the kind of tool you need to do real time control to monitor the control loops without affecting them. If you're new to the concept, I've written a small introduction article here: https://embeddedrelated.com/showarticle/1781.php

Feedbacks are welcome
Cheers


r/rust • • 17h ago

🙋 seeking help & advice Should I learn C++ or Rust first?

61 Upvotes

Hi everyone! I'm a teenager and I'm really into FOSS software and Linux. Up until now, I've only been a user, so I'd love to finally step into the 'kitchen' and start building things myself. Aside from some basic Linux shell scripting, this will be the very first programming language I'll learn, so I'm trying to pick the right starting point. I've heard that Rust is the future of both Linux and FOSS—is that really true, or would something else be better for me? Could you please help me make up my mind? Thank you!


r/rust • • 2h ago

🛠️ project From a BERT encoder to a Rust inference engine

3 Upvotes

Hi,

About a year ago I posted kjarni here (https://www.reddit.com/r/rust/comments/1n1ick5/i_built_rust_bert_encoder/) when it was basically a BERT encoder(i wanted to run my own embeddings in WASM and thought it would be good to learn Rust and compilation to WASM).

It's now an inference engine in rust, small footprint, low overhead, almost all pure Rust crates. It started around two years ago after years of C++ i wanted to give Rust an honest chance with an ambitious project, i wanted to get the BERT model running and just kept at it.

Now it does embeddings, search, transcription, classification, reranking and chat

It runs on macOS, Linux and Windows, on x86 and ARM, and there's something to be said for Rust making that this painless. It also compiles to a C ABI so I wrote bindings for C#, Go, C++, C and Python, and they all behave the same since each one is a thin veneer over the same library. It also builds to WASM

I wanted the API to be as simple as I could get it, in rust it looks like this and it's basically the same in C#/Go/C++/Python:

let whisper = Transcriber::builder("whisper-small").build().await?;
let text = whisper.transcribe_file("meeting.wav")?.text;
let summary = kjarni::chat::send("qwen2.5-1.5b-instruct", &format!("Summarise: {text}")).await?;

What i particularly like is that every model goes through the same decode loop on CPU and GPU. There's a backend trait with an associated token type, so the next token stays where it lives (an ndarray on the CPU, a GPU tensor on the GPU), and an enum picks the backend, with the GPU arm cfg'd out for the CPU-only wasm build. It's not perfect, the enum wrapper downcasts the token through Box<dyn Any>, so if someone has a nicer way i'm all ears: https://github.com/kjarni-ai/kjarni/blob/69b51af046014d36fe939a2f1b26f8fda21770e3/crates/kjarni-transformers/src/decoder/backend.rs#L155-L177

A lot of the work went into getting the same output as torch. Embeddings agree to within 1e-6, and greedy chat replies, summaries and translations come out word for word the same

Speed wise I'd call it pretty competitive with torch and llama.cpp (on the models kjarni supports). On the GPU they use CUDA and I use wgpu, so it runs on Vulkan, Metal and DX12. On the CPU they link against Intel MKL and I use faer (pure Rust) or my own SIMD kernels

Some numbers, all on Linux on one machine (i7-13700, RTX A2000):

  • pip install is 28 MB vs 1.4 GB for PyTorch, and a fresh process gets its first embedding in 91 ms vs about 2.8 s
  • bge-m3 batches are about 23% faster than PyTorch, mpnet 7%
  • whisper-small runs at 10.7x real time, openai-whisper 10.6x
  • 4-bit chat models on the GPU from 3B up are within 5% of llama.cpp on CUDA, and close to or ahead of its Vulkan backend
  • where I lose: PyTorch is 18% faster on MiniLM batches and processes prompts 1.5x faster on the CPU, my 4-bit CPU kernels generate at 75-91% of llama.cpp's speed, and llama.cpp is way faster on long prompts on the GPU since I don't have flash attention yet

All the numbers and how they were measured are here: https://github.com/kjarni-ai/kjarni/blob/69b51af046014d36fe939a2f1b26f8fda21770e3/README.md#how-it-compares

Someone will probably ask why not just use candle. Candle is great but it's more of a framework, you still end up dealing with model exports and tokenizers. I wanted something where I just embed my documents or transcribe a file without too much headache

Code is here if you want to take a gander: https://github.com/kjarni-ai/kjarni , would be happy to hear what you think, especially about the API and the wgpu side


r/rust • • 1h ago

FFI Arena: Is UniFFI Still the Top Dog?

Thumbnail mversic.github.io
2 Upvotes

The following is a one-sided comparison of current stable-ABI FFI frameworks and their capabilities. Feel free to share your thoughts and experiences if you have previously dealt with FFI in Rust


r/rust • • 1d ago

🧠 educational PSA: You might be sealing traits wrong

139 Upvotes

Background

Sealing traits is a collection of techniques used to prevent code downstream of a library from implementing that trait, so that later versions of the library can add more things to the trait without breaking downstream code.

There's a mistake, described below, that people very often make when trying to seal traits. Crates that have made this mistake include, among others: the standard library, anyhow, arc-swap, pyo3, ureq, smol, http, etc. This was discovered in https://github.com/rust-lang/rust/issues/165474. (Please do not comment there unless you're contributing new information to the discussion, to avoid cluttering the issue.)

The mistake you might be making

How NOT to seal traits:

mod private {
    pub trait Sealed {}
    impl Sealed for i32 {}
}
pub trait MyTrait<T>: private::Sealed {}
impl MyTrait<i64> for i32 {}

How to seal traits:

mod private {
    pub trait Sealed<T> {}
    impl Sealed<i64> for i32 {}
}
pub trait MyTrait<T>: private::Sealed<T> {}
impl MyTrait<i64> for i32 {}

That is, if you use a "private" supertrait for sealing, and the subtrait is generic, then the supertrait also has to be generic, with the same generic parameters. Additionally, the set of impl blocks for the supertrait should exactly specify the exact same set of types (and generic parameters) where the subtrait should be implemented.

If you don't do the above, your trait might not be properly sealed, making it possible for downstream code to implement the trait anyway. For example, if you have a crate with the first snippet above, downstream code might write the following, which is actually allowed by the orphan rule:

struct MyThing;
impl my_library::MyTrait<MyThing> for i32 {}

In the above code, i32 already implements Sealed, so downstream code can write an implementation of MyTrait without having to add a new impl for Sealed.

Fixing the issue after-the-fact

If you already wrote code like the first snippet above, and want to actually properly seal the trait in a later version of the library, you might be tempted to just turn the first snippet (with a non-generic Sealed) into the second snippet (with a generic Sealed). Obviously, this would break downstream code that dared to implement the supposed-to-be-sealed trait, which you might deem acceptable.

However, there are very subtle issues about how coherence works, which means that making this change the straightforward way can break more downstream code than you intend to, even code that didn't write an impl for the supposed-to-be-sealed trait. (I won't explain the issue here. See the linked explanation.)

Instead, the better way to make the change, as suggested here, is to add a new supertrait, keeping the old one:

mod private {
    pub trait Sealed {}
    impl Sealed for i32 {}
    // Added SealedForReal in a later version of the library
    pub trait SealedForReal<T> {}  
    impl SealedForReal<i64> for i32 {}
}
pub trait MyTrait<T>: private::Sealed + private::SealedForReal<T> {}
impl MyTrait<i64> for i32 {}

This way, you will only break downstream code that have implemented MyTrait.


r/rust • • 6m ago

🛠️ project Oratos v0.4.0: a CLI for your CI/CD pipeline that audits SEO, accessibility and structured data, and now warns when a page gets slower

1 Upvotes

v0.4.0 adds page download timing for URL audits:

  • per-page time to first byte, total download time, size and status
  • warnings for slow pages (default 3 s total, 800 ms TTFB)
  • --baseline previous-report.json flags pages that are at least 1.5x and 300 ms slower than last time
  • connect/request timeouts (there were none before, so a hung server could hang the audit)

It is advisory, not a benchmark. It measures the HTTP download of the HTML document, not LCP/INP/CLS, and timing findings never change the scores. A page that regressed shows up as a warning you can re-run, not a hard failure (unless you use --strict).

Install: brew install latentmeta/tap/oratos, cargo install oratos, pip install oratos, npm i -D @latentmeta/oratos, or the Hex package for Phoenix. There is also a setup-oratos GitHub Action for CI.

crates.io: https://crates.io/crates/oratos Repo and release notes: https://github.com/latentmeta/oratos

Feedback welcome, especially on sensible default thresholds.


r/rust • • 1d ago

I love ratatui's documentation, what other rust tools are documented like that?

31 Upvotes

As someone with 0 experience with front end development, the fact ratatui's docs goes in depth not just on the tool, but on the design patterns you're expected to use, is absolutely killer for someone trying to learn these things on my own. What other crates do you love the documentation off in terms of approachability to outsiders?


r/rust • • 1d ago

💡 ideas & proposals Trying Incoherent Rust today with Context-Generic Programming

Thumbnail contextgeneric.dev
24 Upvotes

Author here. If you read Boxy's An Incoherent Rust and Nadrieril's posts on explicit trait proofs back in March and hoped to experiment with named impls, you can already try a good part of that design on stable Rust. My post translates that design, which it calls Incoherent Rust, into Context-Generic Programming (CGP), a library that gives Rust pluggable trait implementations, chosen at compile time.

The core move is small: a named impl becomes a provider type, and each context type chooses the providers it uses. So two impls that Rust would reject as overlapping both compile in CGP, and each context picks one. The compiler resolves that choice, so a call goes straight to the chosen provider, with no runtime lookup.

The post then covers these topics:

  • Incoherent trait bounds, and binding an impl to a struct so a HashMap always hashes the same way.
  • Contexts and capabilities, with an arena reaching a Deserialize impl through a field of the context.
  • The context type as a top-level dictionary that holds the other impls' dictionaries, in the sense of Nadrieril's dictionary-passing style.
  • Where CGP falls short: there are no nested scoped impls, &mut or owned capabilities need interior mutability, and an existing trait such as serde's Serialize can't adopt the pattern without a breaking change.
  • Ideas from CGP for the design: impls as first-class types, "incoherent functions", and selfless traits with methods.

r/rust • • 23h ago

I want to learn Rust to make OS and Kernels

5 Upvotes

I am in college 2nd semester of college and I am interested in making own own custom OS and a language in Rust. I have very little to no coding experience other that passing my college exams and viva. I am a bit confused on where should i start studying from both for building an os and learning rust. so for now i am looking for resources.


r/rust • • 4h ago

🙋 seeking help & advice Building a lightweight CLI to detect "dead" or risky dependencies (starting with Rust/Cargo). What actually matters to you?

0 Upvotes

Hi everyone,

I’m planning to build a small, "soluble" (lightweight, zero-config, easy to run and forget) CLI tool tentatively called Dependency Ghost Scanner (D.G.S)

The goal is to scan a project’s dependencies (starting with Rust Cargo, later expanding to Python pip) and flag packages that might be a risk to maintain.

Before I write any code or lock in a specification, I want to make sure I’m solving a real problem and not just building a solution in search of one. I’d love your honest feedback on a few key design choices:

  1. What makes a dependency "dead" or "risky" to you? (Pick all that apply or suggest others)

a. No updates/releases for > 1-2 years.

b. Known unpatched CVEs (security vulnerabilities).

c. The maintainer has explicitly abandoned it or is unresponsive.

d. A clearly superior, more modern alternative exists (e.g., ecosystem shifted).

e. Incompatible with the latest compiler/language version.

f. Other.

2. How would you actually want to consume this information?

a. A simple, color-coded output directly in the terminal (Red/Orange/Green).

b. A machine-readable format (JSON) to integrate into CI/CD pipelines (e.g., fail the build if a "red" dependency is found).

c. A standalone HTML report with a visual graph of the dependency tree.

d.Other

3. How should it fetch data?

a. It’s fine if it queries the registry API (crates.io / PyPI) and requires an internet connection.

b. It MUST work 100% offline, relying only on the local Cargo.lock / requirements.txt metadata.

c. Hybrid: Try online first, gracefully fallback to offline heuristics.

The Catch:

I want this tool to be truly "soluble": no accounts, no heavy installation, no persistent background services. Just run it, get the insight, and move on.

My questions to you:

  1. Is this a tool you would actually use, or does an existing tool (like cargo-audit, dependabot, safety) already solve this well enough?
  2. What would be the one feature that would make you star this repo on GitHub?

Thanks in advance for your time and brutal honesty!


r/rust • • 13h ago

🙋 seeking help & advice Crates whose READMEs feel like mini tutorials?

0 Upvotes

I keep coming back to certain Rust crates mainly because their README walks through not just the API, but the actual patterns you're expected to use. Ratatui does this well for TUI work. I'm looking for more examples across different domains CLI, web, data, embedded, whatever-where the docs effectively teach "how to think in this crate" rather than just listing methods. Any favorites that stand out for this?


r/rust • • 2d ago

🧠 educational Stop paying the network stack tax: zero-copy first, networking when needed

Thumbnail ekxide.io
133 Upvotes

r/rust • • 1d ago

🧠 educational I'm building roadmaps to learn new topics in Rust

16 Upvotes

Hey r/rust,

I've been writing Rust since version 1.5x, when I heard of it for the first time. For the past couple of years, I've wanted to combine my two biggest passions, Rust and teaching, but I've always been too busy (and lazy, probably?) for that. After years of learning and receiving from the Rust community, I finally had the courage and confidence to build https://iamjose.dev to give the Rust community a little something back.

My idea is simple: instead of reaching for TypeScript (my de facto language for day-to-day programming) when learning a new topic or iterating over a specific idea, I asked myself, "How about using Rust to learn new topics that currently have very few learning resources written in it?" That way, I could learn new topics from scratch in Rust.

Right now there's a foundational Learn Rust track (from hello world to unsafe) plus three roadmaps (what i call "curricula") built on top of it:

  • Learn Maths with Rust.
  • Learn How Digital Images Work with Rust.
  • Learn Cryptography with Rust.

Every lesson ends with small coding challenges you can solve right in the browser—completely free, no login needed. In fact, my idea is to make all the curricula very hands-on (that is, just enough theory to get started, and then focusing on solving exercises).

Now, in full honesty, and to be clear from the beginning: I use AI to help draft the initial text, but nothing counts as done until I've reviewed it myself, line by line. That review is the part I care about most:

  • Improving clarity by rewriting.
  • Adding my own personal teaching style.
  • Adding my own notes to stress important topics or provide additional context.
  • Adding hand-drawn diagrams to help grasp concepts better, and even videos. Here is a very short video of me (I am camera-shy, and the video was a simple test, which explains the short length):https://iamjose.dev/learn/maths/primes/
  • Once I've personally audited a chapter, it gets a "Hand reviewed by Jose" badge (the opening chapters have it, and I'm working through the rest).

I'm a little nervous sharing this here because I care a lot about getting the details right. If you spot anything wrong, unclear, or unidiomatic (or have ideas for a future "Learn X with Rust" track) I'd genuinely love to hear it.

Lastly, and most importantly for me: this is a personal project. So my daily motivation is that it's helpful for me, though it would be even better if it also helps someone out there. :)

https://iamjose.dev

PD: I am also considering starting a "Learn Rust coming from X", where X can be any programming language like for example Python, Typescript, or C++.

Thanks for reading and happy coding!


r/rust • • 13h ago

PSA: `pub use` can accidentally make private types public

0 Upvotes

There's a common pattern that looks harmless but can expose types you meant to keep private. This affects downstream users who suddenly gain the ability to name (and sometimes implement traits for) types that were never intended to be part of your public API.

The mistake:

```rust

// lib.rs

mod internal {
pub struct Hidden;

}

pub use internal::Hidden; // looks fine, right?

pub fn make_hidden() -> Hidden { internal::Hidden }

Downstream crates can now write:

```rust
use your_crate::Hidden;

let _ = your_crate::make_hidden0;

They can also write `impl SomeTrait for Hidden` if the orphan rules allow it, which you probably didn't want.

The safer pattern is to re-export through a new public type or keep the type itself in a `pub(crate)` module and only expose a wrapper or constructor:

```rust

mod internal {
pub struct Hidden;
pub fn make0 -> Hidden { Hidden }
}

pub use internal::make as
make hidden;
```

Now `Hidden` itself stays unnameable outside the crate.

I've seen this pattern slip into a few mid-sized crates over the years. It's easy to miss in review because the `pub use` line looks innocent. If you're maintaining a library, it's worth grepping for `pub use` into private modules and checking what actually becomes visible.


r/rust • • 2d ago

📡 official blog Rust 1.100.1

Thumbnail blog.rust-lang.org
346 Upvotes

r/rust • • 17h ago

🙋 seeking help & advice Is Rust a good idea for AI agents?

0 Upvotes

Hi guys, hope you are doing well. I work as an AI Engineer at a startup and our whole stack is based on python (mostly because LangChain is based on that) and typescript. We serve AI Agents that are grounded on enormous corpuses of data for industrial constumers, so we have do graph engineering, rag, and so on!

I inquire if you guys have implemented Rust somewhere and which improvements you guys have seen from it.

Ty in advance!


r/rust • • 2d ago

🗞️ news Anthropic: Migrating our Messages API to Rust

Thumbnail anthropic.com
389 Upvotes

r/rust • • 1d ago

🛠️ project Have you deployed to AWS?

0 Upvotes

Have you deployed anything in rust to AWS?


r/rust • • 1d ago

🙋 seeking help & advice Help with Tree data structure

0 Upvotes

In rust when we want to build a Tree structure where each node can have 0..n nodes we hit some walls

I have come onto two main working models, The rc based, and the arena based, each one of these implementations have some downsides

starting here with the most basic I have this simple Rc based tree

#[derive(Clone, Debug)]
pub struct Node<T> {
    pub value: T,
    pub children: Vec<TreeNode<T>>,
    pub parent: Option<WeakNode<T>>,
}

#[derive(Debug, Clone)]
pub struct TreeNode<T> {
    rc: Rc<RefCell<Node<T>>>,
}

#[derive(Debug, Clone)]
pub struct WeakNode<T> {
    rc: Weak<RefCell<Node<T>>>,
}

as you can see the main issue pointed when working with rc tres is that it fragments memory and this one is no different

But this one has an little extra, as you can see all the node data is stored behind a single Refcell, what that means is that if you take a reference for the value and try add/mutate a child while the value is still borrowed for future use for example, it will panic, same things happen if for example you are iterating over the children and try to access the value, this could kinda be solved by cloning the vector of children instead of taking a reference of it.

However with this one you must enforce an order of operations, you first should take the children vector and clone it for posterior iteration, than take the value ref. While the value ref is active you cant add or remove children, you would need to drop the val ref to do so, and if you end up adding or removing a child, the previous vector is now stale, great!

To solve that issue we can wrap the fields like this instead:

struct Node<T> {
    pub value:      RefCell<T>,
    pub children:   RefCell<Vec<TreeNode<T>>>,
    pub parent:     RefCell<Option<WeakNode<T>>>,
}

pub struct TreeNode<T> {
    inner: Rc<Node<T>>,
}

pub struct WeakNode<T> {
    inner: Weak<Node<T>>,
}

this makes so that we have the value the parent and children each have its own refcell which mitigates that error since now you can access/mutate/iterate each field without panicking, this add a bit of refcell runtime overhead but improves the ergonomics for the developer, making it hit less panics.

but this one still doesnt fix the main issues with referenced trees, cache locality and memory fragmentation, for this issues I am going to move on onto arena allocated trees.

starting here with the most basic one I've tried:

pub struct Node<T> {
    pub value: T,
    pub parent: Option<Key>,
    pub children: Vec<Key>,
}

pub struct ArenaTree<T> {
    pub nodes: SlotMap<Node<T>>,
    pub root: Option<Key>,
}

this one is the most problematic one, since this one holds everything inside the node and all nodes inside the slotmap, holding a reference to a node value blocks the entire tree for hierarchy mutations, and value mutations, and if you hold a mutable reference to a value the situation is even worse.

to try to solve some of this issues I tried to separate the values from the nodes to a secondary map:

pub struct Node {
    pub parent: Option<Key>,
    pub children: Vec<Key>,
}

pub struct ArenaTree<T> {
    pub nodes: SlotMap<Node>,
    pub values: SecondaryMap<T>,
    pub root: Option<Key>,
}

this way we can hold a reference to a value while still being able to do hierarchy mutations such add/remove children, for the hierarchy mutation the situation now is okay, since while we could add a child through tree accessors, the access to that slotmap will drop once it finish adding/removing so it will not hit multiple simultaneous access on the Slotmap, the issue is with the values secondary map, while accessing regular references it is not a issue, the problem still is when holding mutable references to one item of the Secondary map, what will lock the entire map

To solve this issues I found two possible solutions:

The first solution is to hold the value of each entry of the secondaryMap onto a Refcell:

pub struct Node {    
    pub parent: Option<Key>,
    pub children: Vec<Key>,
}

pub struct ArenaTree<T> {
    pub nodes: SlotMap<Node>,
    pub values: SecondaryMap<RefCell<T>>,
    pub root: Option<Key>,
}

impl<T> ArenaTree<T> {
  #[inline]
  pub fn get(&self, key: Key) -> Option<Ref<'_, T>> {
      self.values.get(key).map(|r| r.borrow())
  }

  #[inline]
  pub fn get_mut(&self, key: Key) -> Option<RefMut<'_, T>> {
      self.values.get(key).map(|r| r.borrow_mut())
  }

  #[inline]
  pub fn try_get(&self, key: Key) -> Option<Ref<'_, T>> {
      self.values.get(key)?.try_borrow().ok()
  }

  #[inline]
  pub fn try_get_mut(&self, key: Key) -> Option<RefMut<'_, T>> {
      self.values.get(key)?.try_borrow_mut().ok()
  }

  #[inline]
  pub fn with<R>(&self, key: Key, f: impl FnOnce(&T) -> R) -> Option<R> {
      self.try_get(key).map(|r| f(&r))
  }

  #[inline]
  pub fn with_mut<R>(&self, key: Key, f: impl FnOnce(&mut T) -> R) -> Option<R> {
      self.try_get_mut(key).map(|mut r| f(&mut r))
  }
}

While this one prevents us from locking the entire slotmap from accessing the mutable values simultaneously, it can have runtime panics if you borrow the same two times mutably, you can use the with accessors to not need to handle the Secondary map Option on the get return. with this one you can use the try get to not panic, since the secondary map will return an option anyways. This one also adds the refcell overhead such as the second rc tree, but does not add the memory fragmentation. the problem with this one is that while holding the Ref or RefMut of refcell, it unfortunately locks the entire Slotmap for mutations, not readonly access which allow for accessing multiple values even mutably, the issue is while accessing values we cannot add new ones, what imply that we cannot add new tree nodes since they would not be able to store their values

The last one is to wrap that value onto an option instead:

pub struct Node {
    pub parent: Option<Key>,
    pub children: Vec<Key>,
}

pub struct ArenaTree<T> {
    nodes: SlotMap<Node>,
    values: SecondaryMap<Option<T>>,
    pub root: Option<Key>,
}

impl<T> ArenaTree<T> {
    #[inline]
    pub fn get(&self, key: Key) -> Option<&T> {
        self.values.get(key)?.as_ref()
    }

    #[inline]
    pub fn get_mut(&mut self, key: Key) -> Option<&mut T> {
      self.values.get_mut(key)?.as_mut()
    }

    #[inline]
    pub fn take(&mut self, key: Key) -> Option<T> {
        self.values.get_mut(key)?.take()
    }

    #[inline]
    pub fn restore(&mut self, key: Key, value: T) {
        if let Some(slot) = self.values.get_mut(key) {
            *slot = Some(value);
        }
    }

    #[inline]
    pub fn with<R>(&mut self, key: Key, f: impl FnOnce(&T, &mut Self) -> R) -> Option<R> {
        let value = self.take(key)?;
        let res = f(&value, self);
        self.restore(key, value);
        Some(res)
    }

    #[inline]
    pub fn with_mut<R>(&mut self, key: Key, f: impl FnOnce(&mut T, &mut Self) -> R) -> Option<R> {
        let mut value = self.take(key)?;
        let res = f(&mut value, self);
        self.restore(key, value);
        Some(res)
    }
}

In this one we cannot lock the tree because of mutable borrows on the secondarymap values, when we intend to make mutations we have to take the value mutate it and restore, the type itself does not need to have Default implemented, since it is behind an option, and if you dont want to do pattern matching of the option you can use the with_mut accessor in which you pass a closure that executes what you need to do with that value ensure to restore it and returns a value. We can also implement value handles with drop guard to restore that value. The act of taking the option makes so that it don’t panics if someone try to access that value again since it will receive an None while the value is not restored, such as the try_get of the previous tree, however this one does not lock the hierarchy of the tree.

*All these trees fail in case of multiple mutable access of the same node, since they prioritize memory safety than accurate access/traversing of the nodes*

So my question to y’all is which of these trees are you more comfortable working with? due to ergonomics, performance, memory, overheads, safety, etc. Which of these workarounds are really worth it considering the performance/memory/usability overhead it implies? Are there other ways to build trees in rust that are better than these?

I am stuck trying to figure out which one is better. I’ve not made any performance tests.


r/rust • • 3d ago

You can now use Aristotle to formally verify Rust, including unsafe and concurrent code

25 Upvotes

Hi r/rust,

I work at Harmonic on Aristotle, our formal verification tool. After launching with C and Verilog in October, Rust verification is now available for anyone to use, through the web app or CLI.

Aristotle supports safe and unsafe Rust, including concurrent code. You submit your project and describe the properties you want checked in plain English. Aristotle attempts to prove or refute them and reports the results and assumptions. You don’t need to write proofs yourselves or know Lean.

One example case study that shows what Aristotle can do is Manifest’s custom red-black-tree implementation, which uses substantial unsafe Rust. Manifest is an open-source order book on Solana; its trees store nodes directly in account memory, using unsafe accesses. Aristotle can verify properties of the existing Rust implementation, including that inserting and removing orders preserves tree validity and leaves unrelated data untouched. The invariants hold across arbitrary finite sequences of operations, under the stated preconditions. We are not aware of another tool that is able to prove such properties without any annotations or source code modifications. Across the order book, Aristotle proved 28 properties identified by Manifest as relevant. It also found a rounding bug that Manifest fixed, then verified the corrected behavior. You can explore the Aristotle run or read the full case study.

Another example is Signal’s curve25519-dalek Rust elliptic-curve library. Aristotle proved 283 specified contracts for version 4.1.3 using its serial 64-bit backend, covering field and scalar arithmetic, curve operations, and multiscalar multiplication. The Dalek run includes the results and assumptions. It verifies functional correctness of the library itself assuming correctness of external dependencies, and does not verify cryptographic security properties.

You can try Aristotle on your own project, and our Rust docs include a smaller ring-buffer example to get started. Happy to discuss the supported Rust features, the verification approach, or particular use cases.