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