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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use core::{
    cell::Cell,
    sync::atomic::{AtomicIsize, Ordering},
};

use crate::{
    common::ref_mut::RefMut,
    mem::{manager::Dealloc, object::Object, ref_counter_update::RefCounterUpdate},
};

use super::block::Block;

pub trait BlockHeader: Default + Sized {
    // required
    unsafe fn ref_counter_update(&self, i: RefCounterUpdate) -> isize;
    //
    #[inline(always)]
    unsafe fn block<T: Object, D: Dealloc>(&mut self) -> &mut Block<T, D> {
        &mut *(self.to_mut_ptr() as *mut _)
    }
}

impl BlockHeader for AtomicIsize {
    #[inline(always)]
    unsafe fn ref_counter_update(&self, val: RefCounterUpdate) -> isize {
        self.fetch_add(val as isize, Ordering::Relaxed)
    }
}

impl BlockHeader for Cell<isize> {
    #[inline(always)]
    unsafe fn ref_counter_update(&self, val: RefCounterUpdate) -> isize {
        let result = self.get();
        self.set(result + val as isize);
        result
    }
}

#[cfg(test)]
mod test {
    use core::{
        cell::Cell,
        sync::atomic::{AtomicIsize, Ordering},
    };

    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::mem::ref_counter_update::RefCounterUpdate;

    use super::BlockHeader;

    #[test]
    #[wasm_bindgen_test]
    fn test_atomic() {
        let x = AtomicIsize::default();
        assert_eq!(x.load(Ordering::Relaxed), 0);
        assert_eq!(unsafe { x.ref_counter_update(RefCounterUpdate::Read) }, 0);
        assert_eq!(unsafe { x.ref_counter_update(RefCounterUpdate::AddRef) }, 0);
        assert_eq!(
            unsafe { x.ref_counter_update(RefCounterUpdate::Release) },
            1
        );
        assert_eq!(unsafe { x.ref_counter_update(RefCounterUpdate::Read) }, 0);
        assert_eq!(
            unsafe { x.ref_counter_update(RefCounterUpdate::Release) },
            0
        );
        assert_eq!(unsafe { x.ref_counter_update(RefCounterUpdate::Read) }, -1);
    }

    #[test]
    #[wasm_bindgen_test]
    fn test_cell() {
        let x = Cell::default();
        assert_eq!(x.get(), 0);
        assert_eq!(unsafe { x.ref_counter_update(RefCounterUpdate::Read) }, 0);
        assert_eq!(unsafe { x.ref_counter_update(RefCounterUpdate::AddRef) }, 0);
        assert_eq!(
            unsafe { x.ref_counter_update(RefCounterUpdate::Release) },
            1
        );
        assert_eq!(unsafe { x.ref_counter_update(RefCounterUpdate::Read) }, 0);
        assert_eq!(
            unsafe { x.ref_counter_update(RefCounterUpdate::Release) },
            0
        );
        assert_eq!(unsafe { x.ref_counter_update(RefCounterUpdate::Read) }, -1);
    }
}