tesseract_swift_utils/ptr/
sync.rs1use crate::Void;
2
3#[repr(transparent)]
4#[derive(Debug)]
5pub struct SyncPtr<T>(*const T);
6
7impl<T> SyncPtr<T> {
8 pub fn new(val: T) -> Self {
9 Box::new(val).into()
10 }
11
12 pub fn raw(ptr: *const T) -> Self {
13 Self(ptr)
14 }
15
16 pub fn null() -> Self {
17 Self(std::ptr::null())
18 }
19
20 pub fn ptr(&self) -> *const T {
21 self.0
22 }
23
24 pub fn is_null(&self) -> bool {
25 self.0.is_null()
26 }
27
28 pub fn as_void(self) -> SyncPtr<Void> {
29 SyncPtr(self.0 as *const Void)
30 }
31
32 pub unsafe fn as_ref(&self) -> Option<&T> {
33 self.0.as_ref()
34 }
35
36 pub unsafe fn as_mut(&mut self) -> Option<&mut T> {
37 (self.0 as *mut T).as_mut()
38 }
39
40 pub unsafe fn take(&mut self) -> T {
41 let bx = Box::from_raw(self.0 as *mut T);
42 self.0 = std::ptr::null();
43 *bx
44 }
45}
46
47impl SyncPtr<Void> {
48 pub fn as_type<N>(self) -> SyncPtr<N> {
49 SyncPtr(self.0 as *const N)
50 }
51
52 pub unsafe fn as_typed_ref<N>(&self) -> Option<&N> {
53 (self.0 as *const N).as_ref()
54 }
55
56 pub unsafe fn as_typed_mut<N>(&mut self) -> Option<&mut N> {
57 (self.0 as *mut N).as_mut()
58 }
59
60 pub unsafe fn take_typed<N>(&mut self) -> N {
61 let bx = Box::from_raw(self.0 as *mut N);
62 self.0 = std::ptr::null();
63 *bx
64 }
65}
66
67unsafe impl<T: Send> Send for SyncPtr<T> {}
68unsafe impl<T: Sync> Sync for SyncPtr<T> {}
69
70impl<T> From<*const T> for SyncPtr<T> {
71 fn from(ptr: *const T) -> Self {
72 Self(ptr)
73 }
74}
75
76impl<T> From<&SyncPtr<T>> for *const T {
77 fn from(ptr: &SyncPtr<T>) -> Self {
78 ptr.0
79 }
80}
81
82impl<T> From<SyncPtr<T>> for *const T {
83 fn from(ptr: SyncPtr<T>) -> Self {
84 ptr.0
85 }
86}
87
88impl<T> From<*mut T> for SyncPtr<T> {
89 fn from(ptr: *mut T) -> Self {
90 Self(ptr as *const T)
91 }
92}
93
94impl<T> From<&mut SyncPtr<T>> for *mut T {
95 fn from(ptr: &mut SyncPtr<T>) -> Self {
96 ptr.0 as *mut T
97 }
98}
99
100impl<T> From<SyncPtr<T>> for *mut T {
101 fn from(ptr: SyncPtr<T>) -> Self {
102 ptr.0 as *mut T
103 }
104}
105
106impl<T> From<Box<T>> for SyncPtr<T> {
107 fn from(bx: Box<T>) -> Self {
108 Box::into_raw(bx).into()
109 }
110}