Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate alloc;
- use alloc::alloc::{GlobalAlloc, Layout, alloc_zeroed};
- struct MyAllocator;
- const MAX_MEMORY: usize = 1024;
- struct MemoryStruct {
- curr: usize,
- mem: [u8; MAX_MEMORY]
- }
- impl MemoryStruct {
- pub fn left(&self) -> usize {
- self.mem.len() - self.curr
- }
- pub fn get_curr_ptr(&mut self) -> *mut u8 {
- &mut self.mem[self.curr] as *mut _
- }
- }
- static mut MEMORY: MemoryStruct = MemoryStruct {curr: 0, mem: [0u8; MAX_MEMORY]};
- unsafe impl GlobalAlloc for MyAllocator {
- unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
- println!("hey");
- if layout.size() > MEMORY.left() {
- panic!("Stack overflow");
- }
- let diff = layout.size() % layout.align();
- let ptr = MEMORY.get_curr_ptr();
- MEMORY.curr += layout.size() + diff;
- ptr
- }
- unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
- }
- #[global_allocator]
- static A: MyAllocator = MyAllocator;
- fn main() {
- unsafe {
- let layout = Layout::new::<[u32; 5]>();
- println!("layout size: {:?}", layout);
- // let a = alloc_zeroed(layout);
- // let b = &*(a as *mut [u32; 5]);
- // println!("{:?}", b);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement