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
use crate::*;

use super::Arc;

/// An `Arc` that is known to be uniquely owned
///
/// When `Arc`s are constructed, they are known to be
/// uniquely owned. In such a case it is safe to mutate
/// the contents of the `Arc`. Normally, one would just handle
/// this by mutating the data on the stack before allocating the
/// `Arc`, however it's possible the data is large or unsized
/// and you need to heap-allocate it earlier in such a way
/// that it can be freely converted into a regular `Arc` once you're
/// done.
///
/// `ArcBox` exists for this purpose, when constructed it performs
/// the same allocations necessary for an `Arc`, however it allows mutable access.
/// Once the mutation is finished, you can call `.shareable()` and get a regular `Arc`
/// out of it. You can also attempt to cast an `Arc` back into a `ArcBox`, which will
/// succeed if the `Arc` is unique
///
/// ```rust
/// # use elysees::ArcBox;
/// # use std::ops::Deref;
/// let data = [1, 2, 3, 4, 5];
/// let mut x = ArcBox::new(data);
/// let x_ptr = x.deref() as *const _;
///
/// x[4] = 7; // mutate!
///
/// // The allocation has been modified, but not moved
/// assert_eq!(x.deref(), &[1, 2, 3, 4, 7]);
/// assert_eq!(x_ptr, x.deref() as *const _);
///
/// let y = x.shareable(); // y is an Arc<T>
///
/// // The allocation has not been modified or moved
/// assert_eq!(y.deref(), &[1, 2, 3, 4, 7]);
/// assert_eq!(x_ptr, y.deref() as *const _);
/// ```

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub struct ArcBox<T: ?Sized>(pub(crate) Arc<T>);

impl<T> ArcBox<T> {
    /// Construct a new ArcBox
    #[inline]
    pub fn new(data: T) -> Self {
        ArcBox(Arc::new(data))
    }
}

impl<T: Clone> Clone for ArcBox<T> {
    #[inline]
    fn clone(&self) -> ArcBox<T> {
        ArcBox(Arc::new(self.0.deref().clone()))
    }
}

impl<T: ?Sized> ArcBox<T> {
    /// Convert to a shareable Arc<T> once we're done mutating it
    #[inline]
    pub fn shareable(self) -> Arc<T> {
        self.0
    }
}

impl<T: ?Sized> Deref for ArcBox<T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &T {
        &*self.0
    }
}

impl<T: ?Sized> DerefMut for ArcBox<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        // We know this to be uniquely owned
        unsafe { &mut *self.0.ptr.as_ptr() }
    }
}

impl<T: ?Sized> Borrow<T> for ArcBox<T> {
    #[inline]
    fn borrow(&self) -> &T {
        &**self
    }
}

impl<T: ?Sized> AsRef<T> for ArcBox<T> {
    #[inline]
    fn as_ref(&self) -> &T {
        &**self
    }
}

impl<T: ?Sized> BorrowMut<T> for ArcBox<T> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut T {
        &mut **self
    }
}

impl<T: ?Sized> AsMut<T> for ArcBox<T> {
    #[inline]
    fn as_mut(&mut self) -> &mut T {
        &mut **self
    }
}

impl<T: ?Sized> AsRef<*const T> for ArcBox<T> {
    #[inline]
    fn as_ref(&self) -> &*const T {
        unsafe { &*(self as *const ArcBox<T> as *const *const T) }
    }
}

impl<T: ?Sized> AsRef<*mut T> for ArcBox<T> {
    #[inline]
    fn as_ref(&self) -> &*mut T {
        unsafe { &*(self as *const ArcBox<T> as *const *mut T) }
    }
}

impl<T: ?Sized> AsRef<ptr::NonNull<T>> for ArcBox<T> {
    #[inline]
    fn as_ref(&self) -> &ptr::NonNull<T> {
        unsafe { &*(self as *const ArcBox<T> as *const ptr::NonNull<T>) }
    }
}

impl<T: Default> Default for ArcBox<T> {
    #[inline]
    fn default() -> ArcBox<T> {
        ArcBox::new(Default::default())
    }
}

#[cfg(feature = "stable_deref_trait")]
unsafe impl<T: ?Sized> StableDeref for ArcBox<T> {}

#[cfg(feature = "serde")]
impl<'de, T: Deserialize<'de>> Deserialize<'de> for ArcBox<T> {
    fn deserialize<D>(deserializer: D) -> Result<ArcBox<T>, D::Error>
    where
        D: ::serde::de::Deserializer<'de>,
    {
        T::deserialize(deserializer).map(ArcBox::new)
    }
}

#[cfg(feature = "serde")]
impl<T: ?Sized + Serialize> Serialize for ArcBox<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: ::serde::ser::Serializer,
    {
        (**self).serialize(serializer)
    }
}

#[cfg(feature = "erasable")]
unsafe impl<T: ?Sized + Erasable> ErasablePtr for ArcBox<T> {
    fn erase(this: Self) -> ErasedPtr {
        ErasablePtr::erase(this.0)
    }

    unsafe fn unerase(this: ErasedPtr) -> Self {
        ArcBox(ErasablePtr::unerase(this))
    }
}

#[cfg(feature = "slice-dst")]
mod slice_dst_impl {
    use super::*;
    use slice_dst::{AllocSliceDst, SliceDst, TryAllocSliceDst};

    #[cfg(feature = "slice-dst")]
    unsafe impl<S: ?Sized + SliceDst> TryAllocSliceDst<S> for ArcBox<S> {
        unsafe fn try_new_slice_dst<I, E>(len: usize, init: I) -> Result<Self, E>
        where
            I: FnOnce(ptr::NonNull<S>) -> Result<(), E>,
        {
            Arc::try_new_slice_dst(len, init).map(ArcBox)
        }
    }

    unsafe impl<S: ?Sized + SliceDst> AllocSliceDst<S> for ArcBox<S> {
        unsafe fn new_slice_dst<I>(len: usize, init: I) -> Self
        where
            I: FnOnce(ptr::NonNull<S>),
        {
            ArcBox(Arc::new_slice_dst(len, init))
        }
    }
}

#[cfg(feature = "arbitrary")]
mod arbitrary_impl {
    use super::*;
    use arbitrary::{Arbitrary, Result, Unstructured};
    impl<T: Arbitrary> Arbitrary for ArcBox<T> {
        fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> {
            T::arbitrary(u).map(ArcBox::new)
        }
        fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> {
            T::arbitrary_take_rest(u).map(ArcBox::new)
        }
        fn size_hint(depth: usize) -> (usize, Option<usize>) {
            T::size_hint(depth)
        }
        fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
            Box::new(self.deref().shrink().map(ArcBox::new))
        }
    }
}