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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use core::ptr::NonNull;
use core::{cmp, fmt, mem};

#[cfg(feature = "atomic")]
pub use self::atomic::AtomicCursor;

use crate::Cursed;

/// An structure that represents a location within a [`Cursed`] structure.
///
/// A `Cursor` is created from and used with initialized its owning [`Cursed`]
/// structure, however if the structure is dropped, will point to invalid memory.
///
/// Safety is achieved via `Cursor` validating it's owned by the [`Cursed`] structure.
///
/// [`Cursed`]: trait.Cursed.html
pub struct Cursor<T> {
    ptr: NonNull<T>,
}

impl<T> Cursor<T> {
    /// Constructs a new `Cursor` given a non-null pointer.
    #[inline]
    pub fn new(ptr: NonNull<T>) -> Self {
        Self { ptr }
    }

    /// Returns a reference to the element the `Cursor` is pointing to.
    ///
    /// # Example
    /// ```rust
    /// use arae::{CurVec, Bounded};
    ///
    /// let mut vec: CurVec<_> = vec![0].into();
    ///
    /// let cursor = vec.head();
    ///
    /// assert_eq!(*cursor.get(&vec), 0);
    /// ```
    ///
    /// # Panics
    /// Panics if `cursed` does not own self.
    #[inline]
    pub fn get<C>(self, cursed: &C) -> &T
    where
        C: Cursed<T>,
    {
        assert!(cursed.is_owner(self));
        unsafe { &*self.ptr.as_ptr() }
    }

    /// Returns a mutable reference to the element the `Cursor` is pointing to.
    ///
    /// # Example
    /// ```rust
    /// use arae::{CurVec, Bounded};
    ///
    /// let mut vec: CurVec<_> = vec![0].into();
    ///
    /// let cursor = vec.head();
    ///
    /// *cursor.get_mut(&mut vec) = 1;
    ///
    /// assert_eq!(*cursor.get(&vec), 1);
    /// ```
    ///
    /// # Panics
    /// Panics if `cursed` does not own self.
    #[inline]
    pub fn get_mut<C>(self, cursed: &mut C) -> &mut T
    where
        C: Cursed<T>,
    {
        assert!(cursed.is_owner(self));
        unsafe { &mut *self.ptr.as_ptr() }
    }

    /// Constructs a new `Cursor` given a unchecked pointer.
    ///
    /// # Safety
    /// Must not be null, see `NonNull::new_unchecked` safety notes.
    #[inline]
    pub unsafe fn new_unchecked(ptr: *mut T) -> Self {
        Self::new(NonNull::new_unchecked(ptr))
    }

    /// Returns the `Cursor`'s underlying pointer.
    #[inline]
    pub fn ptr(self) -> NonNull<T> {
        self.ptr
    }

    /// Converts the cursor into an atomic variant.
    #[cfg(feature = "atomic")]
    #[inline]
    pub fn into_atomic(self) -> AtomicCursor<T> {
        AtomicCursor::<T>::new(self)
    }

    #[inline]
    pub(crate) unsafe fn unchecked_add(self, offset: usize) -> Self {
        let offset_ptr = self.ptr.as_ptr().add(offset);
        Self::new_unchecked(offset_ptr)
    }

    #[inline]
    pub(crate) unsafe fn unchecked_sub(self, offset: usize) -> Self {
        let offset_ptr = self.ptr.as_ptr().sub(offset);
        Self::new_unchecked(offset_ptr)
    }

    #[inline]
    pub(crate) fn offset_from(self, other: Self) -> usize {
        // TODO: use `offset_from` when stabilized
        if self == other {
            0
        } else {
            let left = self.ptr.as_ptr() as usize;
            let right = other.ptr.as_ptr() as usize;
            (left - right) / mem::size_of::<T>()
        }
    }
}

impl<T> Clone for Cursor<T> {
    #[inline]
    fn clone(&self) -> Self {
        Self::new(self.ptr())
    }
}
impl<T> Copy for Cursor<T> {}

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

impl<T> Eq for Cursor<T> {}

impl<T> PartialOrd for Cursor<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        self.ptr.partial_cmp(&other.ptr)
    }
}

impl<T> Ord for Cursor<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.ptr.cmp(&other.ptr)
    }
}

impl<T> fmt::Debug for Cursor<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Cursor({:?})", self.ptr)
    }
}

///////////////////////////////////////////////////////////////////////////////
// AsCursor

/// `AsCursor` is for simple [`Cursed`] owners where it makes sense to be able
/// to return a single [`Cursor`].
///
/// [`Cursed`]: trait.Cursed.html
/// [`Cursor`]: struct.Cursor.html
pub trait AsCursor<T>: Cursed<T> {
    /// Return a [`Cursor`] for the owner.
    ///
    /// [`Cursor`]: struct.Cursor.html
    fn as_cursor(&self) -> Cursor<T>;
}

mod atomic {
    use core::fmt;
    use core::marker::PhantomData;

    use crate::atomic::{AtomicPtr, Ordering};
    use crate::{Bounded, CursedExt, Cursor, Sequence};

    /// An atomic wrapper around a [`Cursor`].
    ///
    /// [`Cursor`]: struct.Cursor.html
    pub struct AtomicCursor<T> {
        ptr: AtomicPtr<T>,
        marker: PhantomData<T>,
    }

    impl<T> AtomicCursor<T> {
        /// Constructs new atomic cursor given a `Cursor`.
        #[inline]
        pub fn new(cursor: Cursor<T>) -> Self {
            let ptr = AtomicPtr::new(cursor.ptr().as_ptr());
            Self {
                ptr,
                marker: PhantomData,
            }
        }

        /// Loads a `Cursor` value.
        ///
        /// `load` takes an `Ordering` argument which describes the memory ordering
        /// of this operation. Possible values are `SeqCst`, `Acquire` and `Relaxed`.
        ///
        /// # Panics
        ///
        /// Panics if `order` is `Release` or `AcqRel`.
        #[inline]
        pub fn load(&self, order: Ordering) -> Cursor<T> {
            let ptr = self.ptr.load(order);
            unsafe { Cursor::new_unchecked(ptr) }
        }

        /// Stores a `Cursor` value.
        ///
        /// `store` takes an `Ordering` argument which describes the memory ordering
        /// of this operation. Possible values are `SeqCst`, `Release` and `Relaxed`.
        ///
        /// # Panics
        ///
        /// Panics if `order` is `Acquire` or `AcqRel`.
        #[inline]
        pub fn store(&self, cursor: Cursor<T>, order: Ordering) {
            self.ptr.store(cursor.ptr().as_ptr(), order);
        }

        /// Stores a `Cursor` value, returning the previous value.
        ///
        /// `swap` takes an `Ordering` argument which describes the memory ordering
        /// of this operation. All ordering modes are possible. Note that using
        /// `Acquire` makes the store part of this operation `Relaxed`, and
        /// using `Release` makes the load part `Relaxed`.
        #[inline]
        pub fn swap(&self, cursor: Cursor<T>, order: Ordering) -> Cursor<T> {
            let prev_ptr = self.ptr.swap(cursor.ptr().as_ptr(), order);
            unsafe { Cursor::new_unchecked(prev_ptr) }
        }

        /// Stores a `Cursor` value if the current value is the same as the current value.
        ///
        /// The return value is always the previous value. If it is equal to `current`, then the value
        /// was updated.
        ///
        /// `compare_and_swap` also takes an `Ordering` argument which describes the memory
        /// ordering of this operation. Notice that even when using `AcqRel`, the operation
        /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
        /// Using `Acquire` makes the store part of this operation `Relaxed` if it
        /// happens, and using `Release` makes the load part `Relaxed`.
        #[inline]
        pub fn compare_and_swap(
            &self,
            current: Cursor<T>,
            new: Cursor<T>,
            order: Ordering,
        ) -> Cursor<T> {
            let prev_ptr =
                self.ptr
                    .compare_and_swap(current.ptr().as_ptr(), new.ptr().as_ptr(), order);
            unsafe { Cursor::new_unchecked(prev_ptr) }
        }

        /// Stores a `Cursor` value if the current value is the same as the `current` value.
        ///
        /// The return value is a result indicating whether the new value was written and containing
        /// the previous value. On success this value is guaranteed to be equal to `current`.
        ///
        /// `compare_exchange` takes two `Ordering` arguments to describe the memory
        /// ordering of this operation. The first describes the required ordering if the
        /// operation succeeds while the second describes the required ordering when the
        /// operation fails. Using `Acquire` as success ordering makes the store part
        /// of this operation `Relaxed`, and using `Release` makes the successful load
        /// `Relaxed`. The failure ordering can only be `SeqCst`, `Acquire` or `Relaxed`
        /// and must be equivalent to or weaker than the success ordering.
        #[inline]
        pub fn compare_exchange(
            &self,
            current: Cursor<T>,
            new: Cursor<T>,
            success: Ordering,
            failure: Ordering,
        ) -> Result<Cursor<T>, Cursor<T>> {
            let result = self.ptr.compare_exchange(
                current.ptr().as_ptr(),
                new.ptr().as_ptr(),
                success,
                failure,
            );
            unsafe {
                match result {
                    Ok(success) => Ok(Cursor::new_unchecked(success)),
                    Err(failure) => Err(Cursor::new_unchecked(failure)),
                }
            }
        }

        /// Stores a `Cursor` value if the current value is the same as the `current` value.
        ///
        /// Unlike `compare_exchange`, this function is allowed to spuriously fail even when the
        /// comparison succeeds, which can result in more efficient code on some platforms. The
        /// return value is a result indicating whether the new value was written and containing the
        /// previous value.
        ///
        /// `compare_exchange_weak` takes two `Ordering` arguments to describe the memory
        /// ordering of this operation. The first describes the required ordering if the
        /// operation succeeds while the second describes the required ordering when the
        /// operation fails. Using `Acquire` as success ordering makes the store part
        /// of this operation `Relaxed`, and using `Release` makes the successful load
        /// `Relaxed`. The failure ordering can only be `SeqCst`, `Acquire` or `Relaxed`
        /// and must be equivalent to or weaker than the success ordering.
        #[inline]
        pub fn compare_exchange_weak(
            &self,
            current: Cursor<T>,
            new: Cursor<T>,
            success: Ordering,
            failure: Ordering,
        ) -> Result<Cursor<T>, Cursor<T>> {
            let result = self.ptr.compare_exchange(
                current.ptr().as_ptr(),
                new.ptr().as_ptr(),
                success,
                failure,
            );
            unsafe {
                match result {
                    Ok(success) => Ok(Cursor::new_unchecked(success)),
                    Err(failure) => Err(Cursor::new_unchecked(failure)),
                }
            }
        }

        /// Atomically advance the cursor given its owner.
        ///
        /// `next` takes an `Ordering` argument which describes the memory ordering
        /// of this operation. All ordering modes are possible. Note that using
        /// `Acquire` makes the store part of this operation `Relaxed`, and
        /// using `Release` makes the load part `Relaxed`.
        ///
        /// Returns `true` if the cursor was updated, `false` if the cursor is at the
        /// tail and cannot go forward any further.
        ///
        /// # Panics
        /// Panics if `cursed` does not own the cursor.
        #[inline]
        pub fn next<C>(&self, cursed: &C, order: Ordering) -> bool
        where
            C: Sequence<T>,
        {
            let (load, store) = Self::load_store_order(order);
            let cursor = self.load(load);
            cursed
                .next(cursor)
                .map(|cursor| self.store(cursor, store))
                .is_some()
        }

        /// Atomically reverse the cursor given its owner.
        ///
        /// `prev` takes an `Ordering` argument which describes the memory ordering
        /// of this operation. All ordering modes are possible. Note that using
        /// `Acquire` makes the store part of this operation `Relaxed`, and
        /// using `Release` makes the load part `Relaxed`.
        ///
        /// Returns `true` if the cursor was updated, `false` if the cursor is at the
        /// head and cannot go back any further.
        ///
        /// # Panics
        /// Panics if `cursed` does not own the cursor.
        #[inline]
        pub fn prev<C>(&self, cursed: &C, order: Ordering) -> bool
        where
            C: Sequence<T>,
        {
            let (load, store) = Self::load_store_order(order);
            let cursor = self.load(load);
            cursed
                .prev(cursor)
                .map(|cursor| self.store(cursor, store))
                .is_some()
        }

        /// Atomically advance the cursor given its owner.
        ///
        /// `next` takes an `Ordering` argument which describes the memory ordering
        /// of this operation. All ordering modes are possible. Note that using
        /// `Acquire` makes the store part of this operation `Relaxed`, and
        /// using `Release` makes the load part `Relaxed`.
        ///
        /// # Panics
        /// Panics if `cursed` does not own the cursor.
        #[inline]
        pub fn wrapping_next<C>(&self, cursed: &C, order: Ordering)
        where
            C: Bounded<T>,
        {
            let (load, store) = Self::load_store_order(order);
            let cursor = self.load(load);
            let cursor = cursed.wrapping_next(cursor);
            self.store(cursor, store);
        }

        /// Atomically reverse the cursor given its owner.
        ///
        /// `prev` takes an `Ordering` argument which describes the memory ordering
        /// of this operation. All ordering modes are possible. Note that using
        /// `Acquire` makes the store part of this operation `Relaxed`, and
        /// using `Release` makes the load part `Relaxed`.
        ///
        /// # Panics
        /// Panics if the `cursed` does not own the cursor.
        #[inline]
        pub fn wrapping_prev<C>(&self, cursed: &C, order: Ordering)
        where
            C: Bounded<T>,
        {
            let (load, store) = Self::load_store_order(order);
            let cursor = self.load(load);
            let cursor = cursed.wrapping_prev(cursor);
            self.store(cursor, store);
        }

        /// Converts the atomic cursor into the base variant.
        #[inline]
        pub fn into_cursor(self) -> Cursor<T> {
            unsafe { Cursor::new_unchecked(self.ptr.into_inner()) }
        }

        #[inline]
        fn load_store_order(order: Ordering) -> (Ordering, Ordering) {
            let load = match order {
                Ordering::AcqRel => Ordering::Acquire,
                Ordering::Release => Ordering::Relaxed,
                other => other,
            };
            let store = match order {
                Ordering::AcqRel => Ordering::Release,
                Ordering::Acquire => Ordering::Relaxed,
                other => other,
            };
            (load, store)
        }
    }

    impl<T: fmt::Debug> fmt::Debug for AtomicCursor<T> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "AtomicCursor({:?})", self.ptr)
        }
    }

    impl<T> From<AtomicCursor<T>> for Cursor<T> {
        fn from(cursor: AtomicCursor<T>) -> Self {
            cursor.into_cursor()
        }
    }

    impl<T> From<Cursor<T>> for AtomicCursor<T> {
        fn from(cursor: Cursor<T>) -> Self {
            cursor.into_atomic()
        }
    }
}