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
use std::ffi::c_void;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::alloc::Layout;
use std::cell::Cell;

use crate::{GcRebrand, GcSafe, GcSimpleAlloc, GcArray};
use crate::vec::raw::{IGcVec, GcRawVec};

use super::{EpsilonCollectorId, EpsilonContext};

/// The header of an object in the epsilon collector.
///
/// Not all objects need headers.
/// If they are `Copy` and statically sized they can be elided.
/// They are also unnecessary for statically allocated objects.
pub struct EpsilonHeader {
    /// This object's `TypeInfo`, or `None` if it doesn't need any.
    pub type_info: &'static TypeInfo,
    /// The next allocated object, or `None` if this is the final object.
    pub next: Option<NonNull<EpsilonHeader>>
}
/*
 * We are Send + Sync because once we are allocated
 * `next` and `type_info` cannot change
 */
unsafe impl Send for EpsilonHeader {}
unsafe impl Sync for EpsilonHeader {}
impl EpsilonHeader {
    pub const LAYOUT: Layout = Layout::new::<Self>();
    /// Assume the specified object has a header,
    /// and retrieve it if so.
    ///
    /// ## Safety
    /// Undefined behavior if the object doesn't have a header.
    /// Undefined behavior if the object isn't allocated in the epsilon collector.
    #[inline]
    pub unsafe fn assume_header<T: ?Sized>(header: *const T) -> *const EpsilonHeader {
        let (_, offset) = Self::LAYOUT.extend(Layout::for_value(&*header)).unwrap_unchecked();
        (header as *const c_void).sub(offset).cast()
    }
    #[inline]
    #[track_caller]
    pub unsafe fn determine_layout(&self) -> Layout {
        let tp = self.type_info;
        match tp.layout {
            LayoutInfo::Fixed(fixed) => fixed,
            LayoutInfo::Array { element_layout } |
            LayoutInfo::Vec { element_layout } => {
                let array_header = EpsilonArrayHeader::from_common_header(self);
                let len = (*array_header).len;
                element_layout.repeat(len).unwrap_unchecked().0
            }
        }
    }
}
#[repr(C)]
pub struct EpsilonArrayHeader {
    pub len: usize,
    pub common_header: EpsilonHeader,
}
impl EpsilonArrayHeader {
    const COMMON_OFFSET: usize = std::mem::size_of::<Self>() - std::mem::size_of::<EpsilonHeader>();
    #[inline]
    pub unsafe fn from_common_header(header: *const EpsilonHeader) -> *const Self {
        (header as *const c_void).sub(Self::COMMON_OFFSET).cast()
    }
}
#[repr(C)]
pub struct EpsilonVecHeader {
    pub capacity: usize,
    // NOTE: Suffix must be transmutable to `EpsilonArrayHeader`
    pub len: Cell<usize>,
    pub common_header: EpsilonHeader,
}
impl EpsilonVecHeader {
    const COMMON_OFFSET: usize = std::mem::size_of::<Self>() - std::mem::size_of::<EpsilonHeader>();
}
pub enum LayoutInfo {
    Fixed(Layout),
    /// A variable sized array
    Array {
        element_layout: Layout
    },
    /// A variable sized vector
    Vec {
        element_layout: Layout
    }
}
impl LayoutInfo {
    #[inline]
    pub const fn align(&self) -> usize {
        match *self {
            LayoutInfo::Fixed(layout) |
            LayoutInfo::Array { element_layout: layout } |
            LayoutInfo::Vec { element_layout: layout }  => layout.align()
        }
    }
    #[inline]
    pub fn common_header_offset(&self) -> usize {
        match *self {
            LayoutInfo::Fixed(_) => 0,
            LayoutInfo::Array { .. } => EpsilonArrayHeader::COMMON_OFFSET,
            LayoutInfo::Vec { .. } => EpsilonVecHeader::COMMON_OFFSET
        }
    }
}
pub struct TypeInfo {
    /// The function to drop this object, or `None` if the object doesn't need to be dropped
    pub drop_func: Option<unsafe fn(*mut c_void)>,
    pub layout: LayoutInfo
}
impl TypeInfo {
    #[inline]
    pub const fn may_ignore(&self) -> bool {
        // NOTE: We don't care about `size`
        self.drop_func.is_none() &&
            self.layout.align() <= std::mem::align_of::<usize>()
    }
    #[inline]
    pub const fn of<T>() -> &'static TypeInfo {
        <T as StaticTypeInfo>::TYPE_INFO
    }
    #[inline]
    pub const fn of_array<T>() -> &'static TypeInfo {
        <[T] as StaticTypeInfo>::TYPE_INFO
    }
    #[inline]
    pub const fn of_vec<T>() -> &'static TypeInfo {
        // For now, vectors and arrays share type info
        <T as StaticTypeInfo>::VEC_INFO.as_ref().unwrap()
    }
}
trait StaticTypeInfo {
    const TYPE_INFO: &'static TypeInfo;
    const VEC_INFO: &'static Option<TypeInfo>;
}
impl<T> StaticTypeInfo for T {
    const TYPE_INFO: &'static TypeInfo = &TypeInfo {
        drop_func: if std::mem::needs_drop::<T>() {
            Some(unsafe { std::mem::transmute::<unsafe fn(*mut T), unsafe fn(*mut c_void)>(std::ptr::drop_in_place::<T>) })
        } else {
            None
        },
        layout: LayoutInfo::Fixed(Layout::new::<T>()),
    };
    const VEC_INFO: &'static Option<TypeInfo> = &Some(TypeInfo {
        drop_func: if std::mem::needs_drop::<T>() {
            Some(drop_array::<T>)
        } else {
            None
        },
        layout: LayoutInfo::Vec {
            element_layout: Layout::new::<T>()
        }
    });
}
impl<T> StaticTypeInfo for [T] {
    const TYPE_INFO: &'static TypeInfo = &TypeInfo {
        drop_func: if std::mem::needs_drop::<T>() {
            Some(drop_array::<T>)
        } else { None },
        layout: LayoutInfo::Array {
            element_layout: Layout::new::<T>()
        }
    };
    const VEC_INFO: &'static Option<TypeInfo> = &None;
}
/// Drop an array or vector of the specified type
unsafe fn drop_array<T>(ptr: *mut c_void) {
    let header = EpsilonArrayHeader::from_common_header(
        EpsilonHeader::assume_header(ptr as *const _ as *const T)
    );
    let len = (*header).len;
    std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(ptr as *mut T, len));
}


/// The raw representation of a vector in the "epsilon" collector
/*
 * Implementation note: Length and capacity are stored implicitly in the [`EpsilonVecHeader`]
 */
pub struct EpsilonRawVec<'gc, T> {
    header: NonNull<EpsilonVecHeader>,
    context: &'gc EpsilonContext,
    marker: PhantomData<crate::Gc<'gc, [T], EpsilonCollectorId>>
}
impl<'gc, T> Copy for EpsilonRawVec<'gc, T> {}
impl<'gc, T> Clone for EpsilonRawVec<'gc, T> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}
impl<'gc, T> EpsilonRawVec<'gc, T> {
    #[inline]
    pub(in super) unsafe fn from_raw_parts(
        header: NonNull<EpsilonVecHeader>,
        context: &'gc EpsilonContext
    ) -> Self {
        EpsilonRawVec {
            header, context, marker: PhantomData
        }
    }
    #[inline]
    fn header(&self) -> *const EpsilonVecHeader {
        self.header.as_ptr() as *const EpsilonVecHeader
    }
}
zerogc_derive::unsafe_gc_impl!(
    target => EpsilonRawVec<'gc, T>,
    params => ['gc, T: GcSafe<'gc, EpsilonCollectorId>],
    bounds => {
        TraceImmutable => never,
        GcRebrand => { where T: GcRebrand<'new_gc, EpsilonCollectorId>, T::Branded: Sized }
    },
    branded_type => EpsilonRawVec<'new_gc, T::Branded>,
    collector_id => EpsilonCollectorId,
    NEEDS_TRACE => true, // meh
    NEEDS_DROP => T::NEEDS_DROP,
    null_trace => never,
    trace_mut => |self, visitor| {
        unsafe { visitor.trace_vec(self) }
    },
);
#[inherent::inherent]
unsafe impl<'gc, T: GcSafe<'gc, EpsilonCollectorId>> GcRawVec<'gc, T> for EpsilonRawVec<'gc, T> {
    #[inline]
    #[allow(dead_code)]
    unsafe fn steal_as_array_unchecked(mut self) -> GcArray<'gc, T, EpsilonCollectorId> {
        // Set capacity to zero, so no one else gets any funny ideas!
        self.header.as_mut().capacity = 0;
        GcArray::from_raw_ptr(NonNull::new_unchecked(self.as_mut_ptr()), self.len())
    }
    pub fn iter(&self) -> zerogc::vec::raw::RawVecIter<'gc, T, Self>
        where T: Copy;
}
#[inherent::inherent]
unsafe impl<'gc, T: GcSafe<'gc, EpsilonCollectorId>> IGcVec<'gc, T> for EpsilonRawVec<'gc, T> {
    type Id = EpsilonCollectorId;

    #[inline]
    pub fn with_capacity_in(capacity: usize, ctx: &'gc EpsilonContext) -> Self {
        ctx.alloc_raw_vec_with_capacity::<T>(capacity)
    }

    #[inline]
    pub fn len(&self) -> usize {
        unsafe {
            (*self.header()).len.get()
        }
    }

    #[inline]
    pub unsafe fn set_len(&mut self, len: usize) {
        (*self.header()).len.set(len)
    }

    #[inline]
    pub fn capacity(&self) -> usize {
        unsafe { (*self.header()).capacity }
    }

    #[inline]
    pub fn reserve_in_place(&mut self, _additional: usize) -> Result<(), crate::vec::raw::ReallocFailedError> {
        Err(crate::vec::raw::ReallocFailedError::Unsupported)
    }

    #[inline]
    pub unsafe fn as_ptr(&self) -> *const T {
        const LAYOUT: Layout = Layout::new::<EpsilonVecHeader>();
        let offset = LAYOUT.size() + 
            LAYOUT.padding_needed_for(core::mem::align_of::<T>());
        (self.header() as *const u8).add(offset) as *const T
    }

    #[inline]
    pub fn context(&self) -> &'gc EpsilonContext {
        self.context
    }

    // Default methods:
    pub unsafe fn as_mut_ptr(&mut self) -> *mut T;
    pub fn replace(&mut self, index: usize, val: T) -> T;
    pub fn set(&mut self, index: usize, val: T);
    pub fn extend_from_slice(&mut self, src: &[T])
        where T: Copy;
    pub fn push(&mut self, val: T);
    pub fn pop(&mut self) -> Option<T>;
    pub fn swap_remove(&mut self, index: usize) -> T;
    pub fn reserve(&mut self, additional: usize);
    pub fn is_empty(&self) -> bool;
    pub fn new_in(ctx: &'gc EpsilonContext) -> Self;
    pub fn copy_from_slice(src: &[T], ctx: &'gc EpsilonContext) -> Self
        where T: Copy;
    pub fn from_vec(src: Vec<T>, ctx: &'gc EpsilonContext) -> Self;
    pub fn get(&mut self, index: usize) -> Option<T>
        where T: Copy;
    pub unsafe fn as_slice_unchecked(&self) -> &[T];
}
impl<'gc, T: GcSafe<'gc, EpsilonCollectorId>> Extend<T> for EpsilonRawVec<'gc, T> {
    #[inline]
    fn extend<E: IntoIterator<Item=T>>(&mut self, iter: E) {
        let iter = iter.into_iter();
        self.reserve(iter.size_hint().1.unwrap_or(0));
        for val in iter {
            self.push(val);
        }
    }
}