Skip to content

issues with Lifetime branding example #125

Description

The example as written fails to compile when we uncomment the code:

fn main() {
    with_arena(|arena1| {
        let handle1 = arena1.alloc("hello".to_string());
        println!("{}", arena1.get(&handle1)); // ✅

        // Can't use handle1 with a different arena — compile-time error
        with_arena(|arena2| {
            arena2.get(&handle1); // ❌ borrowed data escapes outside of closure
        });
    });
}

If we rearrange the code a bit:

fn main() {
    with_arena(|arena1| {
        // Can't use handle1 with a different arena — compile-time error
        with_arena(|arena2| {
            let handle1 = arena1.alloc("hello".to_string());
            println!("{}", arena1.get(&handle1)); // ✅
            arena2.get(&handle1); // ❌ borrowed data escapes outside of closure
        });
    });
}

This compiles - even though it isn't supposed to.

By moving the brand to the Arena instead of keeping it on the ArenaHandle it works as intended:

/// A handle branded to a specific arena instance.
/// Invariant over 'arena — prevents using a handle from one arena with another.
struct ArenaHandle<'arena> {
    index: usize,
    _phantom: PhantomData<&'arena ()>,
}

/// An arena that brands each handle with its unique lifetime.
struct Arena<'arena> {
    data: RefCell<Vec<String>>,
    _brand: PhantomData<*mut &'arena ()>,
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions