use 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>>`. #[allow(clippy::module_name_repetitions)] pub type NodeHandle = Pin>>; impl PartialEq for Node { fn eq(&self, other: &Self) -> bool { ptr::eq(self, other) } } impl Eq for Node {} impl Hash for Node { fn hash(&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 { /// The entirety of this instance must be represented by an `UnsafeCell` /// in order to make [`Node::clone_handle`] sound under Strict Provenance. inner: UnsafeCell>, } unsafe impl Sync for Node where T: Send + Sync, K: Send + Sync, V: Send + Sync, C: Send + Sync, { } #[pin_project::pin_project] struct NodeInner { /// 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>, tag: T, local_scope: Pin>, #[pin] ref_counter: C, // FIXME: Remove the extra `PhantomPinned` once `RefCounter` guarantees `!Unpin`. #[pin] pinned: PhantomPinned, } impl ManagedClone for Node where T: ManagedClone, Pin>: 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 IntrusivelyCountable for Node { type RefCounter = C; fn ref_counter(&self) -> &Self::RefCounter { unsafe { &*field_offset::offset_of!(NodeInner => ref_counter) .apply_ptr(self.inner.get()) } } } impl Node { /// Creates a new root-node with tag `tag`. #[must_use] pub fn new(tag: T) -> NodeHandle 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 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, tag: T) -> NodeHandle 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, tag: T, capacity_bytes: usize, ) -> NodeHandle 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 { Pin::clone(unsafe { Arc::borrow_pin_from_inner_ref(&self) }) } } /// # Branching impl Node { /// [`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 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 where C: Default, { Self::handle_into_branch_for_with_capacity(self.clone_handle(), tag, capacity_bytes) } } /// # Insertions impl Node { /// 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, (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(&self, key: K, value: W) -> Fine, (K, W)> where W: BorrowMut, { 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 FnOnce(&K, &'a mut MaybeUninit) -> &'a mut V>( &self, key: K, value_factory: F, ) -> Fine, (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) -> Result<&'a mut V, E>, E, >( &self, key: K, value_factory: F, ) -> Result, (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>) -> Pin<&'a mut V>, >( &self, key: K, value_factory: F, ) -> Fine, (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>) -> Result, E>, E, >( &self, key: K, value_factory: F, ) -> Result, (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> { 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 { 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(&self, tag: &Q) -> Option<&Node> where T: Borrow, 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()?; } } } /// # Retrieval impl Node { /// Extracts a value from this node only according to the given `key`. /// /// # Panics /// /// Iff this node is poisoned. #[must_use] pub fn get_local(&self, key: &Q) -> Option> where K: Borrow, 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(&self, key: &Q) -> Option<(&Node, Pin<&V>)> where K: Borrow, 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 FnMut(&'a Node) -> Option>>( &self, mut local_selector: S, ) -> Option<(&Node, 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 FnMut(&'a Node) -> Result>, E>, E>( &self, mut local_selector: S, ) -> Result, 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) -> Option> { 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 Node { /// 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, (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(self: Pin<&mut Self>, key: K, value: W) -> Fine, (K, W)> where W: BorrowMut, { 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 FnOnce(&K, &'a mut MaybeUninit) -> &'a mut V>( self: Pin<&mut Self>, key: K, value_factory: F, ) -> Fine, (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) -> Result<&'a mut V, E>, E, >( self: Pin<&mut Self>, key: K, value_factory: F, ) -> Result, (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>) -> Pin<&'a mut V>, >( self: Pin<&mut Self>, key: K, value_factory: F, ) -> Fine, (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>) -> Result, E>, E, >( self: Pin<&mut Self>, key: K, value_factory: F, ) -> Result, (K, F)>, E> { let this = unsafe { Pin::new_unchecked(&mut *self.inner.get()) }; this.project() .local_scope .try_emplace_with_mut(key, value_factory) } }