Compare commits

..
6 changed files with 115 additions and 55 deletions

No files matched your search

+76 -35
View File
@@ -1,3 +1,4 @@
use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::marker::PhantomData;
@@ -26,11 +27,11 @@ pub struct Arena {
/// a park costs one pointer in the arena and owns its content outside it.
retained_heap: AtomicUsize,
/// Where [`Arena::move_park`] sent each moved park, as its offset here to
/// the header's address in the receiving arena and the moved size, so a
/// payload two records share is moved once and a mistyped sharer is
/// the header's address in the receiving arena and the moved type's key, so
/// a payload two records share is moved once and a mistyped sharer is
/// refused. Cleared by [`Arena::reset`], so a forwarding holds for one
/// generation.
forwarded: Mutex<HashMap<usize, (usize, usize)>>,
forwarded: Mutex<HashMap<usize, (usize, TypeId)>>,
}
impl std::fmt::Debug for Arena {
@@ -41,9 +42,9 @@ impl std::fmt::Debug for Arena {
struct DropEntry {
offset: usize,
/// The parked payload's own size, so [`Arena::move_park`] refuses a
/// reference into a park of another type that shares the offset.
size: usize,
/// The parked payload's static-type key, `None` where the park was
/// allocated without one and so never moves.
type_of: Option<TypeId>,
drop_fn: unsafe fn(*mut u8),
/// The park glue's estimate of the heap this payload owns, 0 where the
/// glue cannot measure it, so the counter is a lower bound.
@@ -214,6 +215,23 @@ impl Arena {
/// [`Arena::alloc`] with the park glue's estimate of the heap `value` owns,
/// which the region's own occupancy cannot see.
pub fn alloc_sized<T: Send + Sync>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, None)
}
/// [`Arena::alloc_sized`] stamping the park's static-type key, which is what
/// [`Arena::move_park`] matches on, so only a park allocated here can move.
pub fn alloc_sized_keyed<T: Send + Sync + dyn_any::StaticTypeSized>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, Some(TypeId::of::<T::Static>()))
}
/// [`Arena::alloc_sized_keyed`] for park glue already holding the element's
/// static form, which projects the key from the element type instead of
/// from the value's own. Crate-private: a wrong key mistypes a move.
pub(crate) fn alloc_sized_as<T: Send + Sync>(&self, value: T, retained: usize, type_of: TypeId) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, Some(type_of))
}
fn alloc_stamped<T: Send + Sync>(&self, value: T, retained: usize, type_of: Option<TypeId>) -> Option<(&T, ArenaWeak<T>)> {
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
@@ -225,7 +243,7 @@ impl Arena {
unsafe fn glue<T>(p: *mut u8) {
unsafe { p.cast::<T>().drop_in_place() }
}
self.drops.lock().unwrap().push(DropEntry { offset, size: size_of::<T>(), drop_fn: glue::<T>, retained });
self.drops.lock().unwrap().push(DropEntry { offset, type_of, drop_fn: glue::<T>, retained });
self.retained_heap.fetch_add(retained, Ordering::Relaxed);
}
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
@@ -250,32 +268,40 @@ impl Arena {
/// have credited it, and this arena is debited what its own park recorded,
/// so neither counter reads worse than it did before the move.
///
/// `None` where `src` is not this arena's park of `T`'s own size, where
/// `T` is zero-sized (whose parks share an offset and so cannot be told
/// apart), or where `dst` refused the header.
/// The move republishes the payload at `T::Static`, which is the key both
/// [`Arena::alloc_sized_keyed`] and this stamp, so a park and its move
/// project the type exactly once each and agree by construction.
///
/// `None` where `src` is not this arena's park keyed to `T::Static`, where
/// the type is zero-sized (whose parks share an offset and so cannot be
/// told apart), or where `dst` refused the header.
///
/// # Safety
/// `src` must address a live `T`, and a park of this arena at that address
/// and size must be the `T` itself, not another type's park the address
/// coincides with. `T` must own all of its content: the moved header may
/// reference no storage of this arena.
pub unsafe fn move_park<T: Send + Sync>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T> {
(size_of::<T>() != 0).then_some(())?;
/// `src` must address a live `T`, and `T` must own all of its content: the
/// moved header may reference no storage of this arena, which is also what
/// lets the payload be republished at `T::Static`. The key settles the
/// type, so the caller owes no size or identity argument beyond those two.
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T::Static>
where
T::Static: Send + Sync,
{
(size_of::<T::Static>() != 0).then_some(())?;
let offset = (src as usize).checked_sub(self.base() as usize)?;
(offset < self.buf.len()).then_some(())?;
let type_of = TypeId::of::<T::Static>();
let mut forwarded = self.forwarded.lock().unwrap();
if let Some(&(moved, size)) = forwarded.get(&offset) {
(size == size_of::<T>()).then_some(())?;
return Some(moved as *const T);
if let Some(&(moved, moved_type)) = forwarded.get(&offset) {
(moved_type == type_of).then_some(())?;
return Some(moved as *const T::Static);
}
let mut entries = self.drops.lock().unwrap();
let entry = entry_at(&entries, offset)?;
(entries[entry].size == size_of::<T>()).then_some(())?;
let slot = dst.alloc_scratch::<T>(1)?;
let target = slot.as_mut_ptr().cast::<T>();
(entries[entry].type_of == Some(type_of)).then_some(())?;
let slot = dst.alloc_scratch::<T::Static>(1)?;
let target = slot.as_mut_ptr().cast::<T::Static>();
// SAFETY: the caller's contract on `src`, into a freshly reserved,
// aligned, unaliased slot of the same type.
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T>(), target, 1) };
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T::Static>(), target, 1) };
let parked = std::mem::replace(&mut entries[entry].retained, 0);
entries[entry].drop_fn = inert;
drop(entries);
@@ -284,13 +310,13 @@ impl Arena {
}
dst.drops.lock().unwrap().push(DropEntry {
offset: target as usize - dst.base() as usize,
size: size_of::<T>(),
drop_fn: glue::<T>,
type_of: Some(type_of),
drop_fn: glue::<T::Static>,
retained,
});
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
forwarded.insert(offset, (target as usize, size_of::<T>()));
forwarded.insert(offset, (target as usize, type_of));
Some(target.cast_const())
}
@@ -607,7 +633,7 @@ mod tests {
let owned = String::from("moved, never cloned");
let length = owned.len();
let heap = owned.as_ptr();
let (parked, _) = transient.alloc_sized(owned, length).unwrap();
let (parked, _) = transient.alloc_sized_keyed(owned, length).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
let moved = unsafe { transient.move_park::<String>(src, &persistent, length) }.unwrap();
@@ -627,6 +653,9 @@ mod tests {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Probe {
type Static = Probe;
}
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
@@ -636,7 +665,7 @@ mod tests {
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized(Probe(String::from("shared by two records")), 21).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
let first = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
let second = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
@@ -652,18 +681,27 @@ mod tests {
#[test]
fn a_move_refuses_a_mistyped_park_and_its_forwarding() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Owner {
_first: String,
_tail: u64,
struct Owner(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Owner {
type Static = Owner;
}
/// Owner's layout exactly, so only the type key tells the two apart.
struct Twin(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Twin {
type Static = Twin;
}
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc(Owner { _first: String::from("a first member"), _tail: 0 }).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Owner(String::from("a keyed park")), 0).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "a park of another size is refused");
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "a park of another type of the same size is refused");
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
let (unkeyed, _) = transient.alloc(Owner(String::from("an unkeyed park"))).unwrap();
let src = std::ptr::from_ref(unkeyed).cast::<u8>();
assert!(unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.is_none(), "a park allocated without a key never moves");
transient.reset();
persistent.reset();
@@ -674,6 +712,9 @@ mod tests {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Probe {
type Static = Probe;
}
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
@@ -683,7 +724,7 @@ mod tests {
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized(Probe(String::from("first generation")), 16).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("first generation")), 16).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
unsafe { transient.move_park::<Probe>(src, &persistent, 16) }.unwrap();
assert_eq!(transient.forwarded.lock().unwrap().len(), 1, "the move tombstoned the entry it left");
+29 -12
View File
@@ -1313,7 +1313,7 @@ pub unsafe fn write_field<T>(dst: *mut u8, offset: usize, value: T) {
/// `dst` must be the claimed frame (or inline scratch when `frame_bytes` is
/// 0) of a record whose element is `T` and whose frame size is `frame_bytes`,
/// with every carried field already written.
pub(crate) unsafe fn lift_poll_into<'e, T: Send + Sync>(poll: GPoll<T>, dst: *mut u8, frame_bytes: usize, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
pub(crate) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::StaticTypeSized>(poll: GPoll<T>, dst: *mut u8, frame_bytes: usize, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
let build = |element: T| {
let written = unsafe { write_element(dst, element, arena) };
written.map(|()| match frame_bytes {
@@ -1459,7 +1459,8 @@ where
}
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
let value = value.downcast_ref::<T::Static>().expect("an element replays at its own type");
unsafe { write_element_sized(dst, value.clone(), arena, retained) }
// SAFETY: the caller's contract, keyed as this element's own parks are.
unsafe { write_element_keyed(dst, value.clone(), arena, retained, std::any::TypeId::of::<T::Static>()) }
}
/// Declines for a type carrying deep glue, whose value may hold interiors
/// the evaluation's arena owns and which a moved header may not reference.
@@ -1476,7 +1477,7 @@ where
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
// SAFETY: as above, and the decline above establishes that the payload
// owns all of its content.
unsafe { promotion.move_park::<T::Static>(parked, retained) }.map(<*const T::Static>::cast)
unsafe { promotion.move_park::<T>(parked, retained) }.map(<*const T::Static>::cast)
}
let (size, align) = element_dims::<T>();
ElementWrite {
@@ -1563,7 +1564,7 @@ pub unsafe fn read_element<T: Clone>(rec: Rec<'_>) -> T {
/// # Safety
/// `dst` must be fresh element storage of a record whose element is `T`.
/// `None` reports arena exhaustion for a parked element.
pub unsafe fn write_element<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena) -> Option<()> {
pub unsafe fn write_element<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena) -> Option<()> {
unsafe { write_element_sized(dst, value, arena, 0) }
}
@@ -1571,10 +1572,21 @@ pub unsafe fn write_element<T: Send + Sync>(dst: *mut u8, value: T, arena: &crat
///
/// # Safety
/// As [`write_element`].
pub unsafe fn write_element_sized<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize) -> Option<()> {
pub unsafe fn write_element_sized<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize) -> Option<()> {
// SAFETY: the caller's contract; `T::Static` is the element type's own key.
unsafe { write_element_keyed(dst, value, arena, retained, std::any::TypeId::of::<T::Static>()) }
}
/// [`write_element_sized`] for replay glue already holding the element's
/// static form, whose key the element type it replays into supplies.
///
/// # Safety
/// As [`write_element`], and `type_of` must be that element type's key, since
/// a park carrying it is what [`Promotion::move_park`] moves at.
pub(crate) unsafe fn write_element_keyed<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize, type_of: std::any::TypeId) -> Option<()> {
match element_parked::<T>() {
true => {
let (parked, _) = arena.alloc_sized(value, retained)?;
let (parked, _) = arena.alloc_sized_as(value, retained, type_of)?;
unsafe { dst.cast::<&T>().write(parked) };
Some(())
}
@@ -1855,8 +1867,9 @@ impl<'a> Promotion<'a> {
/// Moves a transient payload's header into the persistent region instead of
/// cloning the heap it owns: the heap travels with the drop obligation and
/// is freed at the persistent flush, never at the transient reset. `None`
/// where the header is not the transient arena's own park of `T`'s size or
/// the region refused it, which leaves the caller its clone path.
/// where the header is not the transient arena's own park keyed to `T`'s
/// static type or the region refused it, which leaves the caller its clone
/// path.
///
/// The forwarding is the evaluation's, so a payload two records share moves
/// once and both reach the one persistent header. The source header stays
@@ -1864,10 +1877,14 @@ impl<'a> Promotion<'a> {
/// the move keeps sound: no read of it may outlive the persistent flush.
///
/// # Safety
/// `parked` must address a live `T`, and a transient park at that address
/// and size must be the `T` itself. `T` must own all of its content, a
/// persistent header being allowed to reference no transient storage.
pub unsafe fn move_park<T: Send + Sync>(&self, parked: *const u8, retained: usize) -> Option<*const T> {
/// `parked` must address a live `T`, and `T` must own all of its content, a
/// persistent header being allowed to reference no transient storage, which
/// is also what lets it be republished at `T::Static`. The park's key
/// settles the type, so the caller owes no identity argument.
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, parked: *const u8, retained: usize) -> Option<*const T::Static>
where
T::Static: Send + Sync,
{
// SAFETY: the caller's contract, forwarded to the parking arena.
unsafe { self.transient.move_park::<T>(parked, self.persistent, retained) }
}
@@ -1842,7 +1842,7 @@ mod run_tests {
};
// SAFETY: the list serves only while `persistent` is live, and the
// promote under test replaces every borrow it carries.
let (paint, _) = transient.alloc(unsafe { core_types::record::erase_static(published) }).unwrap();
let (paint, _) = transient.alloc_sized_keyed(unsafe { core_types::record::erase_static(published) }, 0).unwrap();
let occupied = persistent.occupancy();
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
@@ -1866,7 +1866,7 @@ mod run_tests {
let Some(Graphic::Vector(vector)) = paint.element(0) else { panic!("the paint carries a vector") };
vector.point_domain.positions().as_ptr()
};
let (paint, _) = transient.alloc(paint).unwrap();
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
let (layout, span, _frames) = promote_paint_field(Some(paint), 2, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
+1 -1
View File
@@ -214,7 +214,7 @@ where
};
let park_paint = |paint: Option<List<Graphic<'static>>>| -> Result<Option<&'e List<Graphic<'static>>>, Interrupt> {
match paint {
Some(paint) => Ok(Some(arena.alloc(paint).ok_or_else(exhausted)?.0)),
Some(paint) => Ok(Some(arena.alloc_sized_keyed(paint, 0).ok_or_else(exhausted)?.0)),
None => Ok(None),
}
};
+2 -2
View File
@@ -69,7 +69,7 @@ fn boolean_core<'e>(
};
let park_paint = |paint: Option<List<Graphic<'static>>>| -> Result<Option<&'e List<Graphic>>, core_types::gpoll::Interrupt> {
match paint {
Some(list) => Ok(Some(arena.alloc(list).ok_or_else(exhausted)?.0)),
Some(list) => Ok(Some(arena.alloc_sized_keyed(list, 0).ok_or_else(exhausted)?.0)),
None => Ok(None),
}
};
@@ -82,7 +82,7 @@ fn boolean_core<'e>(
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
// Snapshot the input layers so the renderer can recurse into them for
// editor click-target preservation.
let merged_layers = arena.alloc(snapshot).ok_or_else(exhausted)?.0;
let merged_layers = arena.alloc_sized_keyed(snapshot, 0).ok_or_else(exhausted)?.0;
Ok((
element,
+5 -3
View File
@@ -276,8 +276,10 @@ fn assign_colors_graphic_extent(
pub use _assign_colors_graphic_mod::assign_colors_graphic_entries;
/// Keyed, so a group-free paint's promote moves this header rather than
/// cloning the content it owns.
fn park_paint<'e>(arena: &'e core_types::arena::Arena, paint: List<Graphic<'static>>) -> Result<&'e List<Graphic<'static>>, Interrupt> {
let (parked, _) = arena.alloc(paint).ok_or(GraphError {
let (parked, _) = arena.alloc_sized_keyed(paint, 0).ok_or(GraphError {
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
trace: Vec::new(),
})?;
@@ -1555,7 +1557,7 @@ fn emit_legacy_lane<'e>(
let merged_layers = output
.attribute::<Option<List<Graphic>>>(ATTR_EDITOR_MERGED_LAYERS, lane)
.and_then(|layers| layers.as_ref())
.map(|layers| arena.alloc(layers.clone()).ok_or_else(exhausted).map(|(parked, _)| parked))
.map(|layers| arena.alloc_sized_keyed(layers.clone(), 0).ok_or_else(exhausted).map(|(parked, _)| parked))
.transpose()?;
Ok((
@@ -1884,7 +1886,7 @@ fn flatten_path_core<'e>(
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
// Snapshot the input layers so the renderer can recurse into them for
// editor click-target preservation, as the boolean operation does.
let merged_layers = arena.alloc(snapshot).ok_or_else(exhausted)?.0;
let merged_layers = arena.alloc_sized_keyed(snapshot, 0).ok_or_else(exhausted)?.0;
Ok((output, Attr(DAffine2::IDENTITY), Attr(fill), Attr(stroke), Attr(layer_path.as_slice()), Attr(Some(merged_layers))))
}