pointers 0.1.0

trait for smart pointers, alternation to Arc, Intrusive ref counting (Irc)
Documentation
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
//! Intrusive Reference Counter (Irc)
//!
//! `Irc` is an intrusive reference counting smart pointer, similar to `Arc` but without weak reference support.
//! It requires the inner type to implement [IrcItem] trait to provide a counter field.
//!
//! The underlayer of `Irc` can be any types implementing `Pointer` (default to be Box),
//! unlike `Arc` which wrap a hidden ArcInner on your inner types,
//! Irc use the pointer of your inner types by [Pointer::into_raw]
//!
//! The atomic ordering is mostly the same with std `Arc` (miri test cases verified)
//!
//! # Benefits
//!
//! - No need to manual implementing the inc / dec on counter.
//!
//! - No enforced weak counter if you don't need it (every atomic op has cost).
//!
//! - Customized counter type (not limited to AtomicUsize)
//!
//! - [IrcItem::on_drop] in the trait allow you to have the ownship of underlying inner memory after
//!   the reference count of Irc is dropped. And you only need to define the drop behavior once,
//!   instead of write the same logic `Arc::into_inner` in every possible places
//!   (If forgetting so make your code block and hard to debug).
//!
//! - Using `Irc` to wrap a `Box`, no additional memory allocation and memory fragmentation, no
//!   additional dereference cost (than using `Arc<Box<T>>`)
//!
//! - You can allocate a box from the time of its birth and wrap it will `Irc` for temporary usage,
//!   don't need to move bytes from / to stack. (especially when the inner object is large)
//!
//! - Advanced usage, multiple layer customized counter, on the same heap object, while preserving
//!   the safe boundary
//!
//! # Example
//!
//! The follow example shows `Irc` wrapping a `Box` (You can also the same to Change the param P with `Arc`, or other [Pointer](crate::Pointer) type)
//!
//! ```rust
//! use pointers::irc::{Irc, IrcItem};
//! use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
//! use crossfire::oneshot;
//! use std::thread;
//! use std::time::Duration;
//!
//! // Usually we use Irc for some large structure, but we show a simple demo here.
//! struct MyItem {
//!     is_done: AtomicBool,
//!     counter: AtomicUsize,
//!     done_tx: Option<oneshot::TxOneshot<Box<MyItem>>>,
//! }
//!
//! // The default parameter Tag=(), P=Box<Self>
//! unsafe impl IrcItem for MyItem {
//!     type Counter = AtomicUsize;
//!     fn counter(&self) -> &Self::Counter {
//!         &self.counter
//!     }
//!
//!     // overwrite default behavior to send the item through channel
//!     fn on_drop(mut this: Box<Self>) {
//!         let done_tx = this.done_tx.take().unwrap();
//!         done_tx.send(this);
//!     }
//! }
//!
//! let (done_tx, done_rx) = oneshot::oneshot();
//! let boxed_item = Box::new(MyItem {
//!     is_done: AtomicBool::new(false),
//!     counter: AtomicUsize::new(0),
//!     done_tx: Some(done_tx),
//! });
//!
//! // Convert from Box to Irc, which does not have additional allocation.
//! let item = Irc::from(boxed_item);
//! thread::spawn(move || {
//!     thread::sleep(Duration::from_secs(1));
//!     item.is_done.store(true, Ordering::SeqCst);
//!     drop(item);
//! });
//! let item: Box<MyItem> = done_rx.recv().unwrap();
//! assert!(item.is_done.load(Ordering::SeqCst));
//! ```

use crate::{Pointer, SmartPointer};
use alloc::boxed::Box;
use atomic_traits::{
    Atomic, NumOps,
    fetch::{Add, Sub},
};
use core::fmt;
use core::marker::PhantomData;
use core::ops::Deref;
use core::ptr::NonNull;
use core::sync::atomic::{
    Ordering::{Acquire, Relaxed, Release},
    fence,
};

/// trait for types that can be wrapped by [Irc]
///
/// # Safety
///
/// Tag is for distinguish multiple Irc from the same Inner type.
/// When implement multiple types of Irc from the same object,
/// you must make sure they don't have overlapped Counter fields.
pub unsafe trait IrcItem<Tag = (), P = Box<Self>>: Sized + Send + Sync
where
    <Self::Counter as Atomic>::Type: From<u8> + Into<usize> + PartialEq,
    P: Pointer<Target = Self>,
{
    /// The type of counter
    type Counter: NumOps;

    /// return reference to the field of counter
    fn counter(&self) -> &Self::Counter;

    /// The default behavior for Irc is dropping the inner smart pointer type.
    ///
    /// You can overwrite this if you want to send the inner somewhere.
    #[inline(always)]
    fn on_drop(_this: P) {}

    #[inline]
    fn strong_count(&self) -> usize {
        self.counter().load(Relaxed).into()
    }
}

/// Intrusive reference counter, which support conversion between `P`.
///
/// It does not support weak reference.
pub struct Irc<T, Tag = (), P = Box<T>>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
    inner: NonNull<T>,
    _phan: PhantomData<fn(&Tag, &P)>,
}

impl<T, Tag, P> Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: SmartPointer<Target = T>,
{
    /// Wrap a stack value T inside P with Irc.
    ///
    /// The counter will be reset to 1 on initialization.
    #[inline]
    pub fn new(inner: T) -> Self {
        Self::from(P::new(inner))
    }
}

impl<T: IrcItem<Tag, P>, Tag, P> SmartPointer for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: SmartPointer<Target = T>,
{
    #[inline]
    fn new(inner: T) -> Self {
        Irc::new(inner)
    }
}

impl<T, Tag, P> From<P> for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
    /// Convert a [Pointer] containing `T` into Irc.
    ///
    /// The counter will be reset to 1 on initialization.
    #[inline]
    fn from(inner: P) -> Self {
        inner.as_ref().counter().store(1u8.into(), Relaxed);
        Self {
            inner: unsafe { NonNull::new_unchecked(inner.into_raw() as *mut T) },
            _phan: Default::default(),
        }
    }
}

impl<T, Tag, P> Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
    #[inline(always)]
    fn get_inner(&self) -> &T {
        unsafe { self.inner.as_ref() }
    }

    #[inline]
    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
        this.inner == other.inner
    }

    /// Wrap a [Pointer] containing `T` with Irc.
    ///
    /// # Safety
    ///
    /// The counter will be increase by 1, but the previous value is not checked
    #[inline]
    pub unsafe fn with_unchecked(inner: P) -> Self {
        inner.as_ref().counter().fetch_add(1u8.into(), Relaxed);
        Self {
            inner: unsafe { NonNull::new_unchecked(inner.into_raw() as *mut T) },
            _phan: Default::default(),
        }
    }

    /// If is_unique returns true, then this thread is the only owner
    ///
    /// # False negative
    ///
    /// it's possible to return false when counter drop to 1,
    /// Because of using Acquire load and Release on drop.
    ///
    /// # Example
    ///
    ///
    /// ```rust
    /// use pointers::irc::{Irc, IrcItem};
    /// use core::sync::atomic::AtomicUsize;
    ///
    /// struct Tag;
    ///
    /// struct MyItem {
    ///     value: i32,
    ///     counter: AtomicUsize,
    /// }
    ///
    /// unsafe impl IrcItem<Tag> for MyItem {
    ///     type Counter = AtomicUsize;
    ///     fn counter(&self) -> &Self::Counter {
    ///         &self.counter
    ///     }
    /// }
    ///
    /// // Create a new Irc
    /// let irc1 = Irc::<_, Tag>::new(MyItem { value: 10, counter: AtomicUsize::new(0) });
    /// assert_eq!(irc1.value, 10);
    /// assert!(irc1.is_unique());
    ///
    /// // Clone the Irc
    /// let irc2 = irc1.clone();
    /// assert_eq!(irc1.strong_count(), 2);
    /// assert!(!irc1.is_unique());
    /// ```
    #[inline]
    pub fn is_unique(&self) -> bool {
        // Safety:
        // we have make sure counter reset to 1 on init.
        // although clone use Relaxed, it can never pass this fence
        self.counter().load(Acquire) == 1u8.into()
    }

    /// return mutable reference if we are the only owner
    ///
    /// # False negative
    ///
    /// It can return None even when only one reference left
    #[inline]
    pub fn get_mut(this: &mut Self) -> Option<&mut T> {
        if this.is_unique() { Some(unsafe { this.inner.as_mut() }) } else { None }
    }
}

impl<T, Tag, P> Irc<T, Tag, P>
where
    T: IrcItem<Tag, P> + Clone,
    P: SmartPointer<Target = T>,
{
    /// The Cow function, the same as `Arc::make_mut()`
    ///
    /// # Example
    ///
    /// ```rust
    /// use pointers::irc::{Irc, IrcItem};
    /// use core::sync::atomic::AtomicUsize;
    ///
    /// struct Tag;
    /// struct MyItem {
    ///     value: i32,
    ///     counter: AtomicUsize,
    /// }
    ///
    /// impl Clone for MyItem {
    ///     fn clone(&self) -> Self {
    ///         Self { value: self.value, counter: AtomicUsize::new(0) }
    ///     }
    /// }
    ///
    /// unsafe impl IrcItem<Tag> for MyItem {
    ///     type Counter = AtomicUsize;
    ///     fn counter(&self) -> &Self::Counter {
    ///         &self.counter
    ///     }
    /// }
    ///
    /// let mut irc1 = Irc::<_, Tag>::new(MyItem { value: 10, counter: AtomicUsize::new(0) });
    /// let irc2 = irc1.clone();
    ///
    /// // This will clone the inner item because it's shared
    /// let m = Irc::make_mut(&mut irc1);
    /// m.value = 20;
    ///
    /// assert_eq!(irc1.value, 20);
    /// assert_eq!(irc2.value, 10);
    /// ```
    #[inline]
    pub fn make_mut(this: &mut Self) -> &mut T {
        if !this.is_unique() {
            let cloned_item = this.get_inner().clone();
            let mut new_irc = Self::new(cloned_item);
            core::mem::swap(this, &mut new_irc);
        }
        unsafe { this.inner.as_mut() }
    }
}

impl<T, Tag, P> Deref for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
    type Target = T;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        self.get_inner()
    }
}

impl<T, Tag, P> AsRef<T> for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
    #[inline(always)]
    fn as_ref(&self) -> &T {
        self.get_inner()
    }
}

unsafe impl<T, Tag, P> Send for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
}
unsafe impl<T, Tag, P> Sync for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
}

impl<T, Tag, P> Clone for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
    #[inline]
    fn clone(&self) -> Self {
        self.get_inner().counter().fetch_add(1u8.into(), Relaxed);
        Self { inner: self.inner, _phan: Default::default() }
    }
}

impl<T, Tag, P> Drop for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
    #[inline]
    fn drop(&mut self) {
        let p = self.inner.as_ptr();
        unsafe {
            if (*p).counter().fetch_sub(1u8.into(), Release) == 1u8.into() {
                fence(Acquire);
                let inner = P::from_raw(p);
                IrcItem::<Tag, P>::on_drop(inner);
            }
        }
    }
}

impl<T, Tag, P> fmt::Debug for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P> + fmt::Debug,
    P: Pointer<Target = T>,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.get_inner().fmt(f)
    }
}

impl<T, Tag, P> fmt::Display for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P> + fmt::Display,
    P: Pointer<Target = T>,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.get_inner().fmt(f)
    }
}

impl<T: IrcItem<Tag, P>, Tag, P> Pointer for Irc<T, Tag, P>
where
    T: IrcItem<Tag, P>,
    P: Pointer<Target = T>,
{
    type Target = T;

    #[inline]
    fn as_ref(&self) -> &Self::Target {
        unsafe { self.inner.as_ref() }
    }

    /// # Safety
    ///
    /// must be pointer acquire from [Irc::into_raw()]
    #[inline]
    unsafe fn from_raw(p: *const Self::Target) -> Self {
        Self {
            inner: unsafe { NonNull::new_unchecked(p as *mut Self::Target) },
            _phan: Default::default(),
        }
    }

    #[inline]
    fn into_raw(self) -> *const Self::Target {
        let p = self.inner.as_ptr();
        core::mem::forget(self);
        p
    }
}