1 use crate::{include::bindings::bindings::{atomic_inc, atomic_t, atomic_dec}, kwarn};
2
3 use super::{ffi_convert::{FFIBind2Rust, __convert_mut, __convert_ref}, atomic::atomic_read};
4
5 #[derive(Debug, Copy, Clone)]
6 pub struct RefCount {
7 pub refs: atomic_t,
8 }
9
10 impl Default for RefCount{
default() -> Self11 fn default() -> Self {
12 Self { refs: atomic_t { value: 1 }}
13 }
14 }
15
16 /// @brief 将给定的来自bindgen的refcount_t解析为Rust的RefCount的引用
17 impl FFIBind2Rust<crate::include::bindings::bindings::refcount_struct> for RefCount{
convert_mut( src: *mut crate::include::bindings::bindings::refcount_struct, ) -> Option<&'static mut Self>18 fn convert_mut(
19 src: *mut crate::include::bindings::bindings::refcount_struct,
20 ) -> Option<&'static mut Self> {
21 return __convert_mut(src);
22 }
convert_ref( src: *const crate::include::bindings::bindings::refcount_struct, ) -> Option<&'static Self>23 fn convert_ref(
24 src: *const crate::include::bindings::bindings::refcount_struct,
25 ) -> Option<&'static Self> {
26 return __convert_ref(src)
27 }
28 }
29
30 /// @brief 以指定的值初始化refcount
31 macro_rules! REFCOUNT_INIT {
32 ($x:expr) => {
33 $crate::libs::refcount::RefCount {
34 refs: $crate::include::bindings::bindings::atomic_t { value: $x },
35 }
36 };
37 }
38
39 /// @brief 引用计数自增1
40 #[allow(dead_code)]
41 #[inline]
refcount_inc(r: &mut RefCount)42 pub fn refcount_inc(r: &mut RefCount) {
43 if atomic_read(&r.refs) == 0{
44 kwarn!("Refcount increased from 0, may be use-after free");
45 }
46
47 unsafe {
48 atomic_inc(&mut r.refs);
49 }
50 }
51
52 /// @brief 引用计数自减1
53 #[allow(dead_code)]
54 #[inline]
refcount_dec(r: &mut RefCount)55 pub fn refcount_dec(r: &mut RefCount){
56 unsafe{
57 atomic_dec(&mut r.refs);
58 }
59 }
60
61
62