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
//! Dynamically-atomic reference-counting pointers.
//!
//! This is a proof of concept of a Rust `Rc<T>` type that can *dynamically* choose
//! whether to use atomic access to update its reference count. A related `Arc<T>`
//! can be created which offers thread-safe (`Send + Sync`) access to the same
//! data. If there's never an `Arc`, the `Rc` never pays the price for atomics.

use std::borrow::Borrow;
use std::cell::{Cell, UnsafeCell};
use std::cmp;
use std::fmt;
use std::hash;
use std::isize;
use std::marker::PhantomData;
use std::ops::Deref;
use std::panic;
use std::process::abort;
use std::ptr::NonNull;
use std::sync::atomic::{self, AtomicUsize, Ordering};

/// A soft limit on the amount of references that may be made to an `Arc`.
///
/// Going above this limit will abort your program (although not
/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
const MAX_REFCOUNT: usize = (isize::MAX) as usize;

enum Count {
    Single(Cell<usize>),
    Multi(AtomicUsize),
}

struct Inner<T: ?Sized> {
    count: UnsafeCell<Count>,
    data: T,
}

impl<T> Inner<T> {
    fn new(data: T) -> Box<Self> {
        Box::new(Self {
            count: Count::Single(1.into()).into(),
            data,
        })
    }
}

impl<T: ?Sized> Inner<T> {
    unsafe fn make_multi_threaded(&self) {
        let count = match &*self.count.get() {
            Count::Single(cell) => cell.get(),
            Count::Multi(_) => return,
        };
        // We're single-threaded, so we can safely do an unsynchronized write.
        *self.count.get() = Count::Multi(count.into());
    }

    unsafe fn make_single_threaded(&self) -> bool {
        let count = match &*self.count.get() {
            Count::Single(_) => return true,
            Count::Multi(atom) => atom.load(Ordering::SeqCst),
        };
        if count == 1 {
            // We're the sole owner, so we can safely do an unsynchronized write.
            *self.count.get() = Count::Single(count.into());
            true
        } else {
            false
        }
    }

    fn increment(&self) -> usize {
        unsafe {
            let count = match &*self.count.get() {
                Count::Single(cell) => {
                    let count = cell.get() + 1;
                    cell.set(count);
                    count
                }
                Count::Multi(atom) => atom.fetch_add(1, Ordering::Relaxed) + 1,
            };
            if count > MAX_REFCOUNT {
                abort();
            }
            count
        }
    }

    fn decrement(&self) -> usize {
        unsafe {
            match &*self.count.get() {
                Count::Single(cell) => {
                    let count = cell.get() - 1;
                    cell.set(count);
                    count
                }
                Count::Multi(atom) => {
                    let count = atom.fetch_sub(1, Ordering::Release) - 1;
                    if count == 0 {
                        atomic::fence(Ordering::Acquire);
                    }
                    count
                }
            }
        }
    }
}

/// A reference-counted pointer. 'Rc' stands for 'Reference Counted'.
///
/// This may or may not use atomic access for the reference count, depending on whether it is ever
/// converted to an `Arc`.
pub struct Rc<T: ?Sized> {
    inner: NonNull<Inner<T>>,
    phantom: PhantomData<Inner<T>>,
}

impl<T: ?Sized> Rc<T> {
    fn inner(&self) -> &Inner<T> {
        unsafe { self.inner.as_ref() }
    }
}

impl<T> Rc<T> {
    /// Constructs a new `Rc<T>`.
    ///
    /// This is initially single-threaded, so updates to the reference count will use non-atomic
    /// access. If an `Arc` is ever created from this instance, this will cause *all* of its
    /// references to start using atomic access to the reference count.
    pub fn new(data: T) -> Self {
        Self {
            // FIXME: use `Box::into_raw_non_null` when stable
            inner: unsafe { NonNull::new_unchecked(Box::into_raw(Inner::new(data))) },
            phantom: PhantomData,
        }
    }

    /// Converts an `Arc<T>` to `Rc<T>`. This does not change its atomic property.
    pub fn from_arc(arc: Arc<T>) -> Self {
        arc.inner
    }

    /// Attempts to convert this to an unsynchronized pointer, no longer atomic. Returns `true` if
    /// successful, or `false` if there are still potentially references on other threads.
    pub fn unshare(this: &Self) -> bool {
        unsafe { this.inner().make_single_threaded() }
    }
}

impl<T: ?Sized> Clone for Rc<T> {
    fn clone(&self) -> Self {
        self.inner().increment();
        Self { ..*self }
    }
}

impl<T: ?Sized> Drop for Rc<T> {
    fn drop(&mut self) {
        if self.inner().decrement() == 0 {
            drop(unsafe { Box::from_raw(self.inner.as_ptr()) });
        }
    }
}

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

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

impl<T: ?Sized> AsRef<T> for Rc<T> {
    fn as_ref(&self) -> &T {
        &**self
    }
}

impl<T: ?Sized> Borrow<T> for Rc<T> {
    fn borrow(&self) -> &T {
        &**self
    }
}

impl<T> From<T> for Rc<T> {
    fn from(data: T) -> Self {
        Rc::new(data)
    }
}

impl<T: Default> Default for Rc<T> {
    fn default() -> Self {
        Rc::new(T::default())
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T: ?Sized> fmt::Pointer for Rc<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&(&**self as *const T), f)
    }
}

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

impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }

    fn ne(&self, other: &Self) -> bool {
        **self != **other
    }
}

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

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

    fn lt(&self, other: &Self) -> bool {
        **self < **other
    }

    fn le(&self, other: &Self) -> bool {
        **self <= **other
    }

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

    fn ge(&self, other: &Self) -> bool {
        **self >= **other
    }
}

impl<T: ?Sized + Ord> Ord for Rc<T> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        T::cmp(&**self, &**other)
    }
}

impl<T: panic::RefUnwindSafe + ?Sized> panic::UnwindSafe for Rc<T> {}

/// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically Reference Counted'.
pub struct Arc<T: ?Sized> {
    inner: Rc<T>,
}

// NB: the inner count **must** be the synchronized `Count::Multi`!
unsafe impl<T: Send + Sync + ?Sized> Send for Arc<T> {}
unsafe impl<T: Send + Sync + ?Sized> Sync for Arc<T> {}

impl<T> Arc<T> {
    /// Constructs a new `Arc<T>`.
    pub fn new(data: T) -> Self {
        Arc::from_rc(Rc::new(data))
    }

    /// Converts an `Rc<T>` to `Arc<T>`. This changes its count to start using atomic access, even
    /// in other outstanding `Rc<T>` references to the same underlying object.
    pub fn from_rc(rc: Rc<T>) -> Self {
        unsafe { rc.inner().make_multi_threaded() };
        Self { inner: rc }
    }
}

impl<T: ?Sized> Clone for Arc<T> {
    fn clone(&self) -> Self {
        Self {
            inner: Rc::clone(&self.inner),
        }
    }
}

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

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

impl<T: ?Sized> AsRef<T> for Arc<T> {
    fn as_ref(&self) -> &T {
        &**self
    }
}

impl<T: ?Sized> Borrow<T> for Arc<T> {
    fn borrow(&self) -> &T {
        &**self
    }
}

impl<T> From<T> for Arc<T> {
    fn from(data: T) -> Self {
        Arc::new(data)
    }
}

impl<T: Default> Default for Arc<T> {
    fn default() -> Self {
        Arc::new(T::default())
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T: ?Sized> fmt::Pointer for Arc<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&(&**self as *const T), f)
    }
}

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

impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }

    fn ne(&self, other: &Self) -> bool {
        **self != **other
    }
}

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

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

    fn lt(&self, other: &Self) -> bool {
        **self < **other
    }

    fn le(&self, other: &Self) -> bool {
        **self <= **other
    }

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

    fn ge(&self, other: &Self) -> bool {
        **self >= **other
    }
}

impl<T: ?Sized + Ord> Ord for Arc<T> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        T::cmp(&**self, &**other)
    }
}

impl<T: panic::RefUnwindSafe + ?Sized> panic::UnwindSafe for Arc<T> {}