Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/Tamschi/rhizome.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558use crate::UnwrapInfallible;use core::{ borrow::{Borrow, BorrowMut}, cell::UnsafeCell, hash::{Hash, Hasher}, marker::PhantomPinned, mem::MaybeUninit, pin::Pin, ptr,};use pinus::{prelude::*, sync::PressedPineMap};use tap::Pipe;use this_is_fine::Fine;
use tiptoe::{Arc, ExclusivePin, IntrusivelyCountable, ManagedClone, RefCounter, TipToe};
#[cfg(feature = "macros")]pub use crate::TypeKey;
/// Shorthand for `Pin<Arc<Node<T, K, V, C = TipToe>>>`.#[allow(clippy::module_name_repetitions)]pub type NodeHandle<T, K, V, C = TipToe> = Pin<Arc<Node<T, K, V, C>>>;
impl<T, K: Ord, V: ?Sized, C: RefCounter> PartialEq for Node<T, K, V, C> { fn eq(&self, other: &Self) -> bool { ptr::eq(self, other) }}
impl<T, K: Ord, V: ?Sized, C: RefCounter> Eq for Node<T, K, V, C> {}
impl<T, K: Ord, V: ?Sized, C: RefCounter> Hash for Node<T, K, V, C> { fn hash<H: Hasher>(&self, state: &mut H) { state.write_usize(self as *const _ as usize) }}
/// A reference-counted tagged inverse map tree node.////// Construct this indirectly via a [`NodeHandle`] constructor.#[repr(transparent)]pub struct Node<T, K: Ord, V: ?Sized, C: RefCounter = TipToe> { /// The entirety of this instance must be represented by an `UnsafeCell` /// in order to make [`Node::clone_handle`] sound under Strict Provenance. inner: UnsafeCell<NodeInner<T, K, V, C>>,}
unsafe impl<T, K: Ord, V: ?Sized, C: RefCounter> Sync for Node<T, K, V, C>where T: Send + Sync, K: Send + Sync, V: Send + Sync, C: Send + Sync,{}
#[pin_project::pin_project]struct NodeInner<T, K: Ord, V: ?Sized, C: RefCounter = TipToe> { /// This crate walks along the graph a whole lot and normally doesn't do much refcounting, /// so the offset version is likely a bit better here. /// /// This is unbenched though. Someone might want to check. parent: Option<NodeHandle<T, K, V, C>>, tag: T, local_scope: Pin<PressedPineMap<K, V>>, #[pin] ref_counter: C, // FIXME: Remove the extra `PhantomPinned` once `RefCounter` guarantees `!Unpin`. #[pin] pinned: PhantomPinned,}
impl<T, K: Ord, V: ?Sized, C: RefCounter> ManagedClone for Node<T, K, V, C>where T: ManagedClone, Pin<PressedPineMap<K, V>>: ManagedClone, V: Clone, C: ManagedClone,{ unsafe fn managed_clone(&self) -> Self { let this = unsafe { &*self.inner.get() };
// SAFETY: Everything is wrapped as before. Self { inner: NodeInner { parent: Option::managed_clone(&this.parent), tag: this.tag.managed_clone(), local_scope: this.local_scope.managed_clone(), ref_counter: this.ref_counter.managed_clone(), pinned: this.pinned.managed_clone(), } .into(), } }}
unsafe impl<T, K: Ord, V: ?Sized, C: RefCounter> IntrusivelyCountable for Node<T, K, V, C> { type RefCounter = C;
fn ref_counter(&self) -> &Self::RefCounter { unsafe { &*field_offset::offset_of!(NodeInner<T,K,V,C> => ref_counter) .apply_ptr(self.inner.get()) } }}
impl<T, K: Ord, V: ?Sized, C: RefCounter> Node<T, K, V, C> { /// Creates a new root-node with tag `tag`. #[must_use] pub fn new(tag: T) -> NodeHandle<T, K, V, C> where C: Default, { Self { inner: NodeInner { parent: None, tag, local_scope: PressedPineMap::new().pin(), ref_counter: C::default(), pinned: PhantomPinned, } .into(), } .pipe(Arc::pin) }
/// Creates a new root-node with tag `tag` that will store values (almost) contiguously /// until `capacity` (in bytes that are the size of a maximally aligned buffer!) are exceeded. #[must_use] pub fn with_capacity(tag: T, capacity_bytes: usize) -> NodeHandle<T, K, V, C> where C: Default, { Self { inner: NodeInner { parent: None, tag, local_scope: PressedPineMap::with_capacity(capacity_bytes).pin(), ref_counter: C::default(), pinned: PhantomPinned, } .into(), } .pipe(Arc::pin) }
/// Uses this node as parent of a new node tagged `tag`, /// without cloning the handle. #[must_use] pub fn handle_into_branch_for(parent: NodeHandle<T, K, V, C>, tag: T) -> NodeHandle<T, K, V, C> where C: Default, { Self { inner: NodeInner { parent: Some(parent), tag, local_scope: PressedPineMap::new().pin(), ref_counter: C::default(), pinned: PhantomPinned, } .into(), } .pipe(Arc::pin) }
/// Uses this node as parent of a new node tagged `tag`, /// without cloning the handle, /// pre-allocating at least `capacity_bytes` of maximally-aligned contiguous memory to store values. #[must_use] pub fn handle_into_branch_for_with_capacity( parent: NodeHandle<T, K, V, C>, tag: T, capacity_bytes: usize, ) -> NodeHandle<T, K, V, C> where C: Default, { Self { inner: NodeInner { parent: Some(parent), tag, local_scope: PressedPineMap::with_capacity(capacity_bytes).pin(), ref_counter: C::default(), pinned: PhantomPinned, } .into(), } .pipe(Arc::pin) }
/// Creates an additional handle for this [`Node`], incrementing the internal reference count. #[must_use] pub fn clone_handle(&self) -> NodeHandle<T, K, V, C> { Pin::clone(unsafe { Arc::borrow_pin_from_inner_ref(&self) }) }}
/// # Branchingimpl<T, K: Ord, V: ?Sized, C: RefCounter> Node<T, K, V, C> { /// [`Clone`]s this handle to use this node as parent of a new node tagged `tag`. #[must_use] pub fn branch_for(&self, tag: T) -> NodeHandle<T, K, V, C> where C: Default, { Self::handle_into_branch_for(self.clone_handle(), tag) }
/// [`Clone`]s this handle to use this node as parent of a new node tagged `tag`, /// pre-allocating at least `capacity_bytes` of maximally-aligned contiguous memory to store values. #[must_use] pub fn branch_for_with_capacity(&self, tag: T, capacity_bytes: usize) -> NodeHandle<T, K, V, C> where C: Default, { Self::handle_into_branch_for_with_capacity(self.clone_handle(), tag, capacity_bytes) }}
/// # Insertionsimpl<T, K: Ord, V: ?Sized, C: RefCounter> Node<T, K, V, C> { /// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn insert(&self, key: K, value: V) -> Fine<Pin<&V>, (K, V)> where V: Sized, { let this = unsafe { &*self.inner.get() }; this.local_scope.insert(key, value) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn emplace<W>(&self, key: K, value: W) -> Fine<Pin<&V>, (K, W)> where W: BorrowMut<V>, { let this = unsafe { &*self.inner.get() }; this.local_scope.emplace(key, value) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn emplace_with<W, F: for<'a> FnOnce(&K, &'a mut MaybeUninit<W>) -> &'a mut V>( &self, key: K, value_factory: F, ) -> Fine<Pin<&V>, (K, F)> { let this = unsafe { &*self.inner.get() }; this.local_scope.emplace_with_unpinned(key, value_factory) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn try_emplace_with< W, F: for<'a> FnOnce(&K, &'a mut MaybeUninit<W>) -> Result<&'a mut V, E>, E, >( &self, key: K, value_factory: F, ) -> Result<Fine<Pin<&V>, (K, F)>, E> { let this = unsafe { &*self.inner.get() }; this.local_scope .try_emplace_with_unpinned(key, value_factory) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn emplace_with_pinning< W, F: for<'a> FnOnce(&K, Pin<&'a mut MaybeUninit<W>>) -> Pin<&'a mut V>, >( &self, key: K, value_factory: F, ) -> Fine<Pin<&V>, (K, F)> { let this = unsafe { &*self.inner.get() }; this.local_scope.emplace_with(key, value_factory) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn try_emplace_with_pinning< W, F: for<'a> FnOnce(&K, Pin<&'a mut MaybeUninit<W>>) -> Result<Pin<&'a mut V>, E>, E, >( &self, key: K, value_factory: F, ) -> Result<Fine<Pin<&V>, (K, F)>, E> { let this = unsafe { &*self.inner.get() }; this.local_scope.try_emplace_with(key, value_factory) }
/// Retrieves a reference to this node's parent node, if available. #[must_use] pub fn parent(&self) -> Option<&Node<T, K, V, C>> { let this = unsafe { &*self.inner.get() }; this.parent.as_deref() }
/// Retrieves a reference to this node's root node, which may be itself. #[must_use] pub fn root(&self) -> &Node<T, K, V, C> { let mut this = self; while let Some(parent) = this.parent() { this = parent; } this }
/// Retrieves a reference to the neared node node tagged with `tag`. /// /// This may be the current node or any of its ancestors, but no siblings at any level. #[must_use] pub fn tagged<Q>(&self, tag: &Q) -> Option<&Node<T, K, V, C>> where T: Borrow<Q>, Q: PartialEq + ?Sized, { let mut this = self; loop { let this_ = unsafe { &*this.inner.get() }; if this_.tag.borrow() == tag { break Some(this); } this = this.parent()?; } }}
/// # Retrievalimpl<T, K: Ord, V: ?Sized, C: RefCounter> Node<T, K, V, C> { /// Extracts a value from this node only according to the given `key`. /// /// # Panics /// /// Iff this node is poisoned. #[must_use] pub fn get_local<Q>(&self, key: &Q) -> Option<Pin<&V>> where K: Borrow<Q>, Q: Ord + ?Sized, { let this = unsafe { &*self.inner.get() }; this.local_scope.get(key) }
/// Extracts a value from the node tree according to the given `key`. /// /// # Panics /// /// Iff a poisoned node is reached. #[allow(clippy::type_complexity)] #[must_use] pub fn get<Q>(&self, key: &Q) -> Option<(&Node<T, K, V, C>, Pin<&V>)> where K: Borrow<Q>, Q: Ord + ?Sized, { self.find(|node| node.get_local(key)) }
/// Extracts a value from the node tree according to the given `selector`. /// /// The selector is called once each for this node and its ancestors, in order of inverse age, until either: /// /// - It returns [`Some`]. /// - No further parent node is available. /// /// # Panics /// /// Not directly, but if a poisoned node is reached, then `selector` is likely to panic. #[allow(clippy::type_complexity)] #[must_use] pub fn find<S: for<'a> FnMut(&'a Node<T, K, V, C>) -> Option<Pin<&'a V>>>( &self, mut local_selector: S, ) -> Option<(&Node<T, K, V, C>, Pin<&V>)> { self.try_find(|node| Ok(local_selector(node))) .unwrap_infallible() }
/// Extracts a value from the node tree according to the given `selector`. /// /// The selector is called once each for this node and its ancestors, in order of inverse age, until either: /// /// - It fails. /// - It returns [`Some`]. /// - No further parent node is available. /// /// # Errors /// /// Iff the selector fails. /// /// # Panics /// /// Not directly, but if a poisoned node is reached, then `selector` is likely to panic. #[allow(clippy::type_complexity)] pub fn try_find<S: for<'a> FnMut(&'a Node<T, K, V, C>) -> Result<Option<Pin<&'a V>>, E>, E>( &self, mut local_selector: S, ) -> Result<Option<(&Node<T, K, V, C>, Pin<&V>)>, E> { let mut this = self; loop { if let Some(found) = local_selector(this)? { break Some((this, found)); } else if let Some(parent) = this.parent() { this = parent } else { break None; } } .pipe(Ok) }
//TODO: `search` and `try_search`, which should iterate using repeat `find` and/or `try_find` calls.
/// Borrows the current [`Node`] exclusively iff there is only one reference to it. /// /// This enables for example efficient batch insertions of values. pub fn as_mut(this: &mut NodeHandle<T, K, V, C>) -> Option<ExclusivePin<'_, Self>> { Arc::get_mut(this) }}
/// # Exclusive Bulk Insertions////// These functions can be batched without incurring locking overhead between them.////// Use [`Node::as_mut`] to acquire a suitable exclusive [`Node`] reference.impl<T, K: Ord, V: ?Sized, C: RefCounter> Node<T, K, V, C> { /// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. #[allow(clippy::missing_panics_doc)] //TODO: Validate the panics are indeed unreachable, then clean up potential panic sites. pub fn insert_mut(self: Pin<&mut Self>, key: K, value: V) -> Fine<Pin<&mut V>, (K, V)> where V: Sized, { let this = unsafe { Pin::new_unchecked(&mut *self.inner.get()) }; this.project().local_scope.insert_mut(key, value) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn emplace_mut<W>(self: Pin<&mut Self>, key: K, value: W) -> Fine<Pin<&mut V>, (K, W)> where W: BorrowMut<V>, { let this = unsafe { Pin::new_unchecked(&mut *self.inner.get()) }; this.project().local_scope.emplace_mut(key, value) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn emplace_with_mut<W, F: for<'a> FnOnce(&K, &'a mut MaybeUninit<W>) -> &'a mut V>( self: Pin<&mut Self>, key: K, value_factory: F, ) -> Fine<Pin<&mut V>, (K, F)> { let this = unsafe { Pin::new_unchecked(&mut *self.inner.get()) }; this.project() .local_scope .emplace_with_mut_unpinned(key, value_factory) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn try_emplace_with_mut< W, F: for<'a> FnOnce(&K, &'a mut MaybeUninit<W>) -> Result<&'a mut V, E>, E, >( self: Pin<&mut Self>, key: K, value_factory: F, ) -> Result<Fine<Pin<&mut V>, (K, F)>, E> { let this = unsafe { Pin::new_unchecked(&mut *self.inner.get()) }; this.project() .local_scope .try_emplace_with_mut_unpinned(key, value_factory) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn emplace_with_pinning_mut< W, F: for<'a> FnOnce(&K, Pin<&'a mut MaybeUninit<W>>) -> Pin<&'a mut V>, >( self: Pin<&mut Self>, key: K, value_factory: F, ) -> Fine<Pin<&mut V>, (K, F)> { let this = unsafe { Pin::new_unchecked(&mut *self.inner.get()) }; this.project() .local_scope .emplace_with_mut(key, value_factory) }
/// Stores `value` for `key` at the current node. /// /// # Errors /// /// Iff the local scope already contains a value for `key`. pub fn try_emplace_with_pinning_mut< W, F: for<'a> FnOnce(&K, Pin<&'a mut MaybeUninit<W>>) -> Result<Pin<&'a mut V>, E>, E, >( self: Pin<&mut Self>, key: K, value_factory: F, ) -> Result<Fine<Pin<&mut V>, (K, F)>, E> { let this = unsafe { Pin::new_unchecked(&mut *self.inner.get()) }; this.project() .local_scope .try_emplace_with_mut(key, value_factory) }}