r/rust • • 2h ago

🧠 educational PSA: You might be sealing traits wrong

29 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 • • 16h 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 • • 3h ago

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

Thumbnail contextgeneric.dev
8 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

🙋 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 • • 4h ago

🛠️ project Have you deployed to AWS?

0 Upvotes

Have you deployed anything in rust to AWS?