tark 0.1.3

An `Arc` with a thread-local strong/weak count.
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use std::fmt::{Debug, Display, Formatter, Result as FmtResult, Pointer};
use std::hash::{Hash, Hasher};
use std::ptr::NonNull;
use std::ops::Deref;
use std::borrow::Borrow;
use std::cell::Cell;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::num::NonZeroUsize;

struct TarkInner<T: ?Sized> {
    strong: AtomicUsize,
    data: T,
}

impl<T: ?Sized> TarkInner<T> {
    fn dec_maybe_drop(inner: NonNull<TarkInner<T>>) {
        // SAFE: `inner` is assumed valid
        if unsafe { inner.as_ref() }.strong.fetch_sub(1, Ordering::AcqRel) == 1 {
            // SAFE: `inner` was allocated as a box, and thus can be dropped as
            // one.
            unsafe { drop(inner); }
        }
    }

    fn inc_nonnull(inner: NonNull<TarkInner<T>>) {
        // SAFE: `inner` is assumed valid
        unsafe { inner.as_ref() }.strong.fetch_add(1, Ordering::Release);
    }
}

impl<T> TarkInner<T> {
    const fn new(data: T) -> Self {
        TarkInner {
            strong: AtomicUsize::new(1),
            data,
        }
    }
}

impl<T: ?Sized + Hash> Hash for TarkInner<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.data.hash(state)
    }
}

impl<T: ?Sized + PartialEq> PartialEq for TarkInner<T> {
    fn eq(&self, other: &Self) -> bool {
        self.data.eq(&other.data)
    }

    fn ne(&self, other: &Self) -> bool {
        self.data.ne(&other.data)
    }
}

impl<T: ?Sized + Eq> Eq for TarkInner<T> {}

impl<T: ?Sized + PartialOrd> PartialOrd for TarkInner<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.data.partial_cmp(&other.data)
    }

    fn lt(&self, other: &Self) -> bool {
        self.data.lt(&other.data)
    }

    fn le(&self, other: &Self) -> bool {
        self.data.le(&other.data)
    }

    fn gt(&self, other: &Self) -> bool {
        self.data.gt(&other.data)
    }

    fn ge(&self, other: &Self) -> bool {
        self.data.ge(&other.data)
    }
}

impl<T: ?Sized + Ord> Ord for TarkInner<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.data.cmp(&other.data)
    }
}

impl<T: ?Sized + Debug> Debug for TarkInner<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        T::fmt(&self.data, f)
    }
}

impl<T: ?Sized + Display> Display for TarkInner<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        T::fmt(&self.data, f)
    }
}

pub struct TarkSend<T: ?Sized + Send + Sync> {
    inner: NonNull<TarkInner<T>>,
}

impl<T: ?Sized + Send + Sync> TarkSend<T> {
    pub fn new(t: T) -> Self
    where
        T: Sized,
    {
        Self::from_raw(alloc_nonnull(TarkInner::new(t)))
    }

    pub fn atomic_count(this: &Self) -> NonZeroUsize {
        // SAFE: The atomic refcount is guaranteed non-zero.
        unsafe { NonZeroUsize::new_unchecked(
            this.inner.as_ref().strong.load(Ordering::Acquire),
        ) }
    }

    fn from_raw(inner: NonNull<TarkInner<T>>) -> Self {
        TarkInner::inc_nonnull(inner);
        TarkSend { inner }
    }

    pub fn promote(this: Self) -> Tark<T> {
        let t = Tark {
            inner: this.inner,
            strong_weak: StrongWeak::alloc(),
        };
        std::mem::forget(this);
        t
    }

    pub fn promote_ref(this: &Self) -> Tark<T> {
        TarkInner::inc_nonnull(this.inner);
        Tark {
            inner: this.inner,
            strong_weak: StrongWeak::alloc(),
        }
    }

    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
        this.inner.eq(&other.inner)
    }
}

impl<T: ?Sized + Send + Sync + Hash> Hash for TarkSend<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_ref().hash(state)
    }
}

impl<T: ?Sized + Send + Sync + PartialEq> PartialEq for TarkSend<T> {
    fn eq(&self, other: &Self) -> bool {
        self.as_ref().eq(other.as_ref())
    }

    fn ne(&self, other: &Self) -> bool {
        self.as_ref().ne(other.as_ref())
    }
}

impl<T: ?Sized + Send + Sync + Eq> Eq for TarkSend<T> {}

impl<T: ?Sized + Send + Sync + PartialOrd> PartialOrd for TarkSend<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.as_ref().partial_cmp(other.as_ref())
    }

    fn lt(&self, other: &Self) -> bool {
        self.as_ref().lt(other.as_ref())
    }

    fn le(&self, other: &Self) -> bool {
        self.as_ref().le(other.as_ref())
    }

    fn gt(&self, other: &Self) -> bool {
        self.as_ref().gt(other.as_ref())
    }

    fn ge(&self, other: &Self) -> bool {
        self.as_ref().ge(other.as_ref())
    }
}

impl<T: ?Sized + Send + Sync + Ord> Ord for TarkSend<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_ref().cmp(other.as_ref())
    }
}

impl<T: ?Sized + Send + Sync> Clone for TarkSend<T> {
    fn clone(&self) -> Self {
        Self::from_raw(self.inner)
    }

    fn clone_from(&mut self, source: &Self) {
        if self.inner != source.inner {
            std::mem::drop(std::mem::replace(self, source.clone()));
        }
    }
}

impl<T: ?Sized + Send + Sync> Drop for TarkSend<T> {
    fn drop(&mut self) {
        TarkInner::dec_maybe_drop(self.inner);
    }
}

// SAFE: `T` is Send and Sync, meaning a pointer to it is as well.
unsafe impl<T: ?Sized + Send + Sync> Send for TarkSend<T> {}

// SAFE: `T` is Send and Sync, meaning a pointer to it is as well.
unsafe impl<T: ?Sized + Send + Sync> Sync for TarkSend<T> {}

impl<T: ?Sized + Send + Sync> AsRef<T> for TarkSend<T> {
    fn as_ref(&self) -> &T {
        // SAFE: `inner` is a Box pointer, which upholds all the same invariants
        // necessary for .as_ref() except mutable aliasing. we also only allow
        // non-mutable references, so it all works out.
        &unsafe { self.inner.as_ref() }.data
    }
}

impl<T: ?Sized + Send + Sync> Borrow<T> for TarkSend<T> {
    fn borrow(&self) -> &T {
        self.as_ref()
    }
}

impl<T: ?Sized + Send + Sync> Deref for TarkSend<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl<T: ?Sized + Send + Sync + Debug> Debug for TarkSend<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f
            .debug_tuple("TarkSend")
            .field(&self.as_ref())
            .finish()
    }
}

impl<T: ?Sized + Send + Sync + Display> Display for TarkSend<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        Display::fmt(&self, f)
    }
}

impl<T: ?Sized + Send + Sync> Pointer for TarkSend<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        Pointer::fmt(&self.inner, f)
    }
}

pub struct Tark<T: ?Sized> {
    inner: NonNull<TarkInner<T>>,
    strong_weak: NonNull<StrongWeak>,
}

pub type TarkLocal<T> = Tark<T>;

impl<T: ?Sized> Tark<T> {
    pub fn new(t: T) -> Self
    where
        T: Sized,
    {
        let inner = alloc_nonnull(TarkInner::new(t));
        Tark {
            inner,
            strong_weak: StrongWeak::alloc(),
        }
    }

    fn strong(this: &Self) -> &Cell<usize> {
        // SAFE: `strong_weak` is a Box pointer, which upholds all the same
        // invariants necessary for .as_ref() except mutable aliasing. we also
        // only allow non-mutable references, so it all works out.
        &unsafe { this.strong_weak.as_ref() }.strong
    }

    fn weak(this: &Self) -> &Cell<usize> {
        // SAFE: `strong_weak` is a Box pointer, which upholds all the same
        // invariants necessary for .as_ref() except mutable aliasing. we also
        // only allow non-mutable references, so it all works out.
        &unsafe { this.strong_weak.as_ref() }.weak
    }

    pub fn atomic_count(this: &Self) -> NonZeroUsize {
        // SAFE: The atomic refcount is guaranteed non-zero.
        unsafe { NonZeroUsize::new_unchecked(
            this.inner.as_ref().strong.load(Ordering::Acquire),
        ) }
    }

    pub fn strong_count(this: &Self) -> usize {
        Self::strong(this).get()
    }

    pub fn weak_count(this: &Self) -> usize {
        Self::weak(this).get()
    }

    pub fn downgrade(this: &Self) -> Weak<T> {
        let weak = Self::weak(this);
        weak.set(weak.get() + 1);
        WeakTark {
            inner: this.inner,
            strong_weak: this.strong_weak,
        }
    }

    pub fn swap<'a>(this: &'a Self, other: &'a Tark<T>) {
        // SAFE: this is safe because Self isn't sync, so the only thread that
        // could be working with `this` and `other` is the current one. and,
        // because this is the only thread working with this data, and this
        // thread is guaranteed preoccupied with currently performing this
        // function on said data, it's totally fine to swap them right here.
        //
        // i think.
        let this: &'a Cell<Self> = unsafe { std::mem::transmute(this) };
        let other: &'a Cell<Self> = unsafe { std::mem::transmute(other) };
        this.swap(other);
    }
}

impl<T: ?Sized + Send + Sync> Tark<T> {
    pub fn sendable(this: Self) -> TarkSend<T> {
        TarkSend::from_raw(this.inner)
    }
}

impl<T: ?Sized + Hash> Hash for Tark<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_ref().hash(state)
    }
}

impl<T: ?Sized + PartialEq> PartialEq for Tark<T> {
    fn eq(&self, other: &Self) -> bool {
        self.as_ref().eq(other.as_ref())
    }

    fn ne(&self, other: &Self) -> bool {
        self.as_ref().ne(other.as_ref())
    }
}

impl<T: ?Sized + Eq> Eq for Tark<T> {}

impl<T: ?Sized + PartialOrd> PartialOrd for Tark<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.as_ref().partial_cmp(other.as_ref())
    }

    fn lt(&self, other: &Self) -> bool {
        self.as_ref().lt(other.as_ref())
    }

    fn le(&self, other: &Self) -> bool {
        self.as_ref().le(other.as_ref())
    }

    fn gt(&self, other: &Self) -> bool {
        self.as_ref().gt(other.as_ref())
    }

    fn ge(&self, other: &Self) -> bool {
        self.as_ref().ge(other.as_ref())
    }
}

impl<T: ?Sized + Ord> Ord for Tark<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_ref().cmp(other.as_ref())
    }
}

impl<T: ?Sized> Clone for Tark<T> {
    fn clone(&self) -> Self {
        let strong = Self::strong(self);
        strong.set(strong.get() + 1);
        Tark {
            inner: self.inner,
            strong_weak: self.strong_weak,
        }
    }

    fn clone_from(&mut self, source: &Self) {
        if self.inner != source.inner {
            std::mem::drop(std::mem::replace(self, source.clone()));
        }
    }
}

impl<T: ?Sized> Drop for Tark<T> {
    fn drop(&mut self) {
        let strong = Self::strong(self);
        let count = strong.get();

        if count == 1 {
            TarkInner::dec_maybe_drop(self.inner);

            if Self::weak_count(self) == 0 {
                // SAFE: strong_weak was allocated as a box, and thus can be
                // dropped as one.
                unsafe { drop(self.strong_weak); }
            }
        }

        strong.set(count - 1);
    }
}

impl<T: ?Sized> AsRef<T> for Tark<T> {
    fn as_ref(&self) -> &T {
        // SAFE: `inner` is a Box pointer, which upholds all the same invariants
        // necessary for .as_ref() except mutable aliasing. we also only allow
        // non-mutable references, so it all works out.
        &unsafe { self.inner.as_ref() }.data
    }
}

impl<T: ?Sized> Borrow<T> for Tark<T> {
    fn borrow(&self) -> &T {
        self.as_ref()
    }
}

impl<T: ?Sized> Deref for Tark<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl<T: ?Sized + Debug> Debug for Tark<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f
            .debug_tuple("Tark")
            .field(&self.as_ref())
            .finish()
    }
}

impl<T: ?Sized + Display> Display for Tark<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        Display::fmt(&self, f)
    }
}

impl<T: ?Sized> Pointer for Tark<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        Pointer::fmt(&self.inner, f)
    }
}

pub struct WeakTark<T: ?Sized> {
    inner: NonNull<TarkInner<T>>,
    strong_weak: NonNull<StrongWeak>,
}

pub type Weak<T> = WeakTark<T>;

impl<T: ?Sized> Weak<T> {
    fn strong(this: &Self) -> &Cell<usize> {
        // SAFE: `strong_weak` is a Box pointer, which upholds all the same
        // invariants necessary for .as_ref() except mutable aliasing. we also
        // only allow non-mutable references, so it all works out.
        &unsafe { this.strong_weak.as_ref() }.strong
    }

    fn weak(this: &Self) -> &Cell<usize> {
        // SAFE: `strong_weak` is a Box pointer, which upholds all the same
        // invariants necessary for .as_ref() except mutable aliasing. we also
        // only allow non-mutable references, so it all works out.
        &unsafe { this.strong_weak.as_ref() }.weak
    }

    pub fn strong_count(this: &Self) -> usize {
        Self::strong(this).get()
    }

    pub fn weak_count(this: &Self) -> usize {
        Self::weak(this).get()
    }

    pub fn atomic_count(this: &Self) -> Option<NonZeroUsize> {
        if Self::strong_count(this) == 0 {
            None
        } else {
            // SAFE: if the strong count is non-zero, there is some Tark, and
            // thus the atomic count is non-zero.
            Some(unsafe { NonZeroUsize::new_unchecked(
                this.inner.as_ref().strong.load(Ordering::Acquire),
            ) })
        }
    }

    pub fn upgrade(this: &Self) -> Option<Tark<T>> {
        if Weak::strong_count(this) == 0 {
            None
        } else {
            let strong = Weak::strong(this);
            strong.set(strong.get() + 1);
            Some(Tark {
                inner: this.inner,
                strong_weak: this.strong_weak,
            })
        }
    }
}

impl<T: ?Sized> Clone for Weak<T> {
    fn clone(&self) -> Self {
        let weak = Self::weak(self);
        weak.set(weak.get() + 1);
        Weak {
            inner: self.inner,
            strong_weak: self.strong_weak,
        }
    }

    fn clone_from(&mut self, source: &Self) {
        if self.inner != source.inner {
            std::mem::drop(std::mem::replace(self, source.clone()));
        }
    }
}

impl<T: ?Sized> Drop for Weak<T> {
    fn drop(&mut self) {
        let weak = Weak::weak(self);

        if weak.get() == 1 && Weak::strong_count(self) == 0 {
            // SAFE: strong_weak was allocated as a box, and thus can be
            // dropped as one.
            unsafe { drop(self.strong_weak); }
        } else {
            weak.set(weak.get() - 1);
        }
    }
}

impl<T: ?Sized> Pointer for Weak<T> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        Pointer::fmt(&self.inner, f)
    }
}

struct StrongWeak {
    strong: Cell<usize>,
    weak: Cell<usize>,
}

impl StrongWeak {
    fn alloc() -> NonNull<StrongWeak> {
        alloc_nonnull(StrongWeak {
            strong: Cell::new(1),
            weak: Cell::new(0),
        })
    }
}

fn alloc_nonnull<T>(t: T) -> NonNull<T> {
    // SAFE: `Box` itself holds a `Unique` which is guaranteed non-null, so the
    // raw pointer must be non-null too.
    unsafe { NonNull::new_unchecked(Box::into_raw(Box::new(t))) }
}

#[cold]
unsafe fn drop<T: ?Sized>(ptr: NonNull<T>) {
    std::mem::drop(Box::from_raw(ptr.as_ptr()))
}