ijson/
thin.rs

1use std::marker::PhantomData;
2use std::ops::{Deref, DerefMut};
3use std::ptr::NonNull;
4
5#[repr(transparent)]
6pub struct ThinRef<'a, T> {
7    ptr: NonNull<T>,
8    phantom: PhantomData<&'a T>,
9}
10
11impl<T> ThinRef<'_, T> {
12    pub unsafe fn new(ptr: *const T) -> Self {
13        Self {
14            ptr: NonNull::new_unchecked(ptr as *mut T),
15            phantom: PhantomData,
16        }
17    }
18}
19
20impl<T> Deref for ThinRef<'_, T> {
21    type Target = T;
22
23    fn deref(&self) -> &Self::Target {
24        unsafe { &*self.ptr() }
25    }
26}
27
28impl<T> Copy for ThinRef<'_, T> {}
29impl<T> Clone for ThinRef<'_, T> {
30    fn clone(&self) -> Self {
31        *self
32    }
33}
34
35#[repr(transparent)]
36pub struct ThinMut<'a, T> {
37    ptr: NonNull<T>,
38    phantom: PhantomData<&'a mut T>,
39}
40
41impl<T> ThinMut<'_, T> {
42    pub unsafe fn new(ptr: *mut T) -> Self {
43        Self {
44            ptr: NonNull::new_unchecked(ptr),
45            phantom: PhantomData,
46        }
47    }
48}
49
50impl<T> Deref for ThinMut<'_, T> {
51    type Target = T;
52
53    fn deref(&self) -> &Self::Target {
54        // Safety: `ptr` must be valid
55        unsafe { &*self.ptr() }
56    }
57}
58
59impl<T> DerefMut for ThinMut<'_, T> {
60    fn deref_mut(&mut self) -> &mut Self::Target {
61        // Safety: `ptr` must be valid
62        unsafe { &mut *self.ptr_mut() }
63    }
64}
65
66pub trait ThinRefExt<'a, T>: Deref<Target = T> {
67    fn ptr(&self) -> *const T;
68}
69
70pub trait ThinMutExt<'a, T>: DerefMut<Target = T> + ThinRefExt<'a, T> + Sized {
71    fn ptr_mut(&mut self) -> *mut T;
72    fn reborrow(&mut self) -> ThinMut<T>;
73}
74
75impl<'a, T> ThinRefExt<'a, T> for ThinRef<'a, T> {
76    fn ptr(&self) -> *const T {
77        self.ptr.as_ptr()
78    }
79}
80
81impl<'a, T> ThinRefExt<'a, T> for ThinMut<'a, T> {
82    fn ptr(&self) -> *const T {
83        self.ptr.as_ptr()
84    }
85}
86
87impl<'a, T> ThinMutExt<'a, T> for ThinMut<'a, T> {
88    fn ptr_mut(&mut self) -> *mut T {
89        self.ptr.as_ptr()
90    }
91    fn reborrow(&mut self) -> ThinMut<T> {
92        Self {
93            ptr: self.ptr,
94            phantom: self.phantom,
95        }
96    }
97}