ext_php_rs/
rc.rs

1//! Traits and types for interacting with reference counted PHP types.
2
3use std::fmt::Debug;
4
5use crate::{
6    ffi::{zend_refcounted_h, zend_string},
7    types::ZendObject,
8};
9
10/// Object used to store Zend reference counter.
11pub type ZendRefcount = zend_refcounted_h;
12
13impl Debug for ZendRefcount {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        f.debug_struct("ZendRefcount")
16            .field("refcount", &self.refcount)
17            .finish()
18    }
19}
20
21/// Implemented on refcounted types.
22pub trait PhpRc {
23    /// Returns an immutable reference to the corresponding refcount object.
24    fn get_rc(&self) -> &ZendRefcount;
25
26    /// Returns a mutable reference to the corresponding refcount object.
27    fn get_rc_mut(&mut self) -> &mut ZendRefcount;
28
29    /// Returns the number of references to the object.
30    fn get_count(&self) -> u32 {
31        self.get_rc().refcount
32    }
33
34    /// Increments the reference counter by 1.
35    fn inc_count(&mut self) {
36        self.get_rc_mut().refcount += 1
37    }
38
39    /// Decrements the reference counter by 1.
40    fn dec_count(&mut self) {
41        self.get_rc_mut().refcount -= 1;
42    }
43}
44
45macro_rules! rc {
46    ($($t: ty),*) => {
47        $(
48            impl PhpRc for $t {
49                fn get_rc(&self) -> &ZendRefcount {
50                    &self.gc
51                }
52
53                fn get_rc_mut(&mut self) -> &mut ZendRefcount {
54                    &mut self.gc
55                }
56            }
57        )*
58    };
59}
60
61rc!(ZendObject, zend_string);