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
// NB: Last updated for Rust 1.40 parity. All impls are in rustdoc gutter order.

//! Borrowed forms of [`Rc`] and [`Arc`].
//!
//! [`ArcBorrow<_>`](`ArcBorrow`) is functionally equivalent to `&Arc<_>`,
//! but it's represented as `&T`, avoiding the extra indirection.
//!
//! # Examples
//!
//! ```rust
//! # use {rc_borrow::*, std::sync::Arc};
//! # type Resource = u32;
//! # fn acquire_resource() -> Arc<u32> { Arc::new(0) }
//! let resource: Arc<Resource> = acquire_resource();
//! let borrowed: ArcBorrow<'_, Resource> = (&resource).into();
//! let reference: &Resource = ArcBorrow::downgrade(borrowed);
//! let cloned: Arc<Resource> = ArcBorrow::upgrade(borrowed);
//! fn use_resource(resource: &Resource) { /* ... */ }
//! use_resource(&borrowed);
//! ```

#![warn(missing_docs, missing_debug_implementations)]
#![no_std]

extern crate alloc;
#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "erasable")]
use erasable::{Erasable, ErasablePtr, ErasedPtr};
#[cfg(feature = "std")]
use std::{
    io,
    net::ToSocketAddrs,
    panic::{RefUnwindSafe, UnwindSafe},
};
use {
    alloc::{
        rc::{self, Rc},
        sync::{self, Arc},
    },
    core::{
        borrow::Borrow,
        cmp::Ordering,
        fmt::{
            self, Binary, Debug, Display, Formatter, LowerExp, LowerHex, Octal, Pointer, UpperExp,
            UpperHex,
        },
        hash::{Hash, Hasher},
        marker::PhantomData,
        mem::ManuallyDrop,
        ops::Deref,
        ptr,
    },
};

/// This trait is a polyfill for (`A`)`Rc::as_raw` and (`A`)`Rc::clone_raw`.
/// See https://internals.rust-lang.org/t/_/11463/11 for why these are important.
/// By using a trait here, we can more easily switch when these functions are available.
trait RawRc<T: ?Sized> {
    type Weak;

    //noinspection RsSelfConvention
    fn as_raw(this: &Self) -> *const T;

    /// # Safety
    ///
    /// This pointer must have come from [`RawRc::as_raw`] or `into_raw`.
    unsafe fn clone_raw(this: *const T) -> Self;

    unsafe fn downgrade_raw(this: *const T) -> Self::Weak;
}

impl<T: ?Sized> RawRc<T> for Arc<T> {
    type Weak = sync::Weak<T>;

    #[inline(always)]
    fn as_raw(this: &Self) -> *const T {
        // Arc::as_ptr(this)
        Arc::into_raw(unsafe { ptr::read(this) })
    }

    #[inline(always)]
    unsafe fn clone_raw(this: *const T) -> Self {
        Arc::clone(&ManuallyDrop::new(Arc::from_raw(this)))
    }

    #[inline(always)]
    unsafe fn downgrade_raw(this: *const T) -> sync::Weak<T> {
        let this = ManuallyDrop::new(Arc::from_raw(this));
        Arc::downgrade(&this)
    }
}

impl<T: ?Sized> RawRc<T> for Rc<T> {
    type Weak = rc::Weak<T>;

    #[inline(always)]
    fn as_raw(this: &Self) -> *const T {
        // Rc::as_ptr(this)
        Rc::into_raw(unsafe { ptr::read(this) })
    }

    #[inline(always)]
    unsafe fn clone_raw(this: *const T) -> Self {
        Rc::clone(&ManuallyDrop::new(Rc::from_raw(this)))
    }

    #[inline(always)]
    unsafe fn downgrade_raw(this: *const T) -> rc::Weak<T> {
        let this = ManuallyDrop::new(Rc::from_raw(this));
        Rc::downgrade(&this)
    }
}

// sigh, I almost got away without this...
macro_rules! doc_comment {
    ($doc:expr, $($tt:tt)*) => {
        #[doc = $doc]
        $($tt)*
    };
}

macro_rules! rc_borrow {
    ($($(#[$m:meta])* $vis:vis struct $RcBorrow:ident = &$rc:ident::$Rc:ident;)*) => {$(
        $(#[$m])*
        $vis struct $RcBorrow<'a, T: ?Sized> {
            raw: ptr::NonNull<T>,
            marker: PhantomData<&'a $Rc<T>>
        }

        // NB: these cannot be `where &T: Send/Sync` as they allow upgrading to $Rc.
        unsafe impl<'a, T: ?Sized> Send for $RcBorrow<'a, T> where &'a $Rc<T>: Send {}
        unsafe impl<'a, T: ?Sized> Sync for $RcBorrow<'a, T> where &'a $Rc<T>: Sync {}

        impl<'a, T: ?Sized> From<&'a $Rc<T>> for $RcBorrow<'a, T> {
            fn from(v: &'a $Rc<T>) -> $RcBorrow<'a, T> {
                let raw = <$Rc<T> as RawRc<T>>::as_raw(v);
                $RcBorrow {
                    raw: unsafe { ptr::NonNull::new_unchecked(raw as *mut T) },
                    marker: PhantomData,
                }
            }
        }

        impl<'a, T: ?Sized> $RcBorrow<'a, T> {
            /// Convert this borrowed pointer into an owned pointer.
            $vis fn upgrade(this: Self) -> $Rc<T> {
                unsafe { <$Rc<T> as RawRc<T>>::clone_raw(this.raw.as_ptr()) }
            }

            /// Convert this borrowed pointer into a weak pointer.
            $vis fn to_weak(this: Self) -> $rc::Weak<T> {
                unsafe { <$Rc<T> as RawRc<T>>::downgrade_raw(this.raw.as_ptr()) }
            }

            /// Convert this borrowed pointer into a standard reference.
            ///
            /// This gives you a long-lived reference,
            /// whereas dereferencing gives a temporary borrow.
            $vis fn downgrade(this: Self) -> &'a T {
                unsafe { &*this.raw.as_ptr() }
            }

            /// Get the number of strong owning pointers to this allocation.
            $vis fn strong_count(this: Self) -> usize {
                let rc = unsafe { ManuallyDrop::new($Rc::from_raw(Self::into_raw(this))) };
                $Rc::strong_count(&rc)
            }

            /// Get the number of weak owning pointers to this allocation.
            $vis fn weak_count(this: Self) -> usize {
                let rc = unsafe { ManuallyDrop::new($Rc::from_raw(Self::into_raw(this))) };
                $Rc::weak_count(&rc)
            }

            /// Get a raw pointer that can be used with `from_raw`.
            $vis fn into_raw(this: Self) -> *const T {
                ManuallyDrop::new(this).raw.as_ptr()
            }

            doc_comment! {
                concat!("\
Construct a new `", stringify!($RcBorrow), "` from a raw pointer.

The raw pointer must have been previously returned by a call to
`",stringify!($RcBorrow),"<U>::into_raw` or `",stringify!($Rc),"<U>::as_raw`
where `U` must have the same size and alignment as `T`. This is trivially true
if `U` is `T`. Note that if `U` is not `T`, this is a pointer cast (transmute)
between the two types, and the types must be transmute-compatible."),
                $vis unsafe fn from_raw(ptr: *const T) -> Self {
                    $RcBorrow {
                        raw: ptr::NonNull::new_unchecked(ptr as *mut T),
                        marker: PhantomData
                    }
                }
            }
        }

        // ~~~ &T like impls ~~~ //

        #[cfg(feature = "erasable")]
        unsafe impl<T: ?Sized> ErasablePtr for $RcBorrow<'_, T>
        where
            T: Erasable
        {
            #[inline(always)]
            fn erase(this: Self) -> ErasedPtr {
                T::erase(this.raw)
            }

            #[inline(always)]
            unsafe fn unerase(this: ErasedPtr) -> Self {
                $RcBorrow {
                    raw: T::unerase(this),
                    marker: PhantomData,
                }
            }
        }

        impl<T: ?Sized, U: ?Sized> AsRef<U> for $RcBorrow<'_, T>
        where
            T: AsRef<U>,
        {
            fn as_ref(&self) -> &U {
                (**self).as_ref()
            }
        }

        impl<T: ?Sized> Binary for $RcBorrow<'_, T>
        where
            T: Binary,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                (**self).fmt(f)
            }
        }

        impl<T: ?Sized> Borrow<T> for $RcBorrow<'_, T> {
            fn borrow(&self) -> &T {
                &**self
            }
        }

        impl<T: ?Sized> Clone for $RcBorrow<'_, T> {
            fn clone(&self) -> Self { *self }
        }

        // CoerceUnsized is unstable

        impl<T: ?Sized> Copy for $RcBorrow<'_, T> {}

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

        impl<T: ?Sized> Deref for $RcBorrow<'_, T> {
            type Target = T;
            fn deref(&self) -> &T {
                Self::downgrade(*self)
            }
        }

        // DispatchFromDyn is unstable

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

        impl<T: ?Sized> Eq for $RcBorrow<'_, T> where T: Eq {}

        // Fn, FnMut, FnOnce are unstable to implement

        impl<T: ?Sized> Hash for $RcBorrow<'_, T>
        where
            T: Hash,
        {
            fn hash<H: Hasher>(&self, state: &mut H) {
                (**self).hash(state)
            }
        }

        impl<T: ?Sized> LowerExp for $RcBorrow<'_, T>
        where
            T: LowerExp,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                (**self).fmt(f)
            }
        }

        impl<T: ?Sized> LowerHex for $RcBorrow<'_, T>
        where
            T: LowerHex,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                (**self).fmt(f)
            }
        }

        impl<T: ?Sized> Octal for $RcBorrow<'_, T>
        where
            T: Octal,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                (**self).fmt(f)
            }
        }

        impl<T: Ord> Ord for $RcBorrow<'_, T>
        where
            T: Ord,
        {
            fn cmp(&self, other: &Self) -> Ordering {
                (**self).cmp(&**other)
            }
        }

        impl<T: ?Sized, O> PartialEq<O> for $RcBorrow<'_, T>
        where
            O: Deref,
            T: PartialEq<O::Target>,
        {
            fn eq(&self, other: &O) -> bool {
                (**self).eq(&*other)
            }
        }

        impl<T: ?Sized, O> PartialOrd<O> for $RcBorrow<'_, T>
        where
            O: Deref,
            T: PartialOrd<O::Target>,
        {
            fn partial_cmp(&self, other: &O) -> Option<Ordering> {
                (**self).partial_cmp(&*other)
            }
        }

        impl<T: ?Sized> Pointer for $RcBorrow<'_, T>
        where
            T: Pointer,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                (**self).fmt(f)
            }
        }

        #[cfg(feature = "std")]
        impl<T: ?Sized> ToSocketAddrs for $RcBorrow<'_, T>
        where
            T: ToSocketAddrs
        {
            type Iter = T::Iter;
            fn to_socket_addrs(&self) -> io::Result<T::Iter> {
                (**self).to_socket_addrs()
            }
        }

        impl<T: ?Sized> Unpin for $RcBorrow<'_, T> {}

        #[cfg(feature = "std")]
        impl<T: ?Sized> UnwindSafe for $RcBorrow<'_, T> where T: RefUnwindSafe {}

        impl<T: ?Sized> UpperExp for $RcBorrow<'_, T>
        where
            T: UpperExp,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                (**self).fmt(f)
            }
        }

        impl<T: ?Sized> UpperHex for $RcBorrow<'_, T>
        where
            T: UpperHex,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                (**self).fmt(f)
            }
        }
    )*}
}

rc_borrow! {
    /// Borrowed version of [`Arc`].
    ///
    /// This type is guaranteed to have the same repr as `&T`.
    #[repr(transparent)]
    pub struct ArcBorrow = &sync::Arc;
    /// Borrowed version of [`Rc`].
    ///
    /// This type is guaranteed to have the same repr as `&T`.
    #[repr(transparent)]
    pub struct RcBorrow = &rc::Rc;
}