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
//! Contains definition for `RcArray`, which is an implementation-agnositc,
//! reference-counted array.
use super::ref_counters::*;
use crate::prelude::*;
use core::marker::PhantomData;
use core::sync::atomic::Ordering;

// A is the array reference that this type wraps
// R is the reference counter for the label of this type
// L is the label of this type
// E is the element that this type is an array of
// B is the type that A dereferences to using its `.to_null()` method.
/// `RcArray` is a generic, implementation-agnositc array. It uses traits to
/// handle literally everything. Implementing your own version is not recommended.
#[repr(C)]
pub struct RcArray<'a, A, R, E, L = ()>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    data: ManuallyDrop<A>,
    phantom: PhantomData<(&'a E, R, L)>,
}

impl<'a, A, R, E, L> RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn check_null(&self) {
        #[cfg(not(feature = "no-asserts"))]
        assert!(
            !self.is_null(),
            "Null dereference of reference-counted array."
        );
    }
    fn from_ref(ptr: A) -> Self {
        Self {
            data: ManuallyDrop::new(ptr),
            phantom: PhantomData,
        }
    }
    // This would be unsafe if the `A` were returned to caller, but since it
    // isn't, everything should be fiiiiiiiine
    fn to_ref(self) -> A {
        let ret = unsafe { mem::transmute_copy(&self.data) };
        mem::forget(self);
        ret
    }
    pub fn ref_count(&self) -> usize {
        self.data.get_label().counter()
    }
}

impl<'a, A, R, E, L> BaseArrayRef for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn is_null(&self) -> bool {
        (*self.data).is_null()
    }
}

impl<'a, A, R, E, L> Clone for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn clone(&self) -> Self {
        if self.is_null() {
            Self::null_ref()
        } else {
            (*self.data).get_label().increment();
            unsafe { mem::transmute_copy(self) }
        }
    }
}

impl<'a, A, R, E, L> ArrayRef for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn to_null(&mut self) {
        if self.is_null() {
            return;
        } else {
            let ref_count = self.data.get_label_mut().decrement();

            // Set this reference to null
            let other = mem::replace(self, Self::null_ref());

            if ref_count == 0 {
                let to_drop: A = unsafe { mem::transmute_copy(&*other.data) };
                mem::drop(to_drop); // Drop is here to be explicit about intent
            }
            mem::forget(other);
        }
    }

    fn null_ref() -> Self {
        Self::from_ref(unsafe { A::null_ref() })
    }
}

impl<'a, A, R, E, L> Index<usize> for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    type Output = E;
    fn index(&self, idx: usize) -> &E {
        self.check_null();
        &self.data[idx]
    }
}

impl<'a, A, R, E, L> IndexMut<usize> for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn index_mut(&mut self, idx: usize) -> &mut E {
        self.check_null();
        &mut self.data[idx]
    }
}

impl<'a, A, R, E, L> Drop for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn drop(&mut self) {
        self.to_null();
        mem::forget(self);
    }
}

impl<'a, A, R, E, L> Container<(usize, E)> for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn add(&mut self, elem: (usize, E)) {
        self.check_null();
        self[elem.0] = elem.1;
    }
    fn len(&self) -> usize {
        self.check_null();
        self.data.len()
    }
}

impl<'a, A, R, E, L> CopyMap<'a, usize, E> for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn get(&'a self, key: usize) -> Option<&'a E> {
        self.check_null();
        if key > self.len() {
            None
        } else {
            Some(&self[key])
        }
    }
    fn get_mut(&'a mut self, key: usize) -> Option<&'a mut E> {
        self.check_null();
        if key > self.len() {
            None
        } else {
            Some(&mut self[key])
        }
    }
    fn insert(&mut self, key: usize, value: E) -> Option<E> {
        self.check_null();
        if key > self.len() {
            None
        } else {
            Some(mem::replace(&mut self[key], value))
        }
    }
}

impl<'a, A, R, E, L> Array<'a, E> for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
}

impl<'a, A, R, E, L> LabelledArray<'a, E, L> for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn with_label<F>(label: L, len: usize, mut func: F) -> Self
    where
        F: FnMut(&mut L, usize) -> E,
    {
        let new_ptr = A::with_label(R::new(label), len, |rc_struct, idx| {
            func(&mut rc_struct.get_data_mut(), idx)
        });
        Self::from_ref(new_ptr)
    }
    unsafe fn with_label_unsafe(label: L, len: usize) -> Self {
        Self::from_ref(A::with_label_unsafe(R::new(label), len))
    }
    fn get_label(&self) -> &L {
        self.check_null();
        self.data.get_label().get_data()
    }
    fn get_label_mut(&mut self) -> &mut L {
        self.check_null();
        self.data.get_label_mut().get_data_mut()
    }
    unsafe fn get_label_unsafe(&self) -> &mut L {
        self.data.get_label_unsafe().get_data_mut()
    }
    unsafe fn get_unsafe(&self, idx: usize) -> &mut E {
        self.data.get_unsafe(idx)
    }
}

impl<'a, A, R, E> MakeArray<'a, E> for RcArray<'a, A, R, E, ()>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<()>,
    E: 'a,
{
    fn new<F>(len: usize, mut func: F) -> Self
    where
        F: FnMut(usize) -> E,
    {
        Self::with_label((), len, |_, idx| func(idx))
    }
}

impl<'a, A, R, E, L> DefaultLabelledArray<'a, E, L> for RcArray<'a, A, R, E, L>
where
    A: 'a
        + DefaultLabelledArray<'a, E, R>
        + LabelledArray<'a, E, R>
        + BaseArrayRef
        + UnsafeArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a + Default,
{
    fn with_len(label: L, len: usize) -> Self {
        Self::from_ref(A::with_len(R::new(label), len))
    }
}

unsafe impl<'a, A, R, E, L> Send for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L> + Send + Sync,
    L: 'a + Send + Sync,
    E: 'a + Send + Sync,
{
}

unsafe impl<'a, A, R, E, L> Sync for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef,
    R: 'a + RefCounter<L> + Send + Sync,
    L: 'a + Send + Sync,
    E: 'a + Send + Sync,
{
}

impl<'a, A, R, E, L> AtomicArrayRef for RcArray<'a, A, R, E, L>
where
    A: 'a + LabelledArray<'a, E, R> + BaseArrayRef + UnsafeArrayRef + AtomicArrayRef,
    R: 'a + RefCounter<L>,
    L: 'a,
    E: 'a,
{
    fn compare_and_swap(&self, current: Self, new: Self, order: Ordering) -> Self {
        Self::from_ref((*self.data).compare_and_swap(current.to_ref(), new.to_ref(), order))
    }
    fn compare_exchange(
        &self,
        current: Self,
        new: Self,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Self, Self> {
        match (*self.data).compare_exchange(current.to_ref(), new.to_ref(), success, failure) {
            Ok(data) => Ok(Self::from_ref(data)),
            Err(data) => Err(Self::from_ref(data)),
        }
    }
    fn compare_exchange_weak(
        &self,
        current: Self,
        new: Self,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Self, Self> {
        match (*self.data).compare_exchange_weak(current.to_ref(), new.to_ref(), success, failure) {
            Ok(data) => Ok(Self::from_ref(data)),
            Err(data) => Err(Self::from_ref(data)),
        }
    }
    fn load(&self, order: Ordering) -> Self {
        Self::from_ref((*self.data).load(order))
    }
    fn store(&self, ptr: Self, order: Ordering) {
        (*self.data).store(ptr.to_ref(), order);
    }
    fn swap(&self, ptr: Self, order: Ordering) -> Self {
        Self::from_ref((*self.data).swap(ptr.to_ref(), order))
    }
}