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
use core::borrow::Borrow;
use core::hash::{Hash, Hasher};
use core::mem::ManuallyDrop;
use core::ops::Deref;
use core::ptr;
use core::sync::atomic;
use core::{cmp::Ordering, marker::PhantomData};
use core::{fmt, mem};

use super::{Arc, ArcInner, ArcRef, OffsetArc};

/// A "borrowed [`Arc`]". This is essentially a reference to an `ArcInner<T>`
///
/// This is equivalent in guarantees to [`&Arc<T>`][`Arc`], however it has the same representation as an [`Arc<T>`], minimizing pointer-chasing.
///
/// [`ArcBorrow`] lets us deal with borrows of known-refcounted objects
/// without needing to worry about where the [`Arc<T>`][`Arc`] is.
#[repr(transparent)]
pub struct ArcBorrow<'a, T: ?Sized + 'a> {
    pub(crate) p: ptr::NonNull<ArcInner<T>>,
    pub(crate) phantom: PhantomData<&'a T>,
}

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

impl<'a, T> ArcBorrow<'a, T> {
    /// Clone this as an [`Arc<T>`]. This bumps the refcount.
    #[inline]
    pub fn clone_arc(this: Self) -> Arc<T> {
        let arc = unsafe { Arc::from_raw_inner(this.p) };
        // addref it!
        mem::forget(arc.clone());
        arc
    }

    /// Compare two [`ArcBorrow`]s via pointer equality. Will only return
    /// true if they come from the same allocation
    #[inline]
    pub fn ptr_eq(this: Self, other: Self) -> bool {
        this.p == other.p
    }

    /// Similar to deref, but uses the lifetime `'a` rather than the lifetime of
    /// `self`, which is incompatible with the signature of the [`Deref`] trait.
    #[inline]
    pub fn get(&self) -> &'a T {
        &self.inner().data
    }

    /// Borrow this as an [`Arc`]. This does *not* bump the refcount.
    #[inline]
    pub fn as_arc(this: &Self) -> &Arc<T> {
        unsafe { &*(this as *const _ as *const Arc<T>) }
    }

    /// Borrow this as an [`ArcRef`]. This does *not* bump the refcount.
    #[inline]
    pub fn as_arc_ref(this: &'a ArcBorrow<'a, T>) -> &'a ArcRef<'a, T> {
        unsafe { &*(this as *const _ as *const ArcRef<'a, T>) }
    }

    /// Get the internal pointer of an [`ArcBorrow`]
    #[inline]
    pub fn into_raw(this: Self) -> *const T {
        let arc = Self::as_arc(&this);
        Arc::as_ptr(arc)
    }

    #[inline]
    pub(super) fn inner(&self) -> &'a ArcInner<T> {
        // This unsafety is ok because while this arc is alive we're guaranteed
        // that the inner pointer is valid. Furthermore, we know that the
        // `ArcInner` structure itself is `Sync` because the inner data is
        // `Sync` as well, so we're ok loaning out an immutable pointer to these
        // contents.
        unsafe { &*self.p.as_ptr() }
    }

    /// Gets the number of [`Arc`] pointers to this allocation
    #[inline]
    pub fn count(this: Self) -> usize {
        ArcBorrow::load_count(this, atomic::Ordering::Acquire)
    }

    /// Gets the number of [`Arc`] pointers to this allocation, with a given load ordering
    #[inline]
    pub fn load_count(this: Self, order: atomic::Ordering) -> usize {
        this.inner().count.load(order)
    }
}

impl<'a, T> Deref for ArcBorrow<'a, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        self.get()
    }
}

/// A "borrowed [`OffsetArc`]". This is a pointer to
/// a T that is known to have been allocated within an
/// [`Arc`].
///
/// This is equivalent in guarantees to [`&Arc<T>`][`Arc`], however it is
/// a bit more flexible. To obtain an [`&Arc<T>`][`Arc`] you must have
/// an [`Arc<T>`][`Arc`] instance somewhere pinned down until we're done with it.
/// It's also a direct pointer to `T`, so using this involves less pointer-chasing
///
/// However, C++ code may hand us refcounted things as pointers to `T` directly,
/// so we have to conjure up a temporary [`Arc`] on the stack each time. The
/// same happens for when the object is managed by a [`OffsetArc`].
///
/// [`OffsetArcBorrow`] lets us deal with borrows of known-refcounted objects
/// without needing to worry about where the [`Arc<T>`] is.
#[repr(transparent)]
pub struct OffsetArcBorrow<'a, T: ?Sized + 'a> {
    pub(crate) p: ptr::NonNull<T>,
    pub(crate) phantom: PhantomData<&'a T>,
}

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

impl<'a, T> OffsetArcBorrow<'a, T> {
    /// Clone this as an [`Arc<T>`]. This bumps the refcount.
    #[inline]
    pub fn clone_arc(this: Self) -> Arc<T> {
        let arc = unsafe { Arc::from_raw(this.p.as_ptr()) };
        // addref it!
        mem::forget(arc.clone());
        arc
    }

    /// Compare two [`ArcBorrow`]s via pointer equality. Will only return
    /// true if they come from the same allocation
    #[inline]
    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
        this.p == other.p
    }

    /// Temporarily converts `self` into a bonafide [`Arc`] and exposes it to the
    /// provided callback. The refcount is not modified.
    #[inline]
    pub fn with_arc<F, U>(&self, f: F) -> U
    where
        F: FnOnce(&Arc<T>) -> U,
        T: 'static,
    {
        // Synthesize transient Arc, which never touches the refcount.
        let transient = unsafe { ManuallyDrop::new(Arc::from_raw(self.p.as_ptr())) };

        // Expose the transient Arc to the callback, which may clone it if it wants
        // and forward the result to the user
        f(&transient)
    }

    /// Borrow this as an [`OffsetArc`]. This does *not* bump the refcount.
    #[inline]
    pub fn as_arc(&self) -> &OffsetArc<T> {
        unsafe { &*(self as *const _ as *const OffsetArc<T>) }
    }

    /// Similar to deref, but uses the lifetime `'a` rather than the lifetime of
    /// `self`, which is incompatible with the signature of the [`Deref`] trait.
    #[inline]
    pub fn get(&self) -> &'a T {
        unsafe { &*self.p.as_ptr() }
    }
}

impl<'a, T> Deref for OffsetArcBorrow<'a, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        self.get()
    }
}

impl<'a, 'b, T, U: PartialEq<T>> PartialEq<ArcBorrow<'a, T>> for ArcBorrow<'b, U> {
    #[inline]
    fn eq(&self, other: &ArcBorrow<'a, T>) -> bool {
        *(*self) == *(*other)
    }

    #[allow(clippy::partialeq_ne_impl)]
    #[inline]
    fn ne(&self, other: &ArcBorrow<'a, T>) -> bool {
        *(*self) != *(*other)
    }
}

impl<'a, 'b, T, U: PartialOrd<T>> PartialOrd<ArcBorrow<'a, T>> for ArcBorrow<'b, U> {
    #[inline]
    fn partial_cmp(&self, other: &ArcBorrow<'a, T>) -> Option<Ordering> {
        (**self).partial_cmp(&**other)
    }

    #[inline]
    fn lt(&self, other: &ArcBorrow<'a, T>) -> bool {
        *(*self) < *(*other)
    }

    #[inline]
    fn le(&self, other: &ArcBorrow<'a, T>) -> bool {
        *(*self) <= *(*other)
    }

    #[inline]
    fn gt(&self, other: &ArcBorrow<'a, T>) -> bool {
        *(*self) > *(*other)
    }

    #[inline]
    fn ge(&self, other: &ArcBorrow<'a, T>) -> bool {
        *(*self) >= *(*other)
    }
}

impl<'a, T: Ord> Ord for ArcBorrow<'a, T> {
    #[inline]
    fn cmp(&self, other: &ArcBorrow<'a, T>) -> Ordering {
        (**self).cmp(&**other)
    }
}

impl<'a, T: Eq> Eq for ArcBorrow<'a, T> {}

impl<'a, T: fmt::Display> fmt::Display for ArcBorrow<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<'a, T: fmt::Debug> fmt::Debug for ArcBorrow<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T: Hash> Hash for ArcBorrow<'_, T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state)
    }
}

impl<T> Borrow<T> for ArcBorrow<'_, T> {
    #[inline]
    fn borrow(&self) -> &T {
        &**self
    }
}

impl<T> AsRef<T> for ArcBorrow<'_, T> {
    #[inline]
    fn as_ref(&self) -> &T {
        &**self
    }
}

impl<'a, 'b, T, U: PartialEq<T>> PartialEq<OffsetArcBorrow<'a, T>> for OffsetArcBorrow<'b, U> {
    #[inline]
    fn eq(&self, other: &OffsetArcBorrow<'a, T>) -> bool {
        *(*self) == *(*other)
    }

    #[allow(clippy::partialeq_ne_impl)]
    #[inline]
    fn ne(&self, other: &OffsetArcBorrow<'a, T>) -> bool {
        *(*self) != *(*other)
    }
}

impl<'a, 'b, T, U: PartialOrd<T>> PartialOrd<OffsetArcBorrow<'a, T>> for OffsetArcBorrow<'b, U> {
    #[inline]
    fn partial_cmp(&self, other: &OffsetArcBorrow<'a, T>) -> Option<Ordering> {
        (**self).partial_cmp(&**other)
    }

    #[inline]
    fn lt(&self, other: &OffsetArcBorrow<'a, T>) -> bool {
        *(*self) < *(*other)
    }

    #[inline]
    fn le(&self, other: &OffsetArcBorrow<'a, T>) -> bool {
        *(*self) <= *(*other)
    }

    #[inline]
    fn gt(&self, other: &OffsetArcBorrow<'a, T>) -> bool {
        *(*self) > *(*other)
    }

    #[inline]
    fn ge(&self, other: &OffsetArcBorrow<'a, T>) -> bool {
        *(*self) >= *(*other)
    }
}

impl<'a, T: Ord> Ord for OffsetArcBorrow<'a, T> {
    #[inline]
    fn cmp(&self, other: &OffsetArcBorrow<'a, T>) -> Ordering {
        (**self).cmp(&**other)
    }
}

impl<'a, T: Eq> Eq for OffsetArcBorrow<'a, T> {}

impl<'a, T: fmt::Display> fmt::Display for OffsetArcBorrow<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<'a, T: fmt::Debug> fmt::Debug for OffsetArcBorrow<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T: Hash> Hash for OffsetArcBorrow<'_, T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state)
    }
}

impl<T> Borrow<T> for OffsetArcBorrow<'_, T> {
    #[inline]
    fn borrow(&self) -> &T {
        &**self
    }
}

impl<T> AsRef<T> for OffsetArcBorrow<'_, T> {
    #[inline]
    fn as_ref(&self) -> &T {
        &**self
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn borrow_count() {
        let mut borrows = Vec::with_capacity(100);
        let x = Arc::new(76);
        let y = Arc::borrow_arc(&x);
        assert_eq!(Arc::count(&x), 1);
        assert_eq!(ArcBorrow::count(y), 1);
        for i in 0..100 {
            borrows.push(x.clone());
            assert_eq!(Arc::count(&x), i + 2);
            assert_eq!(ArcBorrow::count(y), i + 2);
        }
    }
}