ages

Beyond Rust’s Ownership: Branded Types, GhostCell, and Thread-Safe Arenas

Lifetime subtyping and variance

Variance comes hand in hand with Rust’s lifetime subtyping concept as substitution is only possible in certain cases. A type that features a generic input like &mut T, &T, Cell<T> can either be variant in its lifetime argument or generic argument. Most types are covariant in their lifetime parameter. That means that we can substitute longer lasting references where shorter ones were expected. Contravariance is the inverse of covariance and invariance specifies no subtyping. Rust can use variance in combination with PhantomData<T> to represent branded types.

Thread safety through branded types (GhostCell)

GhostCell<T> promises to be a true zero-cost-abstraction compared to all the existing thread safe cell types inside the standard library like Mutex<T> and RwLock<T>. It does so through a design of permission and data splitting, which stands in stark contrast to Rust’s normal approach, where permission to data are directly bound together via its type (either &T or &mut T). The splitting requires two types: GhostCell<'id, T> which wraps the data and GhostToken<'id> that represents ownership of that data. The token and cell are both branded by an invariant lifetime parameter that inherently links them together at compile time.

Important to note here is that the token does not actually take up any memory at runtime and can rather be seen as a guide to the type system. As we can see below, there is no actual data that it holds, just a lifetime that acts as a compile time identifier. PhantomData<T>, which only exists at compile time, is key to express such compile time patterns. Because Rust features lifetime subtyping, it is critical to specify that the compiler rejects programs where one tries to access a GhostCell<'id, T> by using a GhostToken<'id2> with a different lifetime. The type pattern *mut &'id () inside the PhantomData<T> specifies this exact requirement. In Rust jargon, that means that the lifetimes have to be invariant.

/// An invariant lifetime--required in order to link GhostCell to Token (1-1)
#[derive(Clone, Copy, Default)]
struct InvariantLifetime<'id>(PhantomData<*mut &'id ()>);
impl<'id> InvariantLifetime<'id> {
#[inline]
const fn new() -> InvariantLifetime<'id> {
InvariantLifetime(PhantomData)
}
}
pub struct GhostToken<'id> {
_marker: InvariantLifetime<'id>,
}

A question that naturally arises is: “If GhostToken<'id> does not hold any data at runtime, how does the actual synchronization between multiple threads work?” The term “zero-cost-abstraction” mentioned at the beginning does not mean that there is no synchronization at all, just that the abstraction is as performant as doing it manually. We distinguish between two cases.

  1. Multiple threads read the data only. As no mutation happens in this case we can safely create multiple shared references to the token. This works because the borrow(&self) function on the GhostCell<'id, T> counterpart only requires a shared reference (Sync) to the token.
  2. Mutation occurs and we need synchronization. In that case, the token can be wrapped in any synchronization primitive like RwLock<T>. Whenever a thread wants to access the underlying data, it needs to first acquire a lock on the token. The mutable reference returned can then be used to call borrow_mut() on the cell counterpart. The token statically makes sure that synchronization happens before accessing data, without taking up any space in memory.

In essence, this pattern lets us create a fully typed “zero cost” synchronization scheme on a function call granularity. Acquiring the token (type) that lets us call a mutating function on linked list is as performant as doing it manually via an e.g. semaphore + critical section approach.

To now see why GhostCell<T>’s unique approach of splitting the permission from the data itself is useful in our doubly-linked list example, consider the case where we want to lock the whole list for a thread instead of on a per-node basis. If we used a Vec<T> that has one large block of backing memory, we could simply use RwLock<Vec<T>> to synchronize the access. But when it comes to our doubly-linked list, handing out temporary ownership becomes cumbersome, and just wrapping Node is semantically different to the Vec<T> case. In their paper, Yanovski et al. also show that their permission model can be paired with arena allocators as a backing memory store to simplify the implementation.

use ghost_cell::{GhostCell, GhostToken};
use typed_arena::Arena as TypedArena;
pub struct Node<'arena, 'id, T> {
data: T,
prev: Option<NodeRef<'arena, 'id, T>>,
next: Option<NodeRef<'arena, 'id, T>>,
}
pub type NodeRef<'arena, 'id, T> = &'arena GhostCell<'id, Node<'arena, 'id, T>>;
impl<'arena, 'id, T> Node<'arena, 'id, T> {
pub fn new(
data: T,
arena: &'arena TypedArena<Node<'arena, 'id, T>>,
) -> NodeRef<'arena, 'id, T> {
GhostCell::from_mut(arena.alloc(Self {
data,
prev: None,
next: None,
}))
}
pub fn insert_next(
node1: NodeRef<'arena, 'id, T>,
node2: NodeRef<'arena, 'id, T>,
token: &mut GhostToken<'id>,
) {
Self::remove(node2, token);
let node1_old_next: Option<NodeRef<_>> = node1.borrow(token).next;
if let Some(node1_old_next) = node1_old_next {
node1_old_next.borrow_mut(token).prev = Some(node2);
}
node1.borrow_mut(token).next = Some(node2);
let node2: &mut Node<_> = node2.borrow_mut(token);
node2.prev = Some(node1);
node2.next = node1_old_next;
}
pub fn remove(node: NodeRef<'arena, 'id, T>, token: &mut GhostToken<'id>) {
let old_prev = node.borrow(token).prev;
let old_next = node.borrow(token).next;
if let Some(next) = old_next {
next.borrow_mut(token).prev = old_prev;
}
if let Some(prev) = old_prev {
prev.borrow_mut(token).next = old_next;
}
}
pub fn iter_mut(
node: NodeRef<'arena, 'id, T>,
token: &mut GhostToken<'id>,
mut f: impl FnMut(&mut T),
) {
let mut cur: Option<NodeRef<'arena, 'id, T>> = Some(node);
while let Some(node) = cur {
let node = node.borrow_mut(token); // mutably borrow `node` with `token`
f(&mut node.data);
cur = node.next;
}
}
}

Layout differences and shortcomings

The first major difference that strikes is that there are two lifetime parameters. Although both are Rust lifetimes, they each serve drastically different purposes. The first one is a normal reference to the arena. The second one acts as a brand type that uniquely pairs GhostCell<'id, T> with GhostToken<'id> as previously mentioned. The second difference is that there is no DoublyLinkedList<'arena, 'id, T> struct that holds a reference to an Arena<T> from typed-arena. The reason for this choice can be seen in the following adapted client example:

fn main() {
GhostToken::new(|mut token| {
let arena = TypedArena::new();
let mut tail = list;
(1..20).for_each(|i| {
let node = Node::new(i, &arena);
Node::insert_next(tail, node, &mut token);
tail = node;
});
let token: RwLock<GhostToken> = RwLock::new(token);
rayon::join(
|| {
let token: &GhostToken = &token.read().unwrap();
print_list('r', list, token);
},
|| {
let token: &mut GhostToken = &mut token.write().unwrap();
Node::iter_mut(list, token, |n| {
*n += 100;
print!("w{:?} ", n);
});
let new_node = Node::new(10, &arena); // ERROR
},
);
});
}

Although powerful, pairing GhostCell with typed-arena has one major drawback:

  • Mutating already existing nodes in the lists is perfectly fine.
  • Creating a new node inside the thread and appending it is however not possible, as allocation needs to interact with the arena-allocator in some way. As typed-arena is not Sync due to an internal RefCell<T>, we get a compilation error.

GhostCell<T> can thus only manage data that has already been allocated and does not abstract over the creation of new items in the list. In the end, it is only a thin wrapper around the pointers to the individual items and completely disconnected from the arena concept. Depending on the usecase, it is either possible to accept this shortcoming, opt for a more flexible mechanism based on Arc<T>, or even use a thread safe arena altogether. Nevertheless, GhostCell’s concept of splitting data from permission shows how it can be leveraged to make use of a popular thread local arena like the typed-arena and safely use it in a multithreaded environment.

Pairing GhostCell with thread safe arena allocators

bumpalo-herd’s API pairs well with GhostCell. It wraps bumpalo to make it Sync. Instead of using a TypedArena as previously demonstrated, we leverage the herd concept that allows us to distribute bump allocators to the different threads. Collectively, all abstracted Bumps represent an arena and allow allocation through the corresponding Member<'_> struct.

The Herd struct manages these bump allocators (members) and behaves similarly to Vec<T> in that it does not create any allocators on Herd::new() but rather on demand. Importantly, the items allocated by the individual Member structs can outlive the member struct itself, as the arena remains alive even when the Member<'_> is dropped. Although the allocated bumps can be cached once the corresponding Member goes out of scope, they are only ever reset collectively at the end of the herd’s lifetime when there are no more references to the backing memory remaining. Note that in this context, caching does not mean individually resetting each bump. Internally, Herd stores multiple Bumps inside a Mutex<Vec<Box<Bump>>>. Similar to the concept of bumpalo, Herd does not execute destructors for the stored values. It thus resembles a collection of user-managed, reusable “substacks” that provide extremely fast allocation.

pub struct Member<'h> {
arena: ManuallyDrop<Box<Bump>>,
owner: &'h Herd,
}
impl Drop for Member<'_> {
fn drop(&mut self) {
let mut lock = self.owner.0.lock().unwrap();
let member = unsafe { ManuallyDrop::take(&mut self.arena) };
lock.push(member);
}
}

A fascinating aspect of the bumpalo-herd API is that it demonstrates how we can extend a lifetime in Rust beyond what is conventionally permitted through the use of unsafe casting. The return value of the inner call to Bump::alloc(&self, T) is transformed through the extend function below. This arises as the reference to the function calls differs from the lifetime of the owned reference to the herd. The safety of this approach is ensured by two factors. First, the owned Bump is allocated on the heap behind a Box<T>, which in turn ensures that the memory does not move out of the live references even when returned inside the drop function. Second, because the Box<Bump> is wrapped inside a ManuallyDrop<T>, we can prevent manual memory deallocation. This means that to return the memory into the Herd’s list, a lock must be acquired followed by a non-panicking push operation.

impl<'h> Member<'h> {
pub fn alloc<T>(&self, val: T) -> &'h mut T {
self.extend(self.arena.0.alloc(val))
}
fn extend<'s, T: ?Sized>(&'s self, v: &'s mut T) -> &'h mut T {
let result = v as *mut T;
unsafe { &mut *result }
}
}

Conclusion

In conclusion, we can say that Rust’s ownership system synergizes well with multiple different arena implementations. On the one hand, arenas greatly simplify the difficulties one would experience in Rust without them. They also enable patterns and types that would not work otherwise. Conversely, Rust’s powerful ownership and lifetime system empowers the arena concept. Preventing bugs like dangling references into the arena through its lifetime tracking greatly improves safety compared to less strict arenas like those in C.

Excerpts from my bachelor’s thesis at TU Wien: Beyond Rust’s Ownership: Exploring Arena-Allocators in conjunction with statically safe interior mutability in Rust (March 2025).