children.rs

cdk-rsx/crates/cdk-rsx-store/src/children.rs

children.rs274 lines← SDK documentation
1use crate::*;2use std::{3    cell::{Cell, RefCell},4    collections::BTreeMap,5};67/// Closed owning-attachment group. Unlike NyxusData it is never mutably8/// projected from a module cell. Each field's API needs a real write Scope.9///10/// # Safety11/// Implementations must contain only closed attachment containers/groups,12/// expose no mutable owner storage, bind all fields to exactly this owner, and13/// drop every remaining attachment through the active frame. Use module_children!.14/// Safe code cannot bind a transient ownership container to a public identity:15/// ```compile_fail16/// use cdk_rsx_store::{Identity, ModuleChildren};17/// fn spoof<T: ModuleChildren>(children: &T, public_id: Identity) {18///     children.bind_owner(public_id).unwrap();19/// }20/// ```21/// Owning slots cannot hide inside ordinary mutable Data:22/// ```compile_fail23/// use cdk_rsx_store::{ChildSlot, ModuleMemory, NyxusData};24/// fn hidden_owner<M: ModuleMemory>() {25///     fn data<T: NyxusData>() {}26///     data::<ChildSlot<M>>();27/// }28/// ```29pub unsafe trait ModuleChildren: Default + 'static {30    /// # Safety31    /// Only the kernel may bind this group, in its allocated retained cell.32    /// The group may never subsequently move out through application code.33    unsafe fn bind_owner(&self, owner: Identity) -> Result<()>;34}35unsafe impl ModuleChildren for () {36    unsafe fn bind_owner(&self, _: Identity) -> Result<()> {37        Ok(())38    }39}4041fn bind(owner: &Cell<Identity>, identity: Identity) -> Result<()> {42    let saved = owner.get();43    if !saved.is_none() && saved != identity {44        return Err(Error::WrongOwner);45    }46    owner.set(identity);47    Ok(())48}49fn owner(owner: &Cell<Identity>, scope: &Scope<'_>) -> Result<Identity> {50    let identity = owner.get();51    if identity.is_none() {52        return Err(Error::UnboundChildren);53    }54    scope.cx.store.slot(identity)?;55    Ok(identity)56}5758/// One owning child field. All storage is private and no mutable projection is59/// exposed. It deliberately does not implement NyxusData, Clone or Copy.60#[repr(C)]61pub struct ChildSlot<M: ModuleMemory> {62    owner: Cell<Identity>,63    child: RefCell<Identity>,64    marker: PhantomData<fn() -> M>,65}66impl<M: ModuleMemory> Default for ChildSlot<M> {67    fn default() -> Self {68        Self {69            owner: Cell::new(Identity::NONE),70            child: RefCell::new(Identity::NONE),71            marker: PhantomData,72        }73    }74}75// SAFETY: ChildSlot's first type argument is precisely its owning child type.76unsafe impl<M: ModuleMemory> cdk_rsx_memory_abi::CatalogSlot for ChildSlot<M> {}77unsafe impl<M: ModuleMemory> ModuleChildren for ChildSlot<M> {78    unsafe fn bind_owner(&self, identity: Identity) -> Result<()> {79        bind(&self.owner, identity)80    }81}82impl<M: ModuleMemory> ChildSlot<M> {83    pub fn reference(&self, access: &impl Access) -> Result<Option<ModuleRef<M>>> {84        let cx = scope::context(access);85        let id = *self.child.try_borrow().map_err(|_| Error::Borrowed)?;86        if id.is_none() {87            Ok(None)88        } else {89            cx.store.bind(id).map(Some)90        }91    }92    pub fn attach<'s>(93        &self,94        scope: &Scope<'s>,95        child: Detached<'s, M>,96    ) -> Result<Option<Detached<'s, M>>> {97        let parent = owner(&self.owner, scope)?;98        let mut stored = self.child.try_borrow_mut().map_err(|_| Error::Borrowed)?;99        // Ancestor/capability checks happen before detaching the old child.100        let id = scope.cx.attach(parent, child)?;101        let old = std::mem::replace(&mut *stored, id);102        if old.is_none() {103            Ok(None)104        } else {105            scope.cx.detach::<M>(parent, old).map(Some)106        }107    }108    pub fn take<'s>(&self, scope: &Scope<'s>) -> Result<Option<Detached<'s, M>>> {109        let parent = owner(&self.owner, scope)?;110        let mut stored = self.child.try_borrow_mut().map_err(|_| Error::Borrowed)?;111        let id = *stored;112        if id.is_none() {113            return Ok(None);114        }115        let child = scope.cx.detach::<M>(parent, id)?;116        *stored = Identity::NONE;117        Ok(Some(child))118    }119    pub fn clear(&self, scope: &Scope<'_>) -> Result<()> {120        self.take(scope).map(|_| ())121    }122}123impl<M: ModuleMemory> Drop for ChildSlot<M> {124    fn drop(&mut self) {125        let id = std::mem::replace(self.child.get_mut(), Identity::NONE);126        if !id.is_none() {127            scope::retiring::<M>(self.owner.get(), id);128        }129    }130}131132/// An owning child map. Native tree algorithms stay direct; only attaching or133/// detaching a module touches its parent link and the frame's orphan list.134#[repr(C)]135pub struct ChildMap<K: NyxusData + Ord, M: ModuleMemory> {136    owner: Cell<Identity>,137    entries: RefCell<BTreeMap<K, Identity, Nyxus>>,138    marker: PhantomData<fn() -> M>,139}140impl<K: NyxusData + Ord, M: ModuleMemory> Default for ChildMap<K, M> {141    fn default() -> Self {142        Self {143            owner: Cell::new(Identity::NONE),144            entries: RefCell::new(BTreeMap::new_in(Nyxus)),145            marker: PhantomData,146        }147    }148}149// SAFETY: ChildMap's second type argument is precisely its owning child type.150unsafe impl<K: NyxusData + Ord, M: ModuleMemory> cdk_rsx_memory_abi::CatalogMap for ChildMap<K, M> {}151unsafe impl<K: NyxusData + Ord, M: ModuleMemory> ModuleChildren for ChildMap<K, M> {152    unsafe fn bind_owner(&self, identity: Identity) -> Result<()> {153        bind(&self.owner, identity)154    }155}156impl<K: NyxusData + Ord, M: ModuleMemory> ChildMap<K, M> {157    pub fn len(&self) -> usize {158        self.entries.borrow().len()159    }160    pub fn is_empty(&self) -> bool {161        self.len() == 0162    }163    pub fn reference<Q: ?Sized + Ord>(164        &self,165        access: &impl Access,166        key: &Q,167    ) -> Result<Option<ModuleRef<M>>>168    where169        K: std::borrow::Borrow<Q>,170    {171        let cx = scope::context(access);172        self.entries173            .try_borrow()174            .map_err(|_| Error::Borrowed)?175            .get(key)176            .copied()177            .map(|id| cx.store.bind(id))178            .transpose()179    }180    /// Snapshot ordered keys without exposing or retaining child attachments.181    /// The returned Vec uses transient Global storage; each key follows its182    /// ordinary Clone implementation. No module identity or owner loan escapes.183    pub fn keys(&self) -> Result<std::vec::Vec<K>>184    where185        K: Clone,186    {187        Ok(self188            .entries189            .try_borrow()190            .map_err(|_| Error::Borrowed)?191            .keys()192            .cloned()193            .collect())194    }195    pub fn attach<'s>(196        &self,197        scope: &Scope<'s>,198        key: K,199        child: Detached<'s, M>,200    ) -> Result<Option<Detached<'s, M>>> {201        let parent = owner(&self.owner, scope)?;202        let mut entries = self.entries.try_borrow_mut().map_err(|_| Error::Borrowed)?;203        let id = scope.cx.attach(parent, child)?;204        let old = entries.insert(key, id);205        old.map(|old| scope.cx.detach::<M>(parent, old)).transpose()206    }207    pub fn take<'s, Q: ?Sized + Ord>(208        &self,209        scope: &Scope<'s>,210        key: &Q,211    ) -> Result<Option<Detached<'s, M>>>212    where213        K: std::borrow::Borrow<Q>,214    {215        let parent = owner(&self.owner, scope)?;216        let mut entries = self.entries.try_borrow_mut().map_err(|_| Error::Borrowed)?;217        let Some(id) = entries.get(key).copied() else {218            return Ok(None);219        };220        let child = scope.cx.detach::<M>(parent, id)?;221        entries.remove(key);222        Ok(Some(child))223    }224    pub fn take_first<'s>(&self, scope: &Scope<'s>) -> Result<Option<(K, Detached<'s, M>)>> {225        let parent = owner(&self.owner, scope)?;226        let mut entries = self.entries.try_borrow_mut().map_err(|_| Error::Borrowed)?;227        let Some((key, id)) = entries.pop_first() else {228            return Ok(None);229        };230        let child = scope.cx.detach::<M>(parent, id)?;231        Ok(Some((key, child)))232    }233    /// Adopt an unchanged native child index during an owner-local conversion.234    /// Both containers already belong to the same stable module identity.235    pub fn adopt_from(&self, scope: &Scope<'_>, source: &Self) -> Result<()> {236        let own = owner(&self.owner, scope)?;237        if own != owner(&source.owner, scope)? || std::ptr::eq(self, source) {238            return Err(Error::WrongOwner);239        }240        let mut target = self.entries.try_borrow_mut().map_err(|_| Error::Borrowed)?;241        if !target.is_empty() {242            return Err(Error::WrongOwner);243        }244        let mut old = source245            .entries246            .try_borrow_mut()247            .map_err(|_| Error::Borrowed)?;248        std::mem::swap(&mut *target, &mut *old);249        Ok(())250    }251    pub fn clear(&self, scope: &Scope<'_>, limit: usize) -> Result<usize> {252        let parent = owner(&self.owner, scope)?;253        let mut count = 0;254        while count < limit {255            let item = self256                .entries257                .try_borrow_mut()258                .map_err(|_| Error::Borrowed)?259                .pop_first();260            let Some((_, id)) = item else { break };261            scope.cx.detach::<M>(parent, id)?;262            count += 1;263        }264        Ok(count)265    }266}267impl<K: NyxusData + Ord, M: ModuleMemory> Drop for ChildMap<K, M> {268    fn drop(&mut self) {269        let entries = std::mem::replace(self.entries.get_mut(), BTreeMap::new_in(Nyxus));270        for (_, id) in entries {271            scope::retiring::<M>(self.owner.get(), id);272        }273    }274}