nanvm_lib/mem/
global.rs

1use core::{alloc::Layout, cell::Cell};
2use std::alloc::{alloc, dealloc};
3
4use super::manager::{Dealloc, Manager};
5
6#[derive(Debug, Clone, Copy)]
7pub struct Global();
8
9pub const GLOBAL: Global = Global();
10
11impl Dealloc for Global {
12    type BlockHeader = Cell<isize>;
13    #[inline(always)]
14    unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
15        dealloc(ptr, layout)
16    }
17}
18
19impl Manager for Global {
20    type Dealloc = Global;
21    #[inline(always)]
22    unsafe fn alloc(self, layout: Layout) -> *mut u8 {
23        alloc(layout)
24    }
25}
26
27#[cfg(test)]
28mod test {
29    use wasm_bindgen_test::wasm_bindgen_test;
30
31    use crate::mem::{fixed::Fixed, manager::Manager};
32
33    use super::GLOBAL;
34
35    #[test]
36    #[wasm_bindgen_test]
37    fn test_i32() {
38        let _x = GLOBAL.fixed_new(Fixed(0));
39    }
40
41    struct X<'a>(&'a mut i32);
42
43    impl Drop for X<'_> {
44        fn drop(&mut self) {
45            *self.0 += 1;
46        }
47    }
48
49    #[test]
50    #[wasm_bindgen_test]
51    fn test_x() {
52        let mut i = 0;
53        assert_eq!(i, 0);
54        {
55            let _ = GLOBAL.fixed_new(X(&mut i));
56        }
57        assert_eq!(i, 1);
58    }
59}