【Rust】メモリ管理

const FRAME_SIZE: usize = 4096;
const TOTAL_MEMORY: usize = 1024 * 1024 * 128;
const TOTAL_FRAMES: usize = TOTAL_MEMORY / FRAME_SIZE;

static mut FRAME_BITMAP: [bool; TOTAL_FRAMES] = [false; TOTAL_FRAMES];

pub struct FrameAllocator;

impl FrameAllocator {
    pub fn alloc() -> Option<usize> {
        unsafe {
            for (i, used) in FRAME_BITMAP.iter_mut() enumerate() {
                if !*used {
                    *used = true;
                    return Some(i * FRAME_SIZE);
                }
            }
            None
        }
    }

    pub fn dealloc(addr: usize) {
        let index = addr / FRAME_SIZE;
        if index < TOTAL_FRAMES {
            unsafe {
                FRAME_BITMAP[index] = false;
            }
        }
    }
}