Skip to content

Commit

Permalink
Factor out from_gcbox helper
Browse files Browse the repository at this point in the history
Signed-off-by: Anders Kaseorg <[email protected]>
  • Loading branch information
andersk committed Dec 22, 2022
1 parent 189a876 commit 5d6a7a1
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions gc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,30 @@ impl<T: Trace> Gc<T> {
/// assert_eq!(*five, 5);
/// ```
pub fn new(value: T) -> Self {
assert!(mem::align_of::<GcBox<T>>() > 1);
unsafe { Gc::from_gcbox(GcBox::new(value)) }
}
}

unsafe {
// Allocate the memory for the object
let ptr = GcBox::new(value);
impl<T: Trace + ?Sized> Gc<T> {
/// Constructs a `Gc` that points to a new `GcBox`.
///
/// # Safety
///
/// `ptr` must point to a valid `GcBox` on the thread-local
/// `GcBox` chain.
#[inline]
unsafe fn from_gcbox(ptr: NonNull<GcBox<T>>) -> Gc<T> {
assert!(mem::align_of_val::<GcBox<T>>(ptr.as_ref()) > 1);

// When we create a Gc<T>, all pointers which have been moved to the
// heap no longer need to be rooted, so we unroot them.
ptr.as_ref().value().unroot();
let gc = Gc {
ptr_root: Cell::new(ptr),
marker: PhantomData,
};
gc.set_root();
gc
}
// When we create a Gc<T>, all pointers which have been moved to the
// heap no longer need to be rooted, so we unroot them.
ptr.as_ref().value().unroot();
let gc = Gc {
ptr_root: Cell::new(ptr),
marker: PhantomData,
};
gc.set_root();
gc
}
}

Expand Down

0 comments on commit 5d6a7a1

Please sign in to comment.