self_cell 0.8.0

Safe-to-use proc-macro-free self-referential structs in stable Rust.
Documentation

Overview

self_cell provides one macro-rules macro: [self_cell]. With this macro you can create self-referential structs that are safe-to-use in stable Rust, without leaking the struct internal lifetime.

In a nutshell, the API looks roughly like this:

// User code:

self_cell!(
struct NewStructName {
#[from]
owner: Owner,

#[covariant]
dependent: Dependent,
}

impl {Debug}
);

// Generated by macro:

struct NewStructName(...);

impl NewStructName {
fn new(owner: Owner) -> NewStructName { ... }
fn borrow_owner<'a>(&'a self) -> &'a Owner { ... }
fn borrow_dependent<'a>(&'a self) -> &'a Dependent<'a> { ... }
}

impl Debug for NewStructName { ... }

Self-referential structs are currently not supported with safe vanilla Rust. The only reasonable safe alternative is to expect the user to juggle 2 separate data structures which is a mess. The library solution ouroboros is really expensive to compile due to its use of procedural macros.

This alternative is no_std, uses no proc-macros, some self contained unsafe and works on stable Rust, and is miri tested. With a total of less than 300 lines of implementation code, which consists mostly of type and trait implementations, this crate aims to be a good minimal solution to the problem of self-referential structs.

It has undergone community code review from experienced Rust users.

Fast compile times

$ rm -rf target && cargo +nightly build -Z timings

Compiling self_cell v0.7.0
Completed self_cell v0.7.0 in 0.2s

Because it does not use proc-macros, and has 0 dependencies compile-times are fast.

Measurements done on a slow laptop.

A motivating use case

use self_cell::self_cell;

#[derive(Debug, Eq, PartialEq)]
struct Ast<'a>(pub Vec<&'a str>);

impl<'a> From<&'a String> for Ast<'a> {
fn from(code: &'a String) -> Self {
// Placeholder for expensive parsing.
Ast(code.split(' ').filter(|word| word.len() > 1).collect())
}
}

self_cell!(
struct AstCell {
#[from]
owner: String,

#[covariant]
dependent: Ast,
}

impl {Clone, Debug, Eq, PartialEq}
);

fn build_ast_cell(code: &str) -> AstCell {
// Create owning String on stack.
let pre_processed_code = code.trim().to_string();

// Move String into AstCell, build Ast by calling pre_processed_code.into()
// and then return the AstCell.
AstCell::new(pre_processed_code)
}

fn main() {
let ast_cell = build_ast_cell("fox = cat + dog");
dbg!(&ast_cell);
dbg!(ast_cell.borrow_owner());
dbg!(ast_cell.borrow_dependent().0[1]);
}
$ cargo run

[src/main.rs:33] &ast_cell = AstCell { owner: "fox = cat + dog", dependent: Ast(["fox", "cat", "dog"]) }
[src/main.rs:34] ast_cell.borrow_owner() = "fox = cat + dog"
[src/main.rs:35] ast_cell.borrow_dependent().0[1] = "cat"

There is no way in safe Rust to have an API like build_ast_cell, as soon as Ast depends on stack variables like pre_processed_code you can't return the value out of the function anymore. You could move the pre-processing into the caller but that gets ugly quickly because you can't encapsulate things anymore. Note this is a somewhat niche use case, self-referential structs should only be used when there is no good alternative.

Under the hood, it heap allocates a struct which it initializes first by moving the owner value to it and then using the reference to this now Pin/Immovable owner to construct the dependent inplace next to it. This makes it safe to move the generated SelfCell but you have to pay for the heap allocation.

See the documentation for [self_cell] to dive further into the details.

Or take a look at the advanced examples: