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
use core::{
alloc::Layout,
borrow::Borrow,
fmt::{self, Debug, Display, Pointer},
hash::{Hash, Hasher},
marker::PhantomData,
ops::Deref,
ptr::NonNull,
};
use crate::{
Finalization,
barrier::{Unlock, Write},
collect::{Collect, Trace},
context::Mutation,
gc_weak::GcWeak,
static_collect::Static,
types::{GcBox, GcBoxHeader, GcBoxInner, GcColor, Invariant},
};
/// A garbage collected pointer to a type T. Implements Copy, and is implemented as a plain machine
/// pointer. You can only allocate `Gc` pointers through a `&Mutation<'gc>` inside an arena type,
/// and through "generativity" such `Gc` pointers may not escape the arena they were born in or
/// be stored inside TLS. This, combined with correct `Collect` implementations, means that `Gc`
/// pointers will never be dangling and are always safe to access.
pub struct Gc<'gc, T: ?Sized + 'gc> {
pub(crate) ptr: NonNull<GcBoxInner<T>>,
pub(crate) _invariant: Invariant<'gc>,
}
impl<'gc, T: Debug + ?Sized + 'gc> Debug for Gc<'gc, T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, fmt)
}
}
impl<'gc, T: ?Sized + 'gc> Pointer for Gc<'gc, T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&Gc::as_ptr(*self), fmt)
}
}
impl<'gc, T: Display + ?Sized + 'gc> Display for Gc<'gc, T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, fmt)
}
}
impl<'gc, T: ?Sized + 'gc> Copy for Gc<'gc, T> {}
impl<'gc, T: ?Sized + 'gc> Clone for Gc<'gc, T> {
#[inline]
fn clone(&self) -> Gc<'gc, T> {
*self
}
}
unsafe impl<'gc, T: ?Sized + 'gc> Collect<'gc> for Gc<'gc, T> {
#[inline]
fn trace<C: Trace<'gc>>(&self, cc: &mut C) {
cc.trace_gc(Self::erase(*self))
}
}
impl<'gc, T: ?Sized + 'gc> Deref for Gc<'gc, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
unsafe { &self.ptr.as_ref().value }
}
}
impl<'gc, T: ?Sized + 'gc> AsRef<T> for Gc<'gc, T> {
#[inline]
fn as_ref(&self) -> &T {
unsafe { &self.ptr.as_ref().value }
}
}
impl<'gc, T: ?Sized + 'gc> Borrow<T> for Gc<'gc, T> {
#[inline]
fn borrow(&self) -> &T {
unsafe { &self.ptr.as_ref().value }
}
}
impl<'gc, T: Collect<'gc> + 'gc> Gc<'gc, T> {
#[inline]
pub fn new(mc: &Mutation<'gc>, t: T) -> Gc<'gc, T> {
Gc {
ptr: mc.allocate(t),
_invariant: PhantomData,
}
}
}
impl<'gc, T: 'static> Gc<'gc, T> {
/// Create a new `Gc` pointer from a static value.
///
/// This method does not require that the type `T` implement `Collect`. This uses [`Static`]
/// internally to automatically provide a trivial `Collect` impl and is equivalent to the
/// following code:
///
/// ```rust
/// # use gc_arena::{Gc, Static};
/// # fn main() {
/// # gc_arena::arena::rootless_mutate(|mc| {
/// struct MyStaticStruct;
/// let p = Gc::new(mc, Static(MyStaticStruct));
/// // This is allowed because `Static` is `#[repr(transparent)]`
/// let p: Gc<MyStaticStruct> = unsafe { Gc::cast(p) };
/// # });
/// # }
/// ```
#[inline]
pub fn new_static(mc: &Mutation<'gc>, t: T) -> Gc<'gc, T> {
let p = Gc::new(mc, Static(t));
// SAFETY: `Static` is `#[repr(transparent)]`.
unsafe { Gc::cast::<T>(p) }
}
}
impl<'gc, T: ?Sized + 'gc> Gc<'gc, T> {
/// Cast a `Gc` pointer to a different type.
///
/// # Safety
/// It must be valid to dereference a `*mut U` that has come from casting a `*mut T`.
#[inline]
pub unsafe fn cast<U: 'gc>(this: Gc<'gc, T>) -> Gc<'gc, U> {
Gc {
ptr: NonNull::cast(this.ptr),
_invariant: PhantomData,
}
}
/// Cast a `Gc` to the unit type.
///
/// This is exactly the same as `unsafe { Gc::cast::<()>(this) }`, but we can provide this
/// method safely because it is always safe to dereference a `*mut ()` that has come from
/// casting a `*mut T`.
#[inline]
pub fn erase(this: Gc<'gc, T>) -> Gc<'gc, ()> {
unsafe { Gc::cast(this) }
}
/// Retrieve a `Gc` from a raw pointer obtained from `Gc::as_ptr`
///
/// # Safety
/// The provided pointer must have been obtained from `Gc::as_ptr`, and the pointer must not
/// have been collected yet.
#[inline]
pub unsafe fn from_ptr(ptr: *const T) -> Gc<'gc, T> {
unsafe {
let layout = Layout::new::<GcBoxHeader>();
let (_, header_offset) = layout.extend(Layout::for_value(&*ptr)).unwrap();
let header_offset = -(header_offset as isize);
let ptr = (ptr as *mut T).byte_offset(header_offset) as *mut GcBoxInner<T>;
Gc {
ptr: NonNull::new_unchecked(ptr),
_invariant: PhantomData,
}
}
}
}
impl<'gc, T: Unlock + ?Sized + 'gc> Gc<'gc, T> {
/// Shorthand for [`Gc::write`]`(mc, self).`[`unlock()`](Write::unlock).
#[inline]
pub fn unlock(self, mc: &Mutation<'gc>) -> &'gc T::Unlocked {
Gc::write(mc, self).unlock()
}
}
impl<'gc, T: ?Sized + 'gc> Gc<'gc, T> {
/// Obtains a long-lived reference to the contents of this `Gc`.
///
/// Unlike `AsRef` or `Deref`, the returned reference isn't bound to the `Gc` itself, and
/// will stay valid for the entirety of the current arena callback.
#[inline]
pub fn as_ref(self: Gc<'gc, T>) -> &'gc T {
// SAFETY: The returned reference cannot escape the current arena callback, as `&'gc T`
// never implements `Collect` (unless `'gc` is `'static`, which is impossible here), and
// so cannot be stored inside the GC root.
unsafe { &self.ptr.as_ref().value }
}
#[inline]
pub fn downgrade(this: Gc<'gc, T>) -> GcWeak<'gc, T> {
GcWeak { inner: this }
}
/// Triggers a write barrier on this `Gc`, allowing for safe mutation.
///
/// This triggers an unrestricted *backwards* write barrier on this pointer, meaning that it is
/// guaranteed that this pointer can safely adopt *any* arbitrary child pointers (until the next
/// time that collection is triggered).
///
/// It returns a reference to the inner `T` wrapped in a `Write` marker to allow for
/// unrestricted mutation on the held type or any of its directly held fields.
#[inline]
pub fn write(mc: &Mutation<'gc>, gc: Self) -> &'gc Write<T> {
unsafe {
mc.backward_barrier(Gc::erase(gc), None);
// SAFETY: the write barrier stays valid until the end of the current callback.
Write::assume(gc.as_ref())
}
}
/// Returns true if two `Gc`s point to the same allocation.
///
/// Similarly to `Rc::ptr_eq` and `Arc::ptr_eq`, this function ignores the metadata of `dyn`
/// pointers.
#[inline]
pub fn ptr_eq(this: Gc<'gc, T>, other: Gc<'gc, T>) -> bool {
// TODO: Equivalent to `core::ptr::addr_eq`:
// https://github.com/rust-lang/rust/issues/116324
Gc::as_ptr(this) as *const () == Gc::as_ptr(other) as *const ()
}
#[inline]
pub fn as_ptr(gc: Gc<'gc, T>) -> *const T {
unsafe {
let inner = gc.ptr.as_ptr();
core::ptr::addr_of!((*inner).value) as *const T
}
}
/// Returns true when a pointer is *dead* during finalization. This is equivalent to
/// `GcWeak::is_dead` for strong pointers.
///
/// Any strong pointer reachable from the root will never be dead, BUT there can be strong
/// pointers reachable only through other weak pointers that can be dead.
#[inline]
pub fn is_dead(_: &Finalization<'gc>, gc: Gc<'gc, T>) -> bool {
let inner = unsafe { gc.ptr.as_ref() };
matches!(inner.header.color(), GcColor::White | GcColor::WhiteWeak)
}
/// Manually marks a dead `Gc` pointer as reachable and keeps it alive.
///
/// Equivalent to `GcWeak::resurrect` for strong pointers. Manually marks this pointer and
/// all transitively held pointers as reachable, thus keeping them from being dropped this
/// collection cycle.
#[inline]
pub fn resurrect(fc: &Finalization<'gc>, gc: Gc<'gc, T>) {
unsafe {
fc.resurrect(GcBox::erase(gc.ptr));
}
}
}
impl<'gc, T: PartialEq + ?Sized + 'gc> PartialEq for Gc<'gc, T> {
fn eq(&self, other: &Self) -> bool {
(**self).eq(other)
}
fn ne(&self, other: &Self) -> bool {
(**self).ne(other)
}
}
impl<'gc, T: Eq + ?Sized + 'gc> Eq for Gc<'gc, T> {}
impl<'gc, T: PartialOrd + ?Sized + 'gc> PartialOrd for Gc<'gc, T> {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
(**self).partial_cmp(other)
}
fn le(&self, other: &Self) -> bool {
(**self).le(other)
}
fn lt(&self, other: &Self) -> bool {
(**self).lt(other)
}
fn ge(&self, other: &Self) -> bool {
(**self).ge(other)
}
fn gt(&self, other: &Self) -> bool {
(**self).gt(other)
}
}
impl<'gc, T: Ord + ?Sized + 'gc> Ord for Gc<'gc, T> {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
(**self).cmp(other)
}
}
impl<'gc, T: Hash + ?Sized + 'gc> Hash for Gc<'gc, T> {
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).hash(state)
}
}