bitmap_set.rs
cdk-rsx/crates/cdk-rsx-collections-minima/src/bitmap_set.rs
1//! Exact membership for a bounded, reasonably dense `u64` identifier domain.2//!3//! The fixed layout has one bit per ID, least-significant bit first in each4//! byte. A 4 KiB node covers 32,768 consecutive IDs; there are no node headers5//! or per-ID lengths. The retained owner stores the exclusive upper ID bound6//! and exact cardinality. An empty set owns no stable blocks. Inserting a high7//! ID allocates and zeroes every preceding block: space is **O(highest inserted8//! ID)**, rounded to whole exclusive 64 KiB blocks, even for a very sparse set.9//! Removing an ID does not reclaim the preceding address space.10//!11//! Use this representation for dense IDs with a useful, finite bound. It is not12//! a replacement for a set of arbitrary sparse `u64` keys. All stable access13//! borrows the caller's reusable workspace; no cache or scratch is retained.1415const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("bitmap_set.rs");1617use crate::{Collection, Error, NODE_BYTES, Result, Storage, Workspace};18use cdk_rsx_engine_nyxus::NyxusData;1920/// Number of consecutive identifiers stored by one aligned node.21pub const BITS_PER_NODE: u64 = NODE_BYTES as u64 * 8;2223/// Fixed layout and interpretation input for an owning memory contract.24pub const BITMAP_SET_POLICY: [u8; 32] = crate::contract(25 "MinimaBitmapSet/v1",26 &[],27 &[SOURCE_POLICY, crate::MINIMA_POLICY],28);2930/// A move-only exact set for IDs in `0..id_bound`.31#[repr(C)]32pub struct BitmapSet {33 nodes: Collection,34 id_bound: u64,35 count: u64,36}3738// SAFETY: Collection owns only its admitted retained directory/authority. The39// remaining fields are inline integers; no decoded/transient data is retained.40// BITMAP_SET_POLICY pins this descriptor's fixed encoding and interpretation.41unsafe impl NyxusData for BitmapSet {42 const __NYXUS_POLICY: [u8; 32] = BITMAP_SET_POLICY;43}4445/// A bounded range result. Resume with `next..end` when `next` is present.46#[derive(Debug, Clone, Copy, PartialEq, Eq)]47pub struct RangePage {48 pub written: usize,49 pub nodes_read: usize,50 /// The first ID not yet examined. `None` means the range is exhausted.51 pub next: Option<u64>,52}5354impl BitmapSet {55 /// Construct an empty set without allocating a stable block.56 ///57 /// `id_bound` is exclusive. A zero bound is a valid permanently empty set;58 /// `u64::MAX` as the bound admits IDs through `u64::MAX - 1`.59 pub fn new(storage: &mut dyn Storage, id_bound: u64) -> Result<Self> {60 Ok(Self {61 nodes: Collection::new(storage)?,62 id_bound,63 count: 0,64 })65 }6667 /// Exact cardinality from the retained descriptor, without a stable read.68 pub fn len(&self) -> u64 {69 self.count70 }7172 pub fn is_empty(&self) -> bool {73 self.count == 074 }7576 pub fn id_bound(&self) -> u64 {77 self.id_bound78 }7980 /// Whole exclusive stable blocks currently owned by this set.81 pub fn block_count(&self) -> usize {82 self.nodes.block_count()83 }8485 /// One one-byte fetch for an allocated ID; out-of-domain IDs are absent.86 /// The rooted owner/generation is validated even when no fetch is needed.87 pub fn contains(88 &self,89 storage: &dyn Storage,90 id: u64,91 workspace: &mut Workspace,92 ) -> Result<bool> {93 let node = id / BITS_PER_NODE;94 if id >= self.id_bound || node >= self.nodes.node_capacity() {95 self.nodes.validate(storage)?;96 return Ok(false);97 }98 let bytes = &mut workspace.bytes_mut()[..1];99 self.nodes.read_at(storage, id / 8, bytes)?;100 Ok(bytes[0] & (1u8 << (id % 8)) != 0)101 }102103 /// Insert an ID, returning whether it was newly present.104 ///105 /// Bounds are checked before allocation or mutation. A changed bit writes106 /// exactly one byte after fetching that byte once. Growing to a high107 /// ID also zero-initializes all preceding whole collection blocks.108 pub fn insert(109 &mut self,110 storage: &mut dyn Storage,111 id: u64,112 workspace: &mut Workspace,113 ) -> Result<bool> {114 if id >= self.id_bound {115 self.nodes.validate(storage)?;116 return Err(Error::Bounds);117 }118 let node = id / BITS_PER_NODE;119 let allocated = node < self.nodes.node_capacity();120 if !allocated {121 self.nodes.ensure_nodes(storage, node + 1)?;122 }123 let before = if allocated {124 let bytes = &mut workspace.bytes_mut()[..1];125 self.nodes.read_at(storage, id / 8, bytes)?;126 bytes[0]127 } else {128 // node_capacity counts complete owned blocks. Crossing that bound129 // acquired a whole initialized-zero block, not merely a previously130 // used logical node within an already owned block.131 0132 };133 let mask = 1u8 << (id % 8);134 if before & mask != 0 {135 return Ok(false);136 }137 let changed = before | mask;138 self.nodes.write_at(storage, id / 8, &[changed])?;139 // count <= id_bound and this bit was previously absent, so increment140 // cannot overflow even at the largest representable exclusive bound.141 self.count += 1;142 Ok(true)143 }144145 /// Remove an ID, returning whether it had been present.146 /// Out-of-domain and never-allocated IDs are absent and cause no fetch.147 pub fn remove(148 &mut self,149 storage: &mut dyn Storage,150 id: u64,151 workspace: &mut Workspace,152 ) -> Result<bool> {153 let node = id / BITS_PER_NODE;154 if id >= self.id_bound || node >= self.nodes.node_capacity() {155 self.nodes.validate(storage)?;156 return Ok(false);157 }158 let bytes = &mut workspace.bytes_mut()[..1];159 self.nodes.read_at(storage, id / 8, bytes)?;160 let mask = 1u8 << (id % 8);161 if bytes[0] & mask == 0 {162 return Ok(false);163 }164 let changed = bytes[0] & !mask;165 self.nodes.write_at(storage, id / 8, &[changed])?;166 self.count -= 1;167 Ok(true)168 }169170 /// Insert nondecreasing IDs, returning the number newly present.171 /// Duplicates have the same effect as repeated scalar insertion. Ordering172 /// and bounds reject before allocation or mutation. Each already allocated173 /// node group is fetched once; fresh blocks start from known zero bytes.174 /// Only consecutive changed bytes share a write, with no untouched gaps.175 /// Provider failures during mutation abort the execution for IC rollback.176 pub fn insert_grouped(177 &mut self,178 storage: &mut dyn Storage,179 ids: &[u64],180 workspace: &mut Workspace,181 ) -> Result<u64> {182 self.change_grouped::<true>(storage, ids, workspace)183 }184185 /// Remove nondecreasing IDs, returning the number previously present.186 /// Duplicates remove a bit once. Out-of-domain and unallocated IDs are187 /// absent. The read/write spans and failure contract match insert_grouped;188 /// removal never allocates or reclaims stable blocks.189 pub fn remove_grouped(190 &mut self,191 storage: &mut dyn Storage,192 ids: &[u64],193 workspace: &mut Workspace,194 ) -> Result<u64> {195 self.change_grouped::<false>(storage, ids, workspace)196 }197198 fn change_grouped<const INSERT: bool>(199 &mut self,200 storage: &mut dyn Storage,201 ids: &[u64],202 workspace: &mut Workspace,203 ) -> Result<u64> {204 if ids.windows(2).any(|pair| pair[0] > pair[1]) {205 return Err(Error::InvalidInput("bitmap IDs must be sorted"));206 }207 if INSERT && ids.last().is_some_and(|id| *id >= self.id_bound) {208 return Err(Error::Bounds);209 }210 self.nodes.validate(storage)?;211 let initialized_nodes = self.nodes.node_capacity();212 if INSERT {213 if let Some(id) = ids.last() {214 let node = *id / BITS_PER_NODE;215 if node >= initialized_nodes {216 self.nodes.ensure_nodes(storage, node + 1)?;217 }218 }219 }220 let mut cursor = 0;221 let mut changed = 0;222 while cursor < ids.len() {223 let first = ids[cursor];224 let node = first / BITS_PER_NODE;225 if !INSERT && (first >= self.id_bound || node >= initialized_nodes) {226 break;227 }228 let remaining = BITS_PER_NODE - first % BITS_PER_NODE;229 let mut end = cursor + 1;230 while end < ids.len() && ids[end] - first < remaining && ids[end] < self.id_bound {231 end += 1;232 }233 let first_byte = first / 8;234 let span = (ids[end - 1] / 8 - first_byte + 1) as usize;235 let bytes = &mut workspace.bytes_mut()[..span];236 if node < initialized_nodes {237 // An earlier group may already have committed. A read failure238 // must not return a partially applied mutation to its caller.239 self.nodes240 .read_at(storage, first_byte, bytes)241 .expect("bitmap grouped mutation read");242 } else {243 bytes.fill(0);244 }245 let mut run_start = 0;246 let mut run_end = 0;247 while cursor < end {248 let byte = ids[cursor] / 8;249 let at = (byte - first_byte) as usize;250 let mut mask = 0;251 while cursor < end && ids[cursor] / 8 == byte {252 mask |= 1u8 << (ids[cursor] % 8);253 cursor += 1;254 }255 let before = bytes[at];256 let after = if INSERT {257 before | mask258 } else {259 before & !mask260 };261 if before != after {262 if run_end != 0 && at != run_end {263 self.nodes264 .write_at(265 storage,266 first_byte + run_start as u64,267 &bytes[run_start..run_end],268 )269 .expect("bitmap grouped mutation write");270 run_end = 0;271 }272 if run_end == 0 {273 run_start = at;274 }275 bytes[at] = after;276 run_end = at + 1;277 changed += u64::from((before ^ after).count_ones());278 }279 }280 if run_end != 0 {281 self.nodes282 .write_at(283 storage,284 first_byte + run_start as u64,285 &bytes[run_start..run_end],286 )287 .expect("bitmap grouped mutation write");288 }289 }290 // Distinct changed bits bound this update by id_bound; duplicates never291 // contribute twice, including within one encoded byte.292 if INSERT {293 self.count += changed;294 } else {295 self.count -= changed;296 }297 Ok(changed)298 }299300 /// Check a nondecreasing batch, fetching each distinct node at most once.301 ///302 /// `out.len()` must equal `ids.len()`. Duplicates are allowed. Invalid303 /// ordering or output length rejects before changing `out` or reading304 /// stable bytes. Work is bounded by the supplied slice: at most one fetch305 /// per input ID, and no allocation or persistent cache is used. Each node306 /// fetch spans only the first through last needed byte (one for a307 /// singleton), never crossing the node's logical 4 KiB boundary.308 pub fn contains_grouped(309 &self,310 storage: &dyn Storage,311 ids: &[u64],312 out: &mut [bool],313 workspace: &mut Workspace,314 ) -> Result<()> {315 if ids.len() != out.len() {316 return Err(Error::InvalidInput("bitmap batch output length"));317 }318 if ids.windows(2).any(|pair| pair[0] > pair[1]) {319 return Err(Error::InvalidInput("bitmap batch IDs must be sorted"));320 }321 self.nodes.validate(storage)?;322 let mut at = 0;323 while at < ids.len() {324 let node = ids[at] / BITS_PER_NODE;325 if ids[at] >= self.id_bound || node >= self.nodes.node_capacity() {326 out[at..].fill(false);327 break;328 }329 let first = at;330 at += 1;331 while at < ids.len() && ids[at] < self.id_bound && ids[at] / BITS_PER_NODE == node {332 at += 1;333 }334 let first_byte = ids[first] / 8;335 let span = (ids[at - 1] / 8 - first_byte + 1) as usize;336 let bytes = &mut workspace.bytes_mut()[..span];337 self.nodes.read_at(storage, first_byte, bytes)?;338 for index in first..at {339 let byte = (ids[index] / 8 - first_byte) as usize;340 out[index] = bytes[byte] & (1u8 << (ids[index] % 8)) != 0;341 }342 }343 Ok(())344 }345346 /// Iterate present bits in ascending order within `start..end`.347 ///348 /// Both bounds must belong to `0..=id_bound`, and `start <= end`.349 /// Reads at most `max_nodes` nodes and emits at most `out.len()` IDs.350 /// Empty nodes still consume the node budget, so a sparse range cannot351 /// hide an unbounded scan behind a small output. A zero budget/output352 /// makes no progress. Never-allocated trailing IDs are known absent.353 /// Boundary fetches include only the selected 64-bit words; complete354 /// interior nodes still use one full-node read.355 pub fn range(356 &self,357 storage: &dyn Storage,358 start: u64,359 end: u64,360 out: &mut [u64],361 max_nodes: usize,362 workspace: &mut Workspace,363 ) -> Result<RangePage> {364 if start > end || end > self.id_bound {365 return Err(Error::Bounds);366 }367 self.nodes.validate(storage)?;368 let stored_end = self.nodes.node_capacity().saturating_mul(BITS_PER_NODE);369 let end = end.min(stored_end);370 let mut next = start;371 let mut result = RangePage {372 written: 0,373 nodes_read: 0,374 next: None,375 };376 while next < end && result.nodes_read < max_nodes && result.written < out.len() {377 let node = next / BITS_PER_NODE;378 let page_base = node * BITS_PER_NODE;379 let node_end = end.min(page_base.saturating_add(BITS_PER_NODE));380 let first_word = ((next - page_base) / 64) as usize;381 let end_word = ((node_end - page_base - 1) / 64 + 1) as usize;382 let span = (end_word - first_word) * 8;383 self.nodes.read_at(384 storage,385 page_base / 8 + (first_word * 8) as u64,386 &mut workspace.bytes_mut()[..span],387 )?;388 let bytes = &workspace.bytes()[..span];389 result.nodes_read += 1;390 let mut word_at = first_word;391 while word_at < end_word && next < node_end {392 let base = page_base + word_at as u64 * 64;393 let offset = (word_at - first_word) * 8;394 let mut word = u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap());395 word &= u64::MAX << (next - base);396 let valid_bits = (node_end - base).min(64);397 if valid_bits < 64 {398 word &= (1u64 << valid_bits) - 1;399 }400 while word != 0 {401 let id = base + u64::from(word.trailing_zeros());402 out[result.written] = id;403 result.written += 1;404 next = id + 1;405 if result.written == out.len() {406 result.next = (next < end).then_some(next);407 return Ok(result);408 }409 word &= word - 1;410 }411 next = base.saturating_add(64).min(node_end);412 word_at += 1;413 }414 }415 result.next = (next < end).then_some(next);416 Ok(result)417 }418419 /// Release all stable blocks and the collection's live owner identity.420 pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {421 self.nodes.retire(storage)422 }423}424425#[cfg(test)]426#[path = "bitmap_set_tests.rs"]427mod tests;