Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. use std::mem;
  2. use std::cell::{Cell, UnsafeCell};
  3.  
  4. #[derive(Clone)]
  5. pub struct Arena {
  6. offset: Cell<usize>,
  7. memory: Box<UnsafeCell<[u8]>>,
  8. }
  9.  
  10. // Note Arena does *not* implement Sync or Send!
  11.  
  12. impl Arena {
  13. pub fn new(capacity: usize) -> Arena {
  14. // Not sure how to allocate a `Box<UnsafeCell<[u8]>>` with only safe API...
  15. let memory: Box<[u8]> = vec![0; capacity].into_boxed_slice();
  16. Arena {
  17. offset: Cell::from(0),
  18. memory: unsafe { mem::transmute(memory) },
  19. }
  20. }
  21.  
  22. pub fn alloc_bytes<'a>(&'a self, data: &[u8]) -> &'a [u8] {
  23. // Thread carefully around our memory buffer
  24. // FIXME! Is this even correct?!
  25. let memory = unsafe { &mut *self.memory.get() };
  26. // Allocate a subslice, bounds check done by the slicing code
  27. let len = data.len();
  28. let start = self.offset.get();
  29. let slice = &mut memory[start..start + len];
  30. self.offset.set(start + len);
  31. // Copy the data and return
  32. slice.copy_from_slice(data);
  33. slice
  34. }
  35. }
  36.  
  37. fn main() {
  38. let arena = Arena::new(100);
  39. let slice = arena.alloc_bytes(&[1, 2, 3, 4, 5]);
  40. assert_eq!(slice, &[1, 2, 3, 4, 5]);
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement