fitzgen / bumpalo

A fast bump allocation arena for Rust
https://docs.rs/bumpalo
Apache License 2.0
1.41k stars 111 forks source link

Add Vec::bump method #189

Closed mattfbacon closed 1 year ago

mattfbacon commented 1 year ago

This PR adds a way to get the Bump allocator backing a Vec, for example to make more allocations if the Vec contains other bump-allocated data structures.

One common example of this is a bump-allocated recursive data structure. Consider:

use bumpalo::Bump;
use bumpalo::collections::Vec;

struct Tree<'bump> {
    value: i32,
    children: Vec<'bump, Self>,
}

impl Tree<'bump> {
    fn new(value: i32, bump: &'bump Bump) -> Self {
        Self {
            value,
            children: Vec::new_in(bump),
        }
    }

    fn add_child(&mut self, value: i32) {
        self.children.push(Self::new(value, self.children.bump()));
    }
}

Without this PR, Recursive would be forced to carry an extra shared reference to the Bump.