5 releases
Uses old Rust 2015
0.1.4 | Oct 8, 2015 |
---|---|
0.1.3 | Oct 7, 2015 |
0.1.2 | Oct 6, 2015 |
0.1.1 | Oct 6, 2015 |
0.1.0 | Oct 5, 2015 |
#685 in Memory management
16KB
334 lines
Scoped Allocator
This crate provides a scoped linear allocator. This is useful for reusing a block of memory for temporary allocations in a tight loop. Scopes can be nested and values allocated in a scope cannot be moved outside it.
struct Bomb(u8);
impl Drop for Bomb {
fn drop(&mut self) {
println!("Boom! {}", self.0);
}
}
// new allocator with a kilobyte of memory.
let alloc = ScopedAllocator::new(1024).unwrap();
alloc.scope(|inner| {
let mut bombs = Vec::new();
for i in 0..100 { bombs.push(inner.allocate_val(Bomb(i)).ok().unwrap())}
// watch the bombs go off!
});
let my_int = alloc.allocate_val(23).ok().unwrap();
println!("My int: {}", *my_int);
Disclaimer: this crate leans heavily on unsafe code and nightly features and should not be used in production as it stands.
lib.rs
:
A scoped linear allocator. This is useful for reusing a block of memory for temporary allocations within a tight inner loop. Multiple nested scopes can be used if desired.
Examples
use scoped_allocator::{Allocator, ScopedAllocator};
struct Bomb(u8);
impl Drop for Bomb {
fn drop(&mut self) {
println!("Boom! {}", self.0);
}
}
// new allocator with a kilobyte of memory.
let alloc = ScopedAllocator::new(1024).unwrap();
alloc.scope(|inner| {
let mut bombs = Vec::new();
// allocate_val makes the value on the stack first.
for i in 0..100 { bombs.push(inner.allocate_val(Bomb(i)).ok().unwrap())}
// watch the bombs go off!
});
let my_int = alloc.allocate_val(23).ok().unwrap();
println!("My int: {}", *my_int);