prefix_sums.rs
cdk-rsx/crates/cdk-rsx-collections-minima/src/prefix_sums.rs
1//! Immutable exact `u64` range sums using two prefix endpoints.2//!3//! Each entry is the little-endian 8-byte sum through that input position.4//! There are 512 entries per aligned 4 KiB node, no per-entry lengths and no5//! node headers. The retained descriptor holds the input length and total.6//! Construction rejects arithmetic overflow before allocating collection7//! storage. Queries use ordinary exact subtraction; sums never wrap.8//!9//! This representation is useful for many range-sum queries over an immutable10//! nonnegative sequence: a range fetches at most two nodes regardless of its11//! width. It does not retain the original values or support point updates.1213const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("prefix_sums.rs");1415use crate::{Collection, Error, NODE_BYTES, Result, Storage, Workspace};16use cdk_rsx_engine_nyxus::NyxusData;1718const ENTRIES_PER_NODE: u64 = NODE_BYTES as u64 / 8;19const _: () = assert!(NODE_BYTES.is_multiple_of(8));2021/// Fixed layout and interpretation input for an owning memory contract.22pub const PREFIX_SUMS_POLICY: [u8; 32] = crate::contract(23 "MinimaFrozenPrefixSumsU64/v1",24 &[],25 &[SOURCE_POLICY, crate::MINIMA_POLICY],26);2728/// A move-only frozen exact prefix index over an input sequence of `u64`s.29#[repr(C)]30pub struct FrozenPrefixSums {31 nodes: Collection,32 len: u64,33 total: u64,34}3536// SAFETY: Collection owns its admitted retained directory/authority; len and37// total are inline integers. No decoded element or transient buffer survives.38// PREFIX_SUMS_POLICY pins the fixed encoding and arithmetic interpretation.39unsafe impl NyxusData for FrozenPrefixSums {40 const __NYXUS_POLICY: [u8; 32] = PREFIX_SUMS_POLICY;41}4243impl FrozenPrefixSums {44 /// Build from an immutable input. Overflow rejects before any allocation.45 /// Stable space is eight bytes per input, rounded to exclusive 64 KiB46 /// blocks. The caller lends one reusable node workspace for the whole build.47 pub fn from_slice(48 storage: &mut dyn Storage,49 values: &[u64],50 workspace: &mut Workspace,51 ) -> Result<Self> {52 let first_len = values.len().min(ENTRIES_PER_NODE as usize);53 let mut first_total = 0u64;54 // The first node fits the existing workspace: compute its checked55 // prefixes during preflight instead of adding the same inputs twice.56 for (value, encoded) in values[..first_len]57 .iter()58 .zip(workspace.bytes_mut()[..first_len * 8].chunks_exact_mut(8))59 {60 first_total = first_total.checked_add(*value).ok_or(Error::Overflow)?;61 encoded.copy_from_slice(&first_total.to_le_bytes());62 }63 let total = values[first_len..]64 .iter()65 .try_fold(first_total, |sum, value| {66 sum.checked_add(*value).ok_or(Error::Overflow)67 })?;68 let len = u64::try_from(values.len()).map_err(|_| Error::Capacity)?;69 let mut nodes = Collection::new(storage)?;70 nodes.ensure_nodes(storage, len.div_ceil(ENTRIES_PER_NODE))?;71 if first_len != 0 {72 nodes.write_at(storage, 0, &workspace.bytes()[..first_len * 8])?;73 }74 let mut sum = first_total;75 for (node, chunk) in values[first_len..]76 .chunks(ENTRIES_PER_NODE as usize)77 .enumerate()78 {79 let bytes = &mut workspace.bytes_mut()[..chunk.len() * 8];80 for (at, value) in chunk.iter().enumerate() {81 // The preflight fold proved every nonnegative prefix fits.82 sum += *value;83 bytes[at * 8..at * 8 + 8].copy_from_slice(&sum.to_le_bytes());84 }85 nodes.write_at(storage, (node as u64 + 1) * NODE_BYTES as u64, bytes)?;86 }87 Ok(Self { nodes, len, total })88 }8990 pub fn len(&self) -> u64 {91 self.len92 }9394 pub fn is_empty(&self) -> bool {95 self.len == 096 }9798 /// Exact full-sequence total from the retained descriptor, with no fetch.99 pub fn total(&self) -> u64 {100 self.total101 }102103 pub fn block_count(&self) -> usize {104 self.nodes.block_count()105 }106107 /// Sum the first `end` inputs, with `0 <= end <= len`.108 /// Endpoints 0 and len need no fetch; others need one eight-byte fetch.109 pub fn prefix(110 &self,111 storage: &dyn Storage,112 end: u64,113 workspace: &mut Workspace,114 ) -> Result<u64> {115 if end > self.len {116 return Err(Error::Bounds);117 }118 if end == 0 {119 self.nodes.validate(storage)?;120 return Ok(0);121 }122 if end == self.len {123 self.nodes.validate(storage)?;124 return Ok(self.total);125 }126 self.read_prefix(storage, end, workspace)127 }128129 /// Read sorted, nondecreasing prefix endpoints into caller-owned output.130 ///131 /// `out.len()` must equal `ends.len()`. Endpoints 0 and len use retained132 /// totals; each other node group uses one bounding fetch. Duplicates are133 /// allowed, no result container is allocated, and invalid length, ordering134 /// or bounds reject before changing output or reading payload.135 pub fn prefix_many(136 &self,137 storage: &dyn Storage,138 ends: &[u64],139 out: &mut [u64],140 workspace: &mut Workspace,141 ) -> Result<()> {142 if ends.len() != out.len() {143 return Err(Error::InvalidInput("prefix batch output length"));144 }145 if ends.windows(2).any(|pair| pair[0] > pair[1]) {146 return Err(Error::InvalidInput("prefix endpoints must be sorted"));147 }148 if ends.last().is_some_and(|end| *end > self.len) {149 return Err(Error::Bounds);150 }151 self.nodes.validate(storage)?;152 let mut cursor = 0;153 while cursor < ends.len() {154 let first = ends[cursor];155 if first == 0 {156 out[cursor] = 0;157 cursor += 1;158 continue;159 }160 if first == self.len {161 out[cursor..].fill(self.total);162 break;163 }164 let node = (first - 1) / ENTRIES_PER_NODE;165 let mut group_end = cursor + 1;166 while group_end < ends.len()167 && ends[group_end] < self.len168 && (ends[group_end] - 1) / ENTRIES_PER_NODE == node169 {170 group_end += 1;171 }172 let span = ((ends[group_end - 1] - first + 1) * 8) as usize;173 self.nodes174 .read_at(storage, (first - 1) * 8, &mut workspace.bytes_mut()[..span])?;175 let bytes = &workspace.bytes()[..span];176 for index in cursor..group_end {177 let at = ((ends[index] - first) * 8) as usize;178 out[index] = u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap());179 }180 cursor = group_end;181 }182 Ok(())183 }184185 /// Sum the half-open input range `start..end` exactly.186 ///187 /// Rejects `start > end` or `end > len`. An empty or full sequence range188 /// needs no stable fetch. Other ranges need at most two eight-byte reads,189 /// sharing a single bounded span when both endpoints occupy one node. Work does190 /// not depend on the range's width, and no persistent cache is retained.191 pub fn sum(192 &self,193 storage: &dyn Storage,194 start: u64,195 end: u64,196 workspace: &mut Workspace,197 ) -> Result<u64> {198 if start > end || end > self.len {199 return Err(Error::Bounds);200 }201 if start == end {202 self.nodes.validate(storage)?;203 return Ok(0);204 }205 if start == 0 {206 return if end == self.len {207 self.nodes.validate(storage)?;208 Ok(self.total)209 } else {210 self.read_prefix(storage, end, workspace)211 };212 }213 if end == self.len {214 return Ok(self.total - self.read_prefix(storage, start, workspace)?);215 }216 let start_at = start - 1;217 let end_at = end - 1;218 let start_node = start_at / ENTRIES_PER_NODE;219 let end_node = end_at / ENTRIES_PER_NODE;220 if start_node == end_node {221 let span = ((end_at - start_at + 1) * 8) as usize;222 let bytes = &mut workspace.bytes_mut()[..span];223 self.nodes.read_at(storage, start_at * 8, bytes)?;224 let before = u64::from_le_bytes(bytes[..8].try_into().unwrap());225 let through = u64::from_le_bytes(bytes[span - 8..].try_into().unwrap());226 return Ok(through - before);227 }228 let before = self.read_prefix(storage, start, workspace)?;229 let through = self.read_prefix(storage, end, workspace)?;230 Ok(through - before)231 }232233 fn read_prefix(234 &self,235 storage: &dyn Storage,236 end: u64,237 workspace: &mut Workspace,238 ) -> Result<u64> {239 let at = end - 1;240 let bytes = &mut workspace.bytes_mut()[..8];241 self.nodes.read_at(storage, at * 8, bytes)?;242 Ok(u64::from_le_bytes(bytes.try_into().unwrap()))243 }244245 pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {246 self.nodes.retire(storage)247 }248}249250#[cfg(test)]251#[path = "prefix_sums_tests.rs"]252mod tests;