Skip to main content

sibyl/oci/
ptr.rs

1//! Send-able pointers to OCI handles and descriptors
2
3use std::{ptr, ops::{Deref, DerefMut}};
4
5use libc::c_void;
6
7use super::attr::{AttrGetInto, AttrGet, AttrSet};
8
9/// Send-able cell-like wrapper around a pointer to OCI handle or descriptor.
10pub(crate) struct Ptr<T> (*mut T);
11
12impl<T> Ptr<T> {
13    pub(crate) fn new(ptr: *const T) -> Self {
14        Self(ptr as _)
15    }
16
17    pub(crate) fn null() -> Self {
18        Self(ptr::null_mut())
19    }
20
21    pub(crate) fn swap(&mut self, other: &mut Self) {
22        if !ptr::eq(self, other) && !ptr::eq(self.0, other.0) {
23            unsafe {
24                ptr::swap(&mut self.0, &mut other.0);
25            }
26        }
27    }
28
29    pub(crate) fn is_null(&self) -> bool {
30        self.0.is_null()
31    }
32
33    pub(crate) fn get(&self) -> *const T {
34        self.0
35    }
36
37    pub(crate) fn get_mut(&self) -> *mut T {
38        self.0
39    }
40
41    pub(crate) fn as_ptr(&self) -> *const *mut T {
42        &self.0 as _
43    }
44
45    pub(crate) fn as_mut_ptr(&mut self) -> *mut *mut T {
46        &mut self.0 as _
47    }
48}
49
50impl<T> From<&T> for Ptr<T> {
51    fn from(oci_ref: &T) -> Self {
52        Self(oci_ref as *const T as _)
53    }
54}
55
56impl<T> Copy for Ptr<T> {}
57
58impl<T> Clone for Ptr<T> {
59    fn clone(&self) -> Self {
60        *self
61    }
62}
63
64impl<T> Deref for Ptr<T> {
65    type Target = T;
66
67    fn deref(&self) -> &Self::Target {
68        unsafe {
69            &*self.0
70        }
71    }
72}
73
74impl<T> DerefMut for Ptr<T> {
75    fn deref_mut(&mut self) -> &mut Self::Target {
76        unsafe {
77            &mut *self.0
78        }
79    }
80}
81
82impl<T> AsRef<T> for Ptr<T> {
83    fn as_ref(&self) -> &T {
84        unsafe {
85            &*self.0
86        }
87    }
88}
89
90impl<T> AsMut<T> for Ptr<T> {
91    fn as_mut(&mut self) -> &mut T {
92        unsafe {
93            &mut *self.0
94        }
95    }
96}
97
98impl<T> std::fmt::Pointer for Ptr<T> {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        std::fmt::Pointer::fmt(&self.0, f)
101    }
102}
103
104impl<T> AttrGet for Ptr<T> {
105    type ValueType = *mut T;
106    fn new(ptr: Self::ValueType, _len: usize) -> Self {
107        Ptr::new(ptr)
108    }
109}
110
111impl<T> AttrGetInto for Ptr<T> {
112    fn as_mut_ptr(&mut self) -> *mut c_void {
113        self.as_mut_ptr() as _
114    }
115}
116
117impl<T> AttrSet for Ptr<T> {
118    fn as_ptr(&self) -> *const c_void {
119        self.get() as _
120    }
121}
122
123unsafe impl<T> Send for Ptr<T> {}
124unsafe impl<T> Sync for Ptr<T> {}