Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. extern crate alloc;
  2.  
  3. use alloc::alloc::{GlobalAlloc, Layout, alloc_zeroed};
  4.  
  5. struct MyAllocator;
  6.  
  7. const MAX_MEMORY: usize = 1024;
  8.  
  9. struct MemoryStruct {
  10. curr: usize,
  11. mem: [u8; MAX_MEMORY]
  12. }
  13.  
  14. impl MemoryStruct {
  15. pub fn left(&self) -> usize {
  16. self.mem.len() - self.curr
  17. }
  18. pub fn get_curr_ptr(&mut self) -> *mut u8 {
  19. &mut self.mem[self.curr] as *mut _
  20. }
  21. }
  22.  
  23. static mut MEMORY: MemoryStruct = MemoryStruct {curr: 0, mem: [0u8; MAX_MEMORY]};
  24.  
  25. unsafe impl GlobalAlloc for MyAllocator {
  26. unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
  27. println!("hey");
  28. if layout.size() > MEMORY.left() {
  29. panic!("Stack overflow");
  30. }
  31. let diff = layout.size() % layout.align();
  32. let ptr = MEMORY.get_curr_ptr();
  33. MEMORY.curr += layout.size() + diff;
  34. ptr
  35. }
  36. unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
  37. }
  38.  
  39. #[global_allocator]
  40. static A: MyAllocator = MyAllocator;
  41.  
  42. fn main() {
  43. unsafe {
  44. let layout = Layout::new::<[u32; 5]>();
  45. println!("layout size: {:?}", layout);
  46. // let a = alloc_zeroed(layout);
  47. // let b = &*(a as *mut [u32; 5]);
  48. // println!("{:?}", b);
  49.  
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement