indexed.rs

cdk-rsx/crates/cdk-rsx-collections-minima/src/indexed.rs

indexed.rs427 lines← SDK documentation
1//! Fixed-width values indexed directly into aligned nodes.23const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("indexed.rs");45use crate::{BLOCK_BYTES, Collection, Error, Fixed, NODE_BYTES, Result, Storage, Workspace};6use core::{marker::PhantomData, ops::Range};78/// A packed stable vector whose descriptor belongs in its owner's retained Data.9///10/// Each aligned 4 KiB node stores `floor(4096 / T::WIDTH)` values. Values never11/// straddle nodes. The retained length supplies occupancy; stable nodes contain12/// no record lengths, tags, or header. Whole unused trailing 64 KiB blocks are13/// returned after pop. Ordinary Drop retires the collection through its rooted14/// allocator authority.15///16/// Operations borrow the caller's reusable workspace, which can serve other17/// collections sequentially. No borrowed stable value escapes an operation.18/// `T::CONTRACT` and this collection's implementation belong in root admission.19///20/// ```21/// use cdk_rsx_collections_minima::{Arena, FixedVec, Workspace};22/// use cdk_rsx_platform::memory::VecMemory;23/// let mut arena = Arena::format(VecMemory::new()).unwrap();24/// let mut workspace_buffer = cdk_rsx_engine_minima::NodeBuffer::new();25/// let mut workspace = workspace_buffer.workspace();26/// let mut values = FixedVec::<u64>::new(&mut arena).unwrap();27/// values.push(&mut arena, &71, &mut workspace).unwrap();28/// assert_eq!(values.get(&arena, 0, &mut workspace).unwrap(), Some(71));29/// assert_eq!(values.pop(&mut arena, &mut workspace).unwrap(), Some(71));30/// assert_eq!(values.block_count(), 0);31/// ```32///33/// Zero-width records reject during compilation, rather than an operation:34/// ```compile_fail35/// use cdk_rsx_collections_minima::{Arena, FixedVec};36/// use cdk_rsx_platform::memory::VecMemory;37/// let mut storage = Arena::format(VecMemory::new()).unwrap();38/// let _ = FixedVec::<()>::new(&mut storage);39/// ```40#[repr(C)]41pub struct FixedVec<T: Fixed> {42    collection: Collection,43    len: u64,44    value: PhantomData<T>,45}4647// SAFETY: only the retained Collection directory and scalar length are owned.48// PhantomData describes the encoded contract; no decoded T is retained here.49unsafe impl<T: Fixed> cdk_rsx_engine_nyxus::NyxusData for FixedVec<T> {50    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;51}5253impl<T: Fixed> FixedVec<T> {54    /// Complete fixed-value and collection interpretation contract.55    pub const CONTRACT: [u8; 32] = crate::contract(56        "minima-fixed-vec-v1",57        &[],58        &[crate::MINIMA_POLICY, SOURCE_POLICY, T::CONTRACT],59    );6061    /// Source-known layout checks execute when a concrete collection is used.62    pub const VALUES_PER_NODE: u64 = {63        assert!(64            T::WIDTH > 0,65            "Minima FixedVec values must have nonzero width"66        );67        assert!(68            T::WIDTH <= NODE_BYTES,69            "Minima FixedVec value exceeds a node"70        );71        (NODE_BYTES / T::WIDTH) as u6472    };7374    /// Construct an empty owner without claiming a stable payload block.75    pub fn new(storage: &mut dyn Storage) -> Result<Self> {76        let _ = Self::VALUES_PER_NODE;77        Ok(Self {78            collection: Collection::new(storage)?,79            len: 0,80            value: PhantomData,81        })82    }8384    pub fn len(&self) -> u64 {85        self.len86    }8788    pub fn is_empty(&self) -> bool {89        self.len == 090    }9192    pub fn block_count(&self) -> usize {93        self.collection.block_count()94    }9596    /// Stable payload capacity, including node tails and unused block nodes.97    pub fn allocated_bytes(&self) -> u64 {98        self.block_count() as u64 * BLOCK_BYTES99    }100101    /// Read one exact-width value in one provider call. An out-of-bounds index102    /// reads no payload. Use get_many for repeated indices on the same node;103    /// successive scalar reads may lose execution-local first-read eligibility.104    pub fn get(105        &self,106        storage: &dyn Storage,107        index: u64,108        workspace: &mut Workspace,109    ) -> Result<Option<T>> {110        if index >= self.len {111            self.collection.validate(storage)?;112            return Ok(None);113        }114        let (node, at) = position(index, Self::VALUES_PER_NODE, T::WIDTH);115        self.collection.read_at(116            storage,117            logical_at(node, at)?,118            &mut workspace.bytes_mut()[..T::WIDTH],119        )?;120        T::decode(&workspace.bytes()[..T::WIDTH]).map(Some)121    }122123    /// Replace one value with an exact-width write, without fetching its node.124    pub fn set(125        &mut self,126        storage: &mut dyn Storage,127        index: u64,128        value: &T,129        workspace: &mut Workspace,130    ) -> Result<()> {131        if index >= self.len {132            self.collection.validate(storage)?;133            return Err(Error::Bounds);134        }135        let (node, at) = position(index, Self::VALUES_PER_NODE, T::WIDTH);136        value.encode(&mut workspace.bytes_mut()[..T::WIDTH]);137        self.collection.write_at(138            storage,139            logical_at(node, at)?,140            &workspace.bytes()[..T::WIDTH],141        )142    }143144    /// Append and return the new index. Allocation initializes complete blocks;145    /// ordinary appends write only one encoded value and read no stable bytes.146    pub fn push(147        &mut self,148        storage: &mut dyn Storage,149        value: &T,150        workspace: &mut Workspace,151    ) -> Result<u64> {152        let index = self.len;153        let next_len = index.checked_add(1).ok_or(Error::Capacity)?;154        let (node, at) = position(index, Self::VALUES_PER_NODE, T::WIDTH);155        let address = logical_at(node, at)?;156        let nodes = node.checked_add(1).ok_or(Error::Capacity)?;157        value.encode(&mut workspace.bytes_mut()[..T::WIDTH]);158        if node >= self.collection.node_capacity() {159            self.collection.ensure_nodes(storage, nodes)?;160        }161        self.collection162            .write_at(storage, address, &workspace.bytes()[..T::WIDTH])?;163        self.len = next_len;164        Ok(index)165    }166167    /// Append a slice and return its half-open range of newly assigned indices.168    ///169    /// Performs the same logical appends as repeated `push`, with one encoded170    /// write per occupied node span and no stable reads. Capacity arithmetic is171    /// checked before allocating. An empty slice still validates the owner.172    pub fn extend_from_slice(173        &mut self,174        storage: &mut dyn Storage,175        values: &[T],176        workspace: &mut Workspace,177    ) -> Result<Range<u64>> {178        let start = self.len;179        let count = u64::try_from(values.len()).map_err(|_| Error::Capacity)?;180        let end = start.checked_add(count).ok_or(Error::Capacity)?;181        if values.is_empty() {182            self.collection.validate(storage)?;183            return Ok(start..end);184        }185        let (last_node, last_at) = position(end - 1, Self::VALUES_PER_NODE, T::WIDTH);186        logical_at(last_node, last_at)?187            .checked_add(T::WIDTH as u64)188            .ok_or(Error::Capacity)?;189        if last_node >= self.collection.node_capacity() {190            self.collection191                .ensure_nodes(storage, last_node.checked_add(1).ok_or(Error::Capacity)?)?;192        }193        self.write_slice(storage, start, values, workspace)?;194        self.len = end;195        Ok(start..end)196    }197198    /// Replace a contiguous slice without reading existing values.199    ///200    /// Bounds reject before any write. Each occupied node span is encoded and201    /// written once, without clearing or writing node tails. Empty replacement202    /// at any position through len is valid and still checks the owner.203    pub fn set_slice(204        &mut self,205        storage: &mut dyn Storage,206        start: u64,207        values: &[T],208        workspace: &mut Workspace,209    ) -> Result<()> {210        let end = start211            .checked_add(u64::try_from(values.len()).map_err(|_| Error::Bounds)?)212            .ok_or(Error::Bounds)?;213        if end > self.len {214            self.collection.validate(storage)?;215            return Err(Error::Bounds);216        }217        if values.is_empty() {218            return self.collection.validate(storage);219        }220        self.write_slice(storage, start, values, workspace)221    }222223    fn write_slice(224        &self,225        storage: &mut dyn Storage,226        mut index: u64,227        mut values: &[T],228        workspace: &mut Workspace,229    ) -> Result<()> {230        while !values.is_empty() {231            let (node, at) = position(index, Self::VALUES_PER_NODE, T::WIDTH);232            let take = values233                .len()234                .min((Self::VALUES_PER_NODE - index % Self::VALUES_PER_NODE) as usize);235            let bytes = &mut workspace.bytes_mut()[..take * T::WIDTH];236            for (value, encoded) in values[..take].iter().zip(bytes.chunks_exact_mut(T::WIDTH)) {237                value.encode(encoded);238            }239            self.collection240                .write_at(storage, logical_at(node, at)?, bytes)?;241            index += take as u64;242            values = &values[take..];243        }244        Ok(())245    }246247    /// Remove the last value, returning wholly unused trailing stable blocks.248    pub fn pop(249        &mut self,250        storage: &mut dyn Storage,251        workspace: &mut Workspace,252    ) -> Result<Option<T>> {253        let Some(index) = self.len.checked_sub(1) else {254            self.collection.validate(storage)?;255            return Ok(None);256        };257        let (node, at) = position(index, Self::VALUES_PER_NODE, T::WIDTH);258        self.collection.read_at(259            storage,260            logical_at(node, at)?,261            &mut workspace.bytes_mut()[..T::WIDTH],262        )?;263        let value = T::decode(&workspace.bytes()[..T::WIDTH])?;264        let nodes = if index == 0 {265            0266        } else {267            (index - 1) / Self::VALUES_PER_NODE + 1268        };269        // The payload read checked the exact provider Root. Most pops keep270        // their complete physical block; only its final value needs retirement.271        if nodes.div_ceil(crate::NODES_PER_BLOCK) < self.collection.block_count() as u64 {272            self.collection.truncate_nodes(storage, nodes)?;273        }274        self.len = index;275        Ok(Some(value))276    }277278    /// Visit a bounded half-open range in index order, fetching each node once.279    /// Boundary nodes read only the selected contiguous values; complete nodes280    /// use a full aligned node read. Return false from `visit` to stop. The281    /// return value counts visited values.282    pub fn scan(283        &self,284        storage: &dyn Storage,285        range: Range<u64>,286        mut visit: impl FnMut(u64, T) -> bool,287        workspace: &mut Workspace,288    ) -> Result<u64> {289        if range.start >= range.end || range.end > self.len {290            self.collection.validate(storage)?;291            return if range.start > range.end || range.end > self.len {292                Err(Error::Bounds)293            } else {294                Ok(0)295            };296        }297        let mut index = range.start;298        while index < range.end {299            let (node, at) = position(index, Self::VALUES_PER_NODE, T::WIDTH);300            let take =301                (Self::VALUES_PER_NODE - index % Self::VALUES_PER_NODE).min(range.end - index);302            let end = index + take;303            let bytes = if take == Self::VALUES_PER_NODE {304                &self.collection.read_node(storage, node, workspace)?[..]305            } else {306                let span = take as usize * T::WIDTH;307                self.collection.read_at(308                    storage,309                    logical_at(node, at)?,310                    &mut workspace.bytes_mut()[..span],311                )?;312                &workspace.bytes()[..span]313            };314            let mut at = 0;315            while index < end {316                let value = T::decode(&bytes[at..at + T::WIDTH])?;317                if !visit(index, value) {318                    return Ok(index - range.start + 1);319                }320                index += 1;321                at += T::WIDTH;322            }323        }324        Ok(index - range.start)325    }326327    /// Visit sorted, nondecreasing indices, fetching each distinct node once.328    ///329    /// Each node group reads one contiguous span from its first requested value330    /// through its last. Singletons and repeated copies of one index read only331    /// one encoded value. Duplicate indices are visited separately. The caller332    /// retains control over request and result storage; this method allocates333    /// neither a permutation nor a result vector. Unsorted or out-of-bounds input334    /// rejects before reading payload. Return false from `visit` to stop.335    pub fn get_many(336        &self,337        storage: &dyn Storage,338        indices: &[u64],339        mut visit: impl FnMut(u64, T) -> bool,340        workspace: &mut Workspace,341    ) -> Result<usize> {342        if indices.windows(2).any(|pair| pair[0] > pair[1]) {343            self.collection.validate(storage)?;344            return Err(Error::InvalidInput(345                "Minima FixedVec indices must be sorted",346            ));347        }348        if indices.last().is_some_and(|index| *index >= self.len) {349            self.collection.validate(storage)?;350            return Err(Error::Bounds);351        }352        if indices.is_empty() {353            self.collection.validate(storage)?;354            return Ok(0);355        }356        let mut cursor = 0;357        while cursor < indices.len() {358            let first = indices[cursor];359            let (node, at) = position(first, Self::VALUES_PER_NODE, T::WIDTH);360            let remaining = Self::VALUES_PER_NODE - first % Self::VALUES_PER_NODE;361            let mut group_end = cursor + 1;362            // Preflight proved nondecreasing input. Differences cannot underflow363            // and avoid recomputing a node division for every requested value.364            while group_end < indices.len() && indices[group_end] - first < remaining {365                group_end += 1;366            }367            // Both endpoints are in this fixed node, so this source-known368            // geometry bounds the span by NODE_BYTES without extra workspace.369            let span = (indices[group_end - 1] - first + 1) as usize * T::WIDTH;370            self.collection.read_at(371                storage,372                logical_at(node, at)?,373                &mut workspace.bytes_mut()[..span],374            )?;375            let bytes = &workspace.bytes()[..span];376            while cursor < group_end {377                let index = indices[cursor];378                let at = (index - first) as usize * T::WIDTH;379                let value = T::decode(&bytes[at..at + T::WIDTH])?;380                cursor += 1;381                if !visit(index, value) {382                    return Ok(cursor);383                }384            }385        }386        Ok(cursor)387    }388389    /// Retire explicitly when a mutable storage capability is already available.390    pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {391        self.collection.retire(storage)392    }393}394395pub(crate) fn position(index: u64, per_node: u64, stride: usize) -> (u64, usize) {396    (index / per_node, (index % per_node) as usize * stride)397}398399pub(crate) fn logical_at(node: u64, at: usize) -> Result<u64> {400    node.checked_mul(NODE_BYTES as u64)401        .and_then(|base| base.checked_add(at as u64))402        .ok_or(Error::Capacity)403}404405#[cfg(test)]406mod tests {407    use super::*;408    use crate::Arena;409    use cdk_rsx_platform::memory::VecMemory;410411    #[test]412    fn slice_append_checks_last_value_extent_before_allocating() {413        let mut arena = Arena::format(VecMemory::new()).unwrap();414        let mut buffer = crate::NodeBuffer::new();415        let mut workspace = buffer.workspace();416        let mut values = FixedVec::<u64>::new(&mut arena).unwrap();417        // Exercise arithmetic independently of physical address-space limits.418        // No owning capability is constructed or altered by this test setup.419        values.len = u64::MAX / 8;420        assert_eq!(421            values.extend_from_slice(&mut arena, &[1], &mut workspace),422            Err(Error::Capacity)423        );424        assert_eq!(values.block_count(), 0);425        assert_eq!(arena.root().allocated_blocks(), 0);426    }427}