Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::mem;
- use std::cell::{Cell, UnsafeCell};
- #[derive(Clone)]
- pub struct Arena {
- offset: Cell<usize>,
- memory: Box<UnsafeCell<[u8]>>,
- }
- // Note Arena does *not* implement Sync or Send!
- impl Arena {
- pub fn new(capacity: usize) -> Arena {
- // Not sure how to allocate a `Box<UnsafeCell<[u8]>>` with only safe API...
- let memory: Box<[u8]> = vec![0; capacity].into_boxed_slice();
- Arena {
- offset: Cell::from(0),
- memory: unsafe { mem::transmute(memory) },
- }
- }
- pub fn alloc_bytes<'a>(&'a self, data: &[u8]) -> &'a [u8] {
- // Thread carefully around our memory buffer
- // FIXME! Is this even correct?!
- let memory = unsafe { &mut *self.memory.get() };
- // Allocate a subslice, bounds check done by the slicing code
- let len = data.len();
- let start = self.offset.get();
- let slice = &mut memory[start..start + len];
- self.offset.set(start + len);
- // Copy the data and return
- slice.copy_from_slice(data);
- slice
- }
- }
- fn main() {
- let arena = Arena::new(100);
- let slice = arena.alloc_bytes(&[1, 2, 3, 4, 5]);
- assert_eq!(slice, &[1, 2, 3, 4, 5]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement