1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use super::ref_counted::RefCounted;
use super::{Shared, Tag};
use std::marker::PhantomData;
use std::panic::UnwindSafe;
use std::sync::atomic::Ordering::Relaxed;
use std::{ptr, ptr::NonNull};

/// [`Ptr`] points to an instance.
#[derive(Debug)]
pub struct Ptr<'g, T> {
    instance_ptr: *const RefCounted<T>,
    _phantom: PhantomData<&'g T>,
}

impl<'g, T> Ptr<'g, T> {
    /// Creates a null [`Ptr`].
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::Ptr;
    ///
    /// let ptr: Ptr<usize> = Ptr::null();
    /// ```
    #[inline]
    #[must_use]
    pub const fn null() -> Self {
        Self {
            instance_ptr: ptr::null(),
            _phantom: PhantomData,
        }
    }

    /// Returns `true` if the [`Ptr`] is null.
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::Ptr;
    ///
    /// let ptr: Ptr<usize> = Ptr::null();
    /// assert!(ptr.is_null());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_null(&self) -> bool {
        Tag::unset_tag(self.instance_ptr).is_null()
    }

    /// Tries to create a reference to the underlying instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::{AtomicShared, Guard};
    /// use std::sync::atomic::Ordering::Relaxed;
    ///
    /// let atomic_shared: AtomicShared<usize> = AtomicShared::new(21);
    /// let guard = Guard::new();
    /// let ptr = atomic_shared.load(Relaxed, &guard);
    /// assert_eq!(*ptr.as_ref().unwrap(), 21);
    /// ```
    #[inline]
    #[must_use]
    pub fn as_ref(&self) -> Option<&'g T> {
        let ptr = Tag::unset_tag(self.instance_ptr);
        if ptr.is_null() {
            return None;
        }
        unsafe { Some(&*ptr) }
    }

    /// Provides a raw pointer to the instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::{Guard, Shared};
    /// use std::sync::atomic::Ordering::Relaxed;
    ///
    /// let shared: Shared<usize> = Shared::new(29);
    /// let guard = Guard::new();
    /// let ptr = shared.get_guarded_ptr(&guard);
    /// drop(shared);
    ///
    /// assert_eq!(unsafe { *ptr.as_ptr() }, 29);
    /// ```
    #[inline]
    #[must_use]
    pub fn as_ptr(&self) -> *const T {
        RefCounted::inst_ptr(Tag::unset_tag(self.instance_ptr))
    }

    /// Returns its [`Tag`].
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::{Ptr, Tag};
    ///
    /// let ptr: Ptr<usize> = Ptr::null();
    /// assert_eq!(ptr.tag(), Tag::None);
    /// ```
    #[inline]
    #[must_use]
    pub fn tag(&self) -> Tag {
        Tag::into_tag(self.instance_ptr)
    }

    /// Sets a [`Tag`], overwriting its existing [`Tag`].
    ///
    /// Returns the previous tag value.
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::{Ptr, Tag};
    ///
    /// let mut ptr: Ptr<usize> = Ptr::null();
    /// assert_eq!(ptr.set_tag(Tag::Both), Tag::None);
    /// assert_eq!(ptr.tag(), Tag::Both);
    /// ```
    #[inline]
    pub fn set_tag(&mut self, tag: Tag) -> Tag {
        let old_tag = Tag::into_tag(self.instance_ptr);
        self.instance_ptr = Tag::update_tag(self.instance_ptr, tag);
        old_tag
    }

    /// Clears its [`Tag`].
    ///
    /// Returns the previous tag value.
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::{Ptr, Tag};
    ///
    /// let mut ptr: Ptr<usize> = Ptr::null().with_tag(Tag::Both);
    /// assert_eq!(ptr.unset_tag(), Tag::Both);
    /// ```
    #[inline]
    pub fn unset_tag(&mut self) -> Tag {
        let old_tag = Tag::into_tag(self.instance_ptr);
        self.instance_ptr = Tag::unset_tag(self.instance_ptr);
        old_tag
    }

    /// Returns a copy of `self` with a [`Tag`] set.
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::{Ptr, Tag};
    ///
    /// let mut ptr: Ptr<usize> = Ptr::null();
    /// assert_eq!(ptr.tag(), Tag::None);
    ///
    /// let ptr_with_tag = ptr.with_tag(Tag::First);
    /// assert_eq!(ptr_with_tag.tag(), Tag::First);
    /// ```
    #[inline]
    #[must_use]
    pub fn with_tag(self, tag: Tag) -> Self {
        Self::from(Tag::update_tag(self.instance_ptr, tag))
    }

    /// Returns a copy of `self` with its [`Tag`] erased.
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::{Ptr, Tag};
    ///
    /// let mut ptr: Ptr<usize> = Ptr::null();
    /// ptr.set_tag(Tag::Second);
    /// assert_eq!(ptr.tag(), Tag::Second);
    ///
    /// let ptr_without_tag = ptr.without_tag();
    /// assert_eq!(ptr_without_tag.tag(), Tag::None);
    /// ```
    #[inline]
    #[must_use]
    pub fn without_tag(self) -> Self {
        Self::from(Tag::unset_tag(self.instance_ptr))
    }

    /// Tries to convert itself into a [`Shared`].
    ///
    /// # Examples
    ///
    /// ```
    /// use sdd::{Guard, Shared};
    ///
    /// let shared: Shared<usize> = Shared::new(83);
    /// let guard = Guard::new();
    /// let ptr = shared.get_guarded_ptr(&guard);
    /// let shared_restored = ptr.get_shared().unwrap();
    /// assert_eq!(*shared_restored, 83);
    ///
    /// drop(shared);
    /// drop(shared_restored);
    ///
    /// assert!(ptr.get_shared().is_none());
    /// ```
    #[inline]
    #[must_use]
    pub fn get_shared(self) -> Option<Shared<T>> {
        unsafe {
            if let Some(ptr) = NonNull::new(Tag::unset_tag(self.instance_ptr).cast_mut()) {
                if (*ptr.as_ptr()).try_add_ref(Relaxed) {
                    return Some(Shared::from(ptr));
                }
            }
        }
        None
    }

    /// Creates a new [`Ptr`] from a raw pointer.
    #[inline]
    pub(super) const fn from(ptr: *const RefCounted<T>) -> Self {
        Self {
            instance_ptr: ptr,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Provides a raw pointer to its [`RefCounted`].
    #[inline]
    pub(super) const fn as_underlying_ptr(self) -> *const RefCounted<T> {
        self.instance_ptr
    }
}

impl<'g, T> Clone for Ptr<'g, T> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

impl<'g, T> Copy for Ptr<'g, T> {}

impl<'g, T> Default for Ptr<'g, T> {
    #[inline]
    fn default() -> Self {
        Self::null()
    }
}

impl<'g, T> Eq for Ptr<'g, T> {}

impl<'g, T> PartialEq for Ptr<'g, T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.instance_ptr == other.instance_ptr
    }
}

impl<'g, T: UnwindSafe> UnwindSafe for Ptr<'g, T> {}