1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use core::{alloc::Layout, cell::Cell};
use std::alloc::{alloc, dealloc};

use super::manager::{Dealloc, Manager};

#[derive(Debug, Clone, Copy)]
pub struct Global();

pub const GLOBAL: Global = Global();

impl Dealloc for Global {
    type BlockHeader = Cell<isize>;
    #[inline(always)]
    unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
        dealloc(ptr, layout)
    }
}

impl Manager for Global {
    type Dealloc = Global;
    #[inline(always)]
    unsafe fn alloc(self, layout: Layout) -> *mut u8 {
        alloc(layout)
    }
}

#[cfg(test)]
mod test {
    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::mem::{fixed::Fixed, manager::Manager};

    use super::GLOBAL;

    #[test]
    #[wasm_bindgen_test]
    fn test_i32() {
        let _x = GLOBAL.fixed_new(Fixed(0));
    }

    struct X<'a>(&'a mut i32);

    impl Drop for X<'_> {
        fn drop(&mut self) {
            *self.0 += 1;
        }
    }

    #[test]
    #[wasm_bindgen_test]
    fn test_x() {
        let mut i = 0;
        assert_eq!(i, 0);
        {
            let _ = GLOBAL.fixed_new(X(&mut i));
        }
        assert_eq!(i, 1);
    }
}