memento.rs

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

memento.rs1,428 lines← SDK documentation
1//! Memento's integer partitioning, RSQF runs and three-case keepsake boxes.2//!3//! Independent implementation of Eslami and Dayan, Memento Filter, §3–44//! (<https://arxiv.org/abs/2408.05625v3>). This initial implementation has a5//! fixed quotient geometry: it does not implement §5's fluid fingerprints or6//! expansion. Rank/select counts metadata words; updates stage a bounded7//! proposed local cluster instead of using the reference implementation's SIMD shifts.8//! The underlying quotient runs and compressed keepsake encoding are preserved.9//!10//! An authoritative exact set must authorize each insertion and deletion once.11//! Fingerprint collisions retain multiplicity; a positive never proves presence.12//! Payload mutation faults trap and rely on IC rollback. No undo log is kept.1314const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("memento.rs");1516use crate::hash::{XXH64_POLICY, xxh64};17use crate::{Collection, Error, NODE_BYTES, Result, Storage, Workspace};18use cdk_rsx_engine_nyxus::NyxusData;1920pub const MEMENTO_POLICY: [u8; 32] = crate::contract(21    "MinimaMementoRsqfKeepsakes/v1",22    &[],23    &[SOURCE_POLICY, crate::MINIMA_POLICY, XXH64_POLICY],24);2526/// Hard bounds on transient decoding and metadata scans, in addition to the27/// instance's smaller configured bounds. No operation grows these bounds.28pub const MEMENTO_MAX_QUOTIENT_BITS: u8 = 16;29pub const MEMENTO_MAX_KEYS: u32 = 1 << 20;30pub const MEMENTO_MAX_SHIFT: u32 = 4096;31/// Bounds per-call input/results; decoded proposed state remains bounded by32/// the configured max_keys and geometry. Larger callers use explicit chunks.33pub const MEMENTO_MAX_BATCH_KEYS: usize = 1024;3435#[repr(C)]36#[derive(Clone, Copy, Debug, Eq, PartialEq)]37pub struct MementoConfig {38    pub quotient_bits: u8,39    pub fingerprint_bits: u8,40    /// Maximum inclusive integer range length. Must be in 1..=2^32.41    pub max_range_len: u64,42    pub max_keys: u32,43    /// Maximum distance from a run's canonical slot to its last payload slot.44    pub max_shift_slots: u32,45    pub seed: u64,46}47// SAFETY: inline scalar configuration, with no pointers or transient carriers.48unsafe impl NyxusData for MementoConfig {49    const __NYXUS_POLICY: [u8; 32] = MEMENTO_POLICY;50}5152impl MementoConfig {53    /// Include this value-specific contract, MEMENTO_POLICY and the standard54    /// Minima policies in the owning root's admission dependencies.55    pub const fn contract(self) -> [u8; 32] {56        crate::contract(57            "MinimaMementoConfiguration/v1",58            &[],59            &[60                MEMENTO_POLICY,61                crate::width_contract("quotient", self.quotient_bits as usize, &[]),62                crate::width_contract("fingerprint", self.fingerprint_bits as usize, &[]),63                crate::width_contract("range", self.max_range_len as usize, &[]),64                crate::width_contract("keys", self.max_keys as usize, &[]),65                crate::width_contract("shift", self.max_shift_slots as usize, &[]),66                crate::width_contract("seed", self.seed as usize, &[]),67            ],68        )69    }70    fn validate(self) -> Result<u8> {71        if !(1..=MEMENTO_MAX_QUOTIENT_BITS).contains(&self.quotient_bits)72            || !(1..=32).contains(&self.fingerprint_bits)73            || !(1..=1u64 << 32).contains(&self.max_range_len)74            || !(1..=MEMENTO_MAX_KEYS).contains(&self.max_keys)75            || !(1..=MEMENTO_MAX_SHIFT).contains(&self.max_shift_slots)76        {77            return Err(Error::InvalidInput("Memento configuration"));78        }79        Ok((u64::BITS - (self.max_range_len - 1).leading_zeros()) as u8)80    }81}8283#[derive(Clone, Copy, Debug, Eq, PartialEq)]84#[must_use]85pub enum MementoInsert {86    Inserted,87    /// Key, encoded-slot or displacement budget exhausted. No state changed.88    Full,89}9091/// Move-only retained authority. Stable bytes contain metadata and encoded92/// keepsakes; every owned block belongs exclusively to this descriptor.93#[repr(C)]94pub struct MementoFilter {95    nodes: Collection,96    config: MementoConfig,97    len: u64,98    used_slots: u32,99    memento_bits: u8,100}101// SAFETY: Collection owns admitted retained authority. All other fields are102// inline scalars. Decoded runs, proposed images and workspace are transient.103unsafe impl NyxusData for MementoFilter {104    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;105}106107#[derive(Clone, Debug, Eq, PartialEq)]108pub(crate) struct Keepsake {109    pub fingerprint: u64,110    pub mementos: Vec<u64>,111}112#[derive(Clone, Debug, Eq, PartialEq)]113pub(crate) struct Run {114    pub canonical: u32,115    pub boxes: Vec<Keepsake>,116}117118impl MementoFilter {119    pub const CONTRACT: [u8; 32] = MEMENTO_POLICY;120121    pub fn new(storage: &mut dyn Storage, config: MementoConfig) -> Result<Self> {122        let memento_bits = config.validate()?;123        Ok(Self {124            nodes: Collection::new(storage)?,125            config,126            len: 0,127            used_slots: 0,128            memento_bits,129        })130    }131    pub fn len(&self) -> u64 {132        self.len133    }134    pub fn is_empty(&self) -> bool {135        self.len == 0136    }137    pub fn config(&self) -> MementoConfig {138        self.config139    }140    pub fn memento_bits(&self) -> u8 {141        self.memento_bits142    }143    pub fn encoded_slots(&self) -> u32 {144        self.used_slots145    }146    pub fn block_count(&self) -> usize {147        self.nodes.block_count()148    }149    pub fn payload_bytes(&self) -> u64 {150        self.geometry().bytes()151    }152153    pub fn may_contain(154        &self,155        storage: &dyn Storage,156        key: u64,157        workspace: &mut Workspace,158    ) -> Result<bool> {159        self.may_contain_range(storage, key, key, workspace)160    }161162    /// Inclusive bounds. Invalid/reversed or over-budget ranges reject before163    /// reads. At most two integer partitions are searched, including at u64::MAX.164    pub fn may_contain_range(165        &self,166        storage: &dyn Storage,167        lower: u64,168        upper: u64,169        workspace: &mut Workspace,170    ) -> Result<bool> {171        check_range(lower, upper, self.config.max_range_len)?;172        self.nodes.validate(storage)?;173        if self.is_empty() {174            return Ok(false);175        }176        let geometry = self.geometry();177        let mask = bitmask(self.memento_bits);178        let first = lower >> self.memento_bits;179        let last = upper >> self.memento_bits;180        // Locate both possible partition runs before lending the same buffer181        // to payload decoding. Metadata stays borrowed, without a heap copy.182        let mut runs = [None; 2];183        let mut fingerprints = [0; 2];184        {185            let mut metadata = RunMetadata::new(&self.nodes, storage, geometry.slots, 2, workspace);186            for partition in first..=last {187                let (canonical, fingerprint) = self.identity(partition);188                fingerprints[(partition - first) as usize] = fingerprint;189                runs[(partition - first) as usize] =190                    metadata.locate(canonical, self.config.max_shift_slots)?;191            }192        }193        for partition in first..=last {194            let fingerprint = fingerprints[(partition - first) as usize];195            if let Some((start, end)) = runs[(partition - first) as usize] {196                let mut slots = SlotReader::new(197                    &self.nodes,198                    storage,199                    workspace,200                    geometry.data_at,201                    start,202                    end,203                    geometry.slot_bits,204                );205                let low = if partition == first { lower & mask } else { 0 };206                let high = if partition == last {207                    upper & mask208                } else {209                    mask210                };211                if query_slots(212                    &mut slots,213                    self.memento_bits,214                    self.config.fingerprint_bits,215                    self.config.max_keys as usize,216                    fingerprint,217                    low,218                    high,219                )? {220                    return Ok(true);221                }222            }223        }224        Ok(false)225    }226227    /// Insert one occurrence after exact-set admission. A colliding keepsake228    /// never suppresses an insertion. All expected rejection precedes mutation.229    pub fn try_insert(230        &mut self,231        storage: &mut dyn Storage,232        key: u64,233        workspace: &mut Workspace,234    ) -> Result<MementoInsert> {235        self.nodes.validate(storage)?;236        if self.len >= u64::from(self.config.max_keys) {237            return Ok(MementoInsert::Full);238        }239        let (canonical, fingerprint) = self.identity(key >> self.memento_bits);240        let layout = self.read_layout(storage, workspace)?;241        let at = layout.runs.partition_point(|r| r.canonical < canonical);242        let mut boxes = self.read_run(storage, &layout, at, canonical, workspace)?;243        let memento = key & bitmask(self.memento_bits);244        let at = boxes.partition_point(|b| b.fingerprint < fingerprint);245        if at == boxes.len() || boxes[at].fingerprint != fingerprint {246            boxes.insert(247                at,248                Keepsake {249                    fingerprint,250                    mementos: Vec::new(),251                },252            );253        }254        let mementos = &mut boxes[at].mementos;255        mementos.insert(mementos.partition_point(|m| *m <= memento), memento);256        let encoded = encode_boxes(&boxes, self.memento_bits, self.config.fingerprint_bits);257        let Some(used) = self.replace_run(storage, layout, canonical, &encoded, workspace)? else {258            return Ok(MementoInsert::Full);259        };260        self.len += 1;261        self.used_slots = used;262        Ok(MementoInsert::Inserted)263    }264265    /// Presence must be established by the caller's exact set, never by this266    /// filter. Remove exactly once per previously successful insertion.267    pub fn remove_known_present(268        &mut self,269        storage: &mut dyn Storage,270        key: u64,271        workspace: &mut Workspace,272    ) -> Result<bool> {273        let (canonical, fingerprint) = self.identity(key >> self.memento_bits);274        let layout = self.read_layout(storage, workspace)?;275        let at = layout.runs.partition_point(|r| r.canonical < canonical);276        let mut boxes = self.read_run(storage, &layout, at, canonical, workspace)?;277        let memento = key & bitmask(self.memento_bits);278        let Ok(box_at) = boxes.binary_search_by_key(&fingerprint, |b| b.fingerprint) else {279            return Ok(false);280        };281        let Ok(at) = boxes[box_at].mementos.binary_search(&memento) else {282            return Ok(false);283        };284        boxes[box_at].mementos.remove(at);285        if boxes[box_at].mementos.is_empty() {286            boxes.remove(box_at);287        }288        let encoded = encode_boxes(&boxes, self.memento_bits, self.config.fingerprint_bits);289        let used = self290            .replace_run(storage, layout, canonical, &encoded, workspace)?291            .expect("Memento deletion cannot exhaust capacity");292        self.len -= 1;293        self.used_slots = used;294        Ok(true)295    }296297    /// Validate every stored run and its global counts explicitly. Ordinary298    /// scalar edits decode their selected quotient and relocate encoded neighbors;299    /// they do not inspect unrelated keepsake payloads.300    pub fn check_integrity(&self, storage: &dyn Storage, workspace: &mut Workspace) -> Result<()> {301        self.read_runs(storage, workspace).map(|_| ())302    }303    /// Apply at most 1,024 exact-authorized insertions in input order. Decode304    /// and validate once, preflight every intermediate capacity, then encode305    /// and publish once. Each Full leaves that attempted insertion unchanged;306    /// earlier successes remain in the proposed result. No persistent state307    /// changes on a returned error. Colliding identities retain multiplicity.308    pub fn try_insert_many(309        &mut self,310        storage: &mut dyn Storage,311        keys: &[u64],312        workspace: &mut Workspace,313    ) -> Result<Vec<MementoInsert>> {314        if keys.len() > MEMENTO_MAX_BATCH_KEYS {315            return Err(Error::Capacity);316        }317        self.nodes.validate(storage)?;318        let mut results = Vec::new();319        results320            .try_reserve_exact(keys.len())321            .map_err(|_| Error::Capacity)?;322        if keys.is_empty() || self.len >= u64::from(self.config.max_keys) {323            results.resize(keys.len(), MementoInsert::Full);324            return Ok(results);325        }326        let mut runs = self.read_runs(storage, workspace)?;327        let mut len = self.len;328        for &key in keys {329            if len >= u64::from(self.config.max_keys) {330                results.push(MementoInsert::Full);331                continue;332            }333            let (canonical, fingerprint) = self.identity(key >> self.memento_bits);334            let memento = key & bitmask(self.memento_bits);335            let run = runs.partition_point(|r| r.canonical < canonical);336            if runs.get(run).is_none_or(|r| r.canonical != canonical) {337                runs.insert(338                    run,339                    Run {340                        canonical,341                        boxes: Vec::new(),342                    },343                );344            }345            let boxes = &mut runs[run].boxes;346            let at = boxes.partition_point(|b| b.fingerprint < fingerprint);347            if boxes.get(at).is_none_or(|b| b.fingerprint != fingerprint) {348                boxes.insert(349                    at,350                    Keepsake {351                        fingerprint,352                        mementos: Vec::new(),353                    },354                );355            }356            let mementos = &mut boxes[at].mementos;357            mementos.insert(mementos.partition_point(|m| *m <= memento), memento);358            if self.bulk_fits_runs(&runs)? {359                len += 1;360                results.push(MementoInsert::Inserted);361            } else {362                // Discard only this rejected proposed occurrence. This is363                // transient staging, not a stable undo image or transaction.364                assert!(self.bulk_remove_run(&mut runs, key));365                results.push(MementoInsert::Full);366            }367        }368        if len != self.len {369            let image = self370                .encode(&runs)?371                .expect("preflighted Memento batch image");372            self.publish(storage, &image, workspace);373            self.len = len;374            self.used_slots = image.used;375        }376        Ok(results)377    }378379    /// Apply exact-authorized removals in input order, returning one presence380    /// result per input. A missing stored identity leaves the proposal unchanged.381    /// Decode/validate and encode/publish each occur at most once; all expected382    /// errors precede publication and mutation backend failures trap.383    pub fn remove_known_present_many(384        &mut self,385        storage: &mut dyn Storage,386        keys: &[u64],387        workspace: &mut Workspace,388    ) -> Result<Vec<bool>> {389        if keys.len() > MEMENTO_MAX_BATCH_KEYS {390            return Err(Error::Capacity);391        }392        self.nodes.validate(storage)?;393        let mut results = Vec::new();394        results395            .try_reserve_exact(keys.len())396            .map_err(|_| Error::Capacity)?;397        if keys.is_empty() {398            return Ok(results);399        }400        let mut runs = self.read_runs(storage, workspace)?;401        let mut removed = 0;402        for &key in keys {403            let yes = self.bulk_remove_run(&mut runs, key);404            removed += u64::from(yes);405            results.push(yes);406        }407        if removed != 0 {408            let image = self409                .encode(&runs)?410                .expect("Memento batch deletion capacity");411            self.publish(storage, &image, workspace);412            self.len -= removed;413            self.used_slots = image.used;414        }415        Ok(results)416    }417418    fn bulk_remove_run(&self, runs: &mut Vec<Run>, key: u64) -> bool {419        let (canonical, fingerprint) = self.identity(key >> self.memento_bits);420        let memento = key & bitmask(self.memento_bits);421        let Ok(run) = runs.binary_search_by_key(&canonical, |r| r.canonical) else {422            return false;423        };424        let boxes = &mut runs[run].boxes;425        let Ok(at) = boxes.binary_search_by_key(&fingerprint, |b| b.fingerprint) else {426            return false;427        };428        let Ok(m) = boxes[at].mementos.binary_search(&memento) else {429            return false;430        };431        boxes[at].mementos.remove(m);432        if boxes[at].mementos.is_empty() {433            boxes.remove(at);434        }435        if boxes.is_empty() {436            runs.remove(run);437        }438        true439    }440441    fn bulk_fits_runs(&self, runs: &[Run]) -> Result<bool> {442        let geometry = self.geometry();443        let mut position = 0usize;444        let mut used = 0usize;445        for run in runs {446            let mut count = 0;447            for b in &run.boxes {448                let n = b.mementos.len();449                count += if n <= 2 || b.fingerprint == 0 || self.memento_bits < 2 {450                    n451                } else {452                    // encode_boxes stores two endpoints, then a base-(2^r-1)453                    // count with digits-1 sentinels and n-2 inner mementos.454                    let base = bitmask(self.memento_bits) as usize;455                    let mut left = n - 2;456                    let mut digits = 1;457                    while left >= base {458                        left /= base;459                        digits += 1;460                    }461                    2 + ((n - 2 + 2 * digits - 1) * self.memento_bits as usize)462                        .div_ceil((self.memento_bits + self.config.fingerprint_bits) as usize)463                };464            }465            position = position.max(run.canonical as usize);466            let end = position.checked_add(count).ok_or(Error::Overflow)?;467            if count == 0468                || end > geometry.slots as usize469                || end - 1 - run.canonical as usize > self.config.max_shift_slots as usize470            {471                return Ok(false);472            }473            used += count;474            position = end;475        }476        Ok(used as u64 * 100 <= u64::from(geometry.canonical) * 95)477    }478479    pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {480        self.nodes.retire(storage)481    }482483    fn geometry(&self) -> Geometry {484        Geometry::new(485            self.config.quotient_bits,486            self.config.max_shift_slots,487            self.memento_bits + self.config.fingerprint_bits,488        )489    }490    fn identity(&self, partition: u64) -> (u32, u64) {491        let hash = xxh64(&partition.to_le_bytes(), self.config.seed);492        (493            (hash & bitmask(self.config.quotient_bits)) as u32,494            (hash >> self.config.quotient_bits) & bitmask(self.config.fingerprint_bits),495        )496    }497498    fn read_layout(&self, storage: &dyn Storage, workspace: &mut Workspace) -> Result<RunLayout> {499        self.nodes.validate(storage)?;500        let g = self.geometry();501        let metadata = if self.is_empty() {502            vec![0; g.metadata_bytes()]503        } else {504            read_metadata(&self.nodes, storage, g, workspace)?505        };506        let mut runs = Vec::new();507        let mut position = 0;508        let mut used = 0;509        for group in 0..g.canonical.div_ceil(64) {510            let at = group as usize * 16;511            let mut occupied = u64::from_le_bytes(metadata[at..at + 8].try_into().unwrap());512            if group == g.canonical / 64 {513                occupied &= bitmask((g.canonical % 64) as u8);514            }515            while occupied != 0 {516                let canonical = group * 64 + occupied.trailing_zeros();517                occupied &= occupied - 1;518                let start = position.max(canonical);519                let end = find_end(&metadata, start, g.slots)?;520                if end - canonical > self.config.max_shift_slots {521                    return Err(corrupt());522                }523                used += end - start + 1;524                runs.push(RunSpan {525                    canonical,526                    start,527                    end: end + 1,528                });529                position = end + 1;530            }531        }532        if used != self.used_slots {533            return Err(corrupt());534        }535        Ok(RunLayout { metadata, runs })536    }537538    fn read_run(539        &self,540        storage: &dyn Storage,541        layout: &RunLayout,542        at: usize,543        canonical: u32,544        workspace: &mut Workspace,545    ) -> Result<Vec<Keepsake>> {546        let Some(run) = layout.runs.get(at).filter(|r| r.canonical == canonical) else {547            return Ok(Vec::new());548        };549        let slots = read_slots(550            &self.nodes,551            storage,552            self.geometry(),553            run.start,554            run.end - 1,555            workspace,556        )?;557        let boxes = decode_boxes(558            &slots,559            self.memento_bits,560            self.config.fingerprint_bits,561            self.config.max_keys as usize,562        )?;563        if boxes.iter().map(|b| b.mementos.len() as u64).sum::<u64>() > self.len {564            return Err(corrupt());565        }566        Ok(boxes)567    }568569    fn replace_run(570        &mut self,571        storage: &mut dyn Storage,572        mut layout: RunLayout,573        canonical: u32,574        encoded: &[u64],575        workspace: &mut Workspace,576    ) -> Result<Option<u32>> {577        let g = self.geometry();578        let at = layout.runs.partition_point(|r| r.canonical < canonical);579        let old = layout580            .runs581            .get(at)582            .copied()583            .filter(|r| r.canonical == canonical);584        let old_count = old.map_or(0, |r| r.end - r.start);585        let used = self.used_slots - old_count + encoded.len() as u32;586        if u64::from(used) * 100 > u64::from(g.canonical) * 95 {587            return Ok(None);588        }589        let start = if at == 0 {590            canonical591        } else {592            layout.runs[at - 1].end.max(canonical)593        };594        let mut position = start + encoded.len() as u32;595        if !encoded.is_empty()596            && (position > g.slots || position - 1 - canonical > self.config.max_shift_slots)597        {598            return Ok(None);599        }600        let mut end = position.max(old.map_or(start, |r| r.end));601        let mut moves = Vec::new();602        for run in &layout.runs[at + usize::from(old.is_some())..] {603            let new_start = position.max(run.canonical);604            if new_start == run.start {605                break;606            }607            position = new_start + run.end - run.start;608            if position > g.slots || position - 1 - run.canonical > self.config.max_shift_slots {609                return Ok(None);610            }611            end = end.max(run.end).max(position);612            moves.push((*run, new_start));613        }614        // Stage all reads before allocation or publication. The region is615        // bounded by configured geometry; unrelated clusters remain untouched.616        let before = if self.nodes.block_count() == 0 {617            vec![0; (end - start) as usize]618        } else {619            read_slots(&self.nodes, storage, g, start, end - 1, workspace)?620        };621        let mut after = vec![0; before.len()];622        after[..encoded.len()].copy_from_slice(encoded);623        for (run, new_start) in &moves {624            let source = (run.start - start) as usize;625            let target = (new_start - start) as usize;626            let count = (run.end - run.start) as usize;627            after[target..target + count].copy_from_slice(&before[source..source + count]);628        }629        let metadata_before = layout.metadata.clone();630        if let Some(run) = old {631            clear_flag(&mut layout.metadata, run.end - 1, true);632        }633        clear_flag(&mut layout.metadata, canonical, false);634        for (run, _) in &moves {635            clear_flag(&mut layout.metadata, run.end - 1, true);636        }637        if !encoded.is_empty() {638            set_flag(&mut layout.metadata, canonical, false);639            set_flag(&mut layout.metadata, start + encoded.len() as u32 - 1, true);640        }641        for (run, new_start) in &moves {642            set_flag(643                &mut layout.metadata,644                new_start + run.end - run.start - 1,645                true,646            );647        }648        self.nodes649            .ensure_nodes(storage, g.bytes().div_ceil(NODE_BYTES as u64))650            .expect("admitted Memento allocation failed");651        let mut cursor = 0;652        while cursor < layout.metadata.len() {653            if layout.metadata[cursor] == metadata_before[cursor] {654                cursor += 1;655                continue;656            }657            let first = cursor;658            cursor += 1;659            while cursor < layout.metadata.len()660                && layout.metadata[cursor] != metadata_before[cursor]661            {662                cursor += 1;663            }664            self.nodes665                .write_at(storage, first as u64, &layout.metadata[first..cursor])666                .expect("admitted Memento metadata write failed");667        }668        // Unchanged spans need no write. A changed run remains bounded by one669        // workspace even when packed values straddle a logical node boundary.670        let per_span = NODE_BYTES / g.slot_bytes;671        let mut cursor = 0;672        while cursor < after.len() {673            if before[cursor] == after[cursor] {674                cursor += 1;675                continue;676            }677            let first = cursor;678            cursor += 1;679            while cursor < after.len()680                && cursor - first < per_span681                && before[cursor] != after[cursor]682            {683                cursor += 1;684            }685            let bytes = &mut workspace.bytes_mut()[..(cursor - first) * g.slot_bytes];686            for (slot, encoded) in after[first..cursor]687                .iter()688                .zip(bytes.chunks_exact_mut(g.slot_bytes))689            {690                encoded.copy_from_slice(&slot.to_le_bytes()[..g.slot_bytes]);691            }692            self.nodes693                .write_at(694                    storage,695                    g.data_at + (start as usize + first) as u64 * g.slot_bytes as u64,696                    bytes,697                )698                .expect("admitted Memento write failed");699        }700        Ok(Some(used))701    }702    fn read_runs(&self, storage: &dyn Storage, workspace: &mut Workspace) -> Result<Vec<Run>> {703        self.nodes.validate(storage)?;704        if self.is_empty() {705            return Ok(Vec::new());706        }707        let geometry = self.geometry();708        let metadata = read_metadata(&self.nodes, storage, geometry, workspace)?;709        let mut runs = Vec::new();710        let mut position = 0u32;711        let mut count = 0u64;712        let mut used = 0u32;713        for canonical in 0..geometry.canonical {714            if !flag(&metadata, canonical, false) {715                continue;716            }717            let start = position.max(canonical);718            let end = find_end(&metadata, start, geometry.slots)?;719            let slots = read_slots(&self.nodes, storage, geometry, start, end, workspace)?;720            let boxes = decode_boxes(721                &slots,722                self.memento_bits,723                self.config.fingerprint_bits,724                self.config.max_keys as usize,725            )?;726            count += boxes.iter().map(|b| b.mementos.len() as u64).sum::<u64>();727            if count > self.len {728                return Err(corrupt());729            }730            runs.push(Run { canonical, boxes });731            position = end + 1;732            used += end - start + 1;733        }734        if count != self.len || used != self.used_slots {735            return Err(corrupt());736        }737        Ok(runs)738    }739    fn encode(&self, runs: &[Run]) -> Result<Option<Image>> {740        let geometry = self.geometry();741        let mut image = Image {742            metadata: vec![0; geometry.metadata_bytes()],743            slots: vec![0; geometry.slots as usize],744            used: 0,745        };746        let mut position = 0usize;747        for run in runs {748            position = position.max(run.canonical as usize);749            let encoded = encode_boxes(&run.boxes, self.memento_bits, self.config.fingerprint_bits);750            let end = position.checked_add(encoded.len()).ok_or(Error::Overflow)?;751            if encoded.is_empty()752                || end > image.slots.len()753                || end - 1 - run.canonical as usize > self.config.max_shift_slots as usize754            {755                return Ok(None);756            }757            image.slots[position..end].copy_from_slice(&encoded);758            set_flag(&mut image.metadata, run.canonical, false);759            set_flag(&mut image.metadata, (end - 1) as u32, true);760            image.used += encoded.len() as u32;761            position = end;762        }763        // RSQF's documented maximum nominal load; compression may represent764        // more keys than slots, but does not silently raise payload occupancy.765        if u64::from(image.used) * 100 > u64::from(geometry.canonical) * 95 {766            return Ok(None);767        }768        Ok(Some(image))769    }770    fn publish(&mut self, storage: &mut dyn Storage, image: &Image, workspace: &mut Workspace) {771        let geometry = self.geometry();772        self.nodes773            .ensure_nodes(storage, geometry.bytes().div_ceil(NODE_BYTES as u64))774            .expect("admitted Memento allocation failed");775        // Metadata is already encoded. Block allocation initializes padding to776        // zero, and neither publisher ever writes those padding bytes.777        self.nodes778            .write_at(storage, 0, &image.metadata)779            .expect("admitted Memento metadata write failed");780        let slots_per_span = NODE_BYTES / geometry.slot_bytes;781        for (span, slots) in image.slots.chunks(slots_per_span).enumerate() {782            let out = &mut workspace.bytes_mut()[..slots.len() * geometry.slot_bytes];783            for (slot, encoded) in slots.iter().zip(out.chunks_exact_mut(geometry.slot_bytes)) {784                encoded.copy_from_slice(&slot.to_le_bytes()[..geometry.slot_bytes]);785            }786            self.nodes787                .write_at(788                    storage,789                    geometry.data_at + (span * slots_per_span * geometry.slot_bytes) as u64,790                    out,791                )792                .expect("admitted Memento write failed");793        }794    }795}796797pub(crate) fn check_range(lower: u64, upper: u64, maximum: u64) -> Result<()> {798    if lower > upper || upper - lower >= maximum {799        Err(Error::InvalidInput("integer range bound"))800    } else {801        Ok(())802    }803}804pub(crate) const fn bitmask(bits: u8) -> u64 {805    if bits == 64 {806        u64::MAX807    } else if bits == 0 {808        0809    } else {810        (1u64 << bits) - 1811    }812}813fn corrupt() -> Error {814    Error::InvalidInput("Memento payload invariant")815}816817#[derive(Clone, Copy)]818struct Geometry {819    canonical: u32,820    slots: u32,821    slot_bits: u8,822    slot_bytes: usize,823    data_at: u64,824}825impl Geometry {826    fn new(quotient: u8, shift: u32, slot_bits: u8) -> Self {827        let slots = (1u32 << quotient) + shift;828        let metadata = (slots as u64).div_ceil(64) * 16;829        Self {830            canonical: 1u32 << quotient,831            slots,832            slot_bits,833            slot_bytes: (slot_bits as usize).div_ceil(8),834            data_at: metadata.div_ceil(NODE_BYTES as u64) * NODE_BYTES as u64,835        }836    }837    fn metadata_bytes(self) -> usize {838        (self.slots as usize).div_ceil(64) * 16839    }840    fn bytes(self) -> u64 {841        (self.data_at + self.slots as u64 * self.slot_bytes as u64).div_ceil(NODE_BYTES as u64)842            * NODE_BYTES as u64843    }844}845struct Image {846    metadata: Vec<u8>,847    slots: Vec<u64>,848    used: u32,849}850#[derive(Clone, Copy)]851struct RunSpan {852    canonical: u32,853    start: u32,854    end: u32,855}856struct RunLayout {857    metadata: Vec<u8>,858    runs: Vec<RunSpan>,859}860fn flag(metadata: &[u8], slot: u32, end: bool) -> bool {861    let at = slot as usize / 64 * 16 + usize::from(end) * 8 + slot as usize % 64 / 8;862    metadata[at] & (1 << (slot % 8)) != 0863}864fn set_flag(metadata: &mut [u8], slot: u32, end: bool) {865    let at = slot as usize / 64 * 16 + usize::from(end) * 8 + slot as usize % 64 / 8;866    metadata[at] |= 1 << (slot % 8);867}868fn clear_flag(metadata: &mut [u8], slot: u32, end: bool) {869    let at = slot as usize / 64 * 16 + usize::from(end) * 8 + slot as usize % 64 / 8;870    metadata[at] &= !(1 << (slot % 8));871}872fn find_end(metadata: &[u8], start: u32, bound: u32) -> Result<u32> {873    for group in start / 64..bound.div_ceil(64) {874        let at = group as usize * 16 + 8;875        let mut ends = u64::from_le_bytes(metadata[at..at + 8].try_into().unwrap());876        if group == start / 64 {877            ends &= !bitmask((start % 64) as u8);878        }879        if group == bound / 64 {880            ends &= bitmask((bound % 64) as u8);881        }882        if ends != 0 {883            return Ok(group * 64 + ends.trailing_zeros());884        }885    }886    Err(corrupt())887}888/// One operation's borrowed window. Coalesce its needed span within the current889/// logical node. Nonmonotonic probes can replace and refetch this window; the890/// slot reader retains adjacent scalars for packed node crossings. Nothing891/// outlives the workspace loan and no cache survives a call or mutation.892pub(crate) struct ReadSpan<'a, 'w> {893    nodes: &'a Collection,894    storage: &'a dyn Storage,895    workspace: &'a mut Workspace<'w>,896    first: u64,897    end: u64,898    loaded_at: u64,899    loaded_len: usize,900}901impl<'a, 'w> ReadSpan<'a, 'w> {902    pub(crate) fn new(903        nodes: &'a Collection,904        storage: &'a dyn Storage,905        workspace: &'a mut Workspace<'w>,906        first: u64,907        end: u64,908    ) -> Self {909        Self {910            nodes,911            storage,912            workspace,913            first,914            end,915            loaded_at: 0,916            loaded_len: 0,917        }918    }919    fn fetch(&mut self, at: u64) -> Result<()> {920        if at < self.first || at >= self.end {921            return Err(corrupt());922        }923        if self.loaded_len != 0924            && self.loaded_at <= at925            && at < self.loaded_at + self.loaded_len as u64926        {927            return Ok(());928        }929        let node = at / NODE_BYTES as u64 * NODE_BYTES as u64;930        self.loaded_at = self.first.max(node);931        self.loaded_len = (self.end.min(node + NODE_BYTES as u64) - self.loaded_at) as usize;932        self.nodes.read_at(933            self.storage,934            self.loaded_at,935            &mut self.workspace.bytes_mut()[..self.loaded_len],936        )937    }938    pub(crate) fn value(&mut self, at: u64, width: usize) -> Result<u64> {939        if width > 8940            || at941                .checked_add(width as u64)942                .is_none_or(|end| end > self.end)943        {944            return Err(corrupt());945        }946        self.fetch(at)?;947        let offset = (at - self.loaded_at) as usize;948        let take = width.min(self.loaded_len - offset);949        if take == width {950            return Ok(decode_value(951                &self.workspace.bytes()[offset..offset + width],952            ));953        }954        let mut encoded = [0; 8];955        encoded[..take].copy_from_slice(&self.workspace.bytes()[offset..offset + take]);956        if take < width {957            self.fetch(at + take as u64)?;958            encoded[take..width].copy_from_slice(&self.workspace.bytes()[..width - take]);959        }960        Ok(u64::from_le_bytes(encoded))961    }962    /// Metadata lanes are eight-byte aligned and never cross a logical node.963    /// Decode that fixed span directly instead of staging a variable-width964    /// slot through a zero-filled temporary and a copy.965    fn word(&mut self, at: u64) -> Result<u64> {966        if at.checked_add(8).is_none_or(|end| end > self.end) {967            return Err(corrupt());968        }969        self.fetch(at)?;970        let offset = (at - self.loaded_at) as usize;971        Ok(u64::from_le_bytes(972            self.workspace.bytes()[offset..offset + 8]973                .try_into()974                .unwrap(),975        ))976    }977}978979fn decode_value(bytes: &[u8]) -> u64 {980    match bytes.len() {981        0 => 0,982        1 => u64::from(bytes[0]),983        2 => u64::from(u16::from_le_bytes(bytes.try_into().unwrap())),984        3 => {985            u64::from(u16::from_le_bytes(bytes[..2].try_into().unwrap()))986                | (u64::from(bytes[2]) << 16)987        }988        4 => u64::from(u32::from_le_bytes(bytes.try_into().unwrap())),989        5 => {990            u64::from(u32::from_le_bytes(bytes[..4].try_into().unwrap()))991                | (u64::from(bytes[4]) << 32)992        }993        6 => {994            u64::from(u32::from_le_bytes(bytes[..4].try_into().unwrap()))995                | (u64::from(u16::from_le_bytes(bytes[4..].try_into().unwrap())) << 32)996        }997        7 => {998            u64::from(u32::from_le_bytes(bytes[..4].try_into().unwrap()))999                | (u64::from(u16::from_le_bytes(bytes[4..6].try_into().unwrap())) << 32)1000                | (u64::from(bytes[6]) << 48)1001        }1002        8 => u64::from_le_bytes(bytes.try_into().unwrap()),1003        _ => unreachable!(),1004    }1005}10061007/// RSQF occupied and run-end rank/select. Aeris has a third lane: its run-end1008/// mask is keepsake-end AND extension. Count complete words instead of walking1009/// every canonical slot and every earlier run's payload displacement.1010pub(crate) struct RunMetadata<'a, 'w> {1011    bytes: ReadSpan<'a, 'w>,1012    slots: u32,1013    lanes: u64,1014}1015impl<'a, 'w> RunMetadata<'a, 'w> {1016    pub(crate) fn new(1017        nodes: &'a Collection,1018        storage: &'a dyn Storage,1019        slots: u32,1020        lanes: u64,1021        workspace: &'a mut Workspace<'w>,1022    ) -> Self {1023        Self {1024            bytes: ReadSpan::new(1025                nodes,1026                storage,1027                workspace,1028                0,1029                u64::from(slots).div_ceil(64) * lanes * 8,1030            ),1031            slots,1032            lanes,1033        }1034    }1035    pub(crate) fn word(&mut self, group: u32, lane: u64) -> Result<u64> {1036        self.bytes.word((u64::from(group) * self.lanes + lane) * 8)1037    }1038    fn run_ends(&mut self, group: u32) -> Result<u64> {1039        let ends = self.word(group, 1)?;1040        Ok(if self.lanes == 3 {1041            ends & self.word(group, 2)?1042        } else {1043            ends1044        })1045    }1046    pub(crate) fn locate(&mut self, canonical: u32, max_shift: u32) -> Result<Option<(u32, u32)>> {1047        let group = canonical / 64;1048        let bit = canonical % 64;1049        let occupied = self.word(group, 0)?;1050        if occupied & (1u64 << bit) == 0 {1051            return Ok(None);1052        }1053        let mut rank = 0u32;1054        let mut ends_before = 0u32;1055        for before in 0..group {1056            rank += self.word(before, 0)?.count_ones();1057            ends_before += self.run_ends(before)?.count_ones();1058        }1059        rank += (occupied & bitmask((bit + 1) as u8)).count_ones();1060        ends_before += (self.run_ends(group)? & bitmask(bit as u8)).count_ones();1061        let mut left = rank1062            .checked_sub(ends_before)1063            .filter(|n| *n > 0)1064            .ok_or_else(corrupt)?;1065        let bound = canonical.saturating_add(max_shift).min(self.slots - 1);1066        let mut previous = None;1067        for at in group..=bound / 64 {1068            let mut ends = self.run_ends(at)?;1069            if at == group {1070                ends &= !bitmask(bit as u8);1071            }1072            if at == bound / 64 {1073                ends &= bitmask((bound % 64 + 1) as u8);1074            }1075            let count = ends.count_ones();1076            if count < left {1077                left -= count;1078                if ends != 0 {1079                    previous = Some(at * 64 + 63 - ends.leading_zeros());1080                }1081                continue;1082            }1083            while left > 1 {1084                let end = ends.trailing_zeros();1085                previous = Some(at * 64 + end);1086                ends &= ends - 1;1087                left -= 1;1088            }1089            let end = at * 64 + ends.trailing_zeros();1090            let start = previous.map_or(canonical, |end| (end + 1).max(canonical));1091            return Ok(Some((start, end)));1092        }1093        Err(corrupt())1094    }1095}10961097pub(crate) struct SlotReader<'a, 'w> {1098    bytes: ReadSpan<'a, 'w>,1099    first: u64,1100    count: u32,1101    width: u8,1102    slot_bytes: usize,1103    recent: [Option<(u32, u64)>; 2],1104}1105impl<'a, 'w> SlotReader<'a, 'w> {1106    pub(crate) fn new(1107        nodes: &'a Collection,1108        storage: &'a dyn Storage,1109        workspace: &'a mut Workspace<'w>,1110        data_at: u64,1111        start: u32,1112        end: u32,1113        width: u8,1114    ) -> Self {1115        let slot_bytes = (width as usize).div_ceil(8);1116        let first = data_at + u64::from(start) * slot_bytes as u64;1117        let count = end - start + 1;1118        Self {1119            bytes: ReadSpan::new(1120                nodes,1121                storage,1122                workspace,1123                first,1124                first + u64::from(count) * slot_bytes as u64,1125            ),1126            first,1127            count,1128            width,1129            slot_bytes,1130            recent: [None; 2],1131        }1132    }1133    pub(crate) fn len(&self) -> u32 {1134        self.count1135    }1136    pub(crate) fn slot(&mut self, at: u32) -> Result<u64> {1137        if at >= self.count {1138            return Err(corrupt());1139        }1140        if let Some((_, value)) = self.recent.iter().flatten().find(|(slot, _)| *slot == at) {1141            return Ok(*value);1142        }1143        let value = self.bytes.value(1144            self.first + u64::from(at) * self.slot_bytes as u64,1145            self.slot_bytes,1146        )? & bitmask(self.width);1147        // Adjacent packed chunks and compression lookahead can reuse a slot1148        // that straddles two nodes without fetching its first node again.1149        self.recent[0] = self.recent[1];1150        self.recent[1] = Some((at, value));1151        Ok(value)1152    }1153    pub(crate) fn bits(&mut self, at: usize, bits: u8) -> Result<u64> {1154        if at + bits as usize > self.count as usize * self.width as usize {1155            return Err(corrupt());1156        }1157        let slot = at / self.width as usize;1158        let shift = at % self.width as usize;1159        let mut value = self.slot(slot as u32)? >> shift;1160        if shift + bits as usize > self.width as usize {1161            value |= self.slot(slot as u32 + 1)? << (self.width as usize - shift);1162        }1163        Ok(value & bitmask(bits))1164    }1165}11661167fn query_slots(1168    slots: &mut SlotReader<'_, '_>,1169    r: u8,1170    f: u8,1171    maximum: usize,1172    query: u64,1173    low: u64,1174    high: u64,1175) -> Result<bool> {1176    let width = r + f;1177    let mask = bitmask(r);1178    let mut position = 0u32;1179    let mut total = 0usize;1180    let mut previous_fingerprint = None;1181    let mut found = false;1182    while position < slots.len() {1183        let first = slots.slot(position)?;1184        let fingerprint = first >> r;1185        if previous_fingerprint.is_some_and(|old| old >= fingerprint) {1186            return Err(corrupt());1187        }1188        previous_fingerprint = Some(fingerprint);1189        let mut previous = first & mask;1190        found |= fingerprint == query && low <= previous && previous <= high;1191        let mut count = 1usize;1192        if fingerprint != 01193            && r >= 21194            && position + 1 < slots.len()1195            && slots.slot(position + 1)? >> r == 01196        {1197            let largest = slots.slot(position + 1)? & mask;1198            let inner_at = (position as usize + 2) * width as usize;1199            let mut sentinels = 0usize;1200            while slots.bits(inner_at + sentinels * r as usize, r)? == mask {1201                sentinels += 1;1202                if sentinels > 32 {1203                    return Err(corrupt());1204                }1205            }1206            let mut inner_count = 0u64;1207            for i in 0..=sentinels {1208                let digit = slots.bits(inner_at + (sentinels + i) * r as usize, r)?;1209                if digit >= mask {1210                    return Err(corrupt());1211                }1212                inner_count = inner_count1213                    .checked_mul(mask)1214                    .and_then(|v| v.checked_add(digit))1215                    .ok_or_else(corrupt)?;1216            }1217            let inner_count = usize::try_from(inner_count).map_err(|_| corrupt())?;1218            if inner_count == 0 || inner_count > maximum.saturating_sub(total + 2) {1219                return Err(corrupt());1220            }1221            let chunks = sentinels * 2 + 1;1222            for i in 0..inner_count {1223                let memento = slots.bits(inner_at + (chunks + i) * r as usize, r)?;1224                if memento < previous {1225                    return Err(corrupt());1226                }1227                found |= fingerprint == query && low <= memento && memento <= high;1228                previous = memento;1229            }1230            if largest < previous {1231                return Err(corrupt());1232            }1233            found |= fingerprint == query && low <= largest && largest <= high;1234            count += inner_count + 1;1235            position += 2 + ((chunks + inner_count) * r as usize).div_ceil(width as usize) as u32;1236        } else {1237            position += 1;1238            while position < slots.len() {1239                let value = slots.slot(position)?;1240                if value >> r != fingerprint {1241                    break;1242                }1243                let memento = value & mask;1244                if memento < previous {1245                    return Err(corrupt());1246                }1247                found |= fingerprint == query && low <= memento && memento <= high;1248                previous = memento;1249                count += 1;1250                position += 1;1251            }1252            if fingerprint != 0 && r >= 2 && count > 2 {1253                return Err(corrupt());1254            }1255        }1256        total += count;1257        if total > maximum {1258            return Err(corrupt());1259        }1260    }1261    Ok(found)1262}1263fn read_metadata(1264    nodes: &Collection,1265    storage: &dyn Storage,1266    geometry: Geometry,1267    workspace: &mut Workspace,1268) -> Result<Vec<u8>> {1269    let mut out = vec![0; geometry.metadata_bytes()];1270    for (node, chunk) in out.chunks_mut(NODE_BYTES).enumerate() {1271        chunk.copy_from_slice(&nodes.read_node(storage, node as u64, workspace)?[..chunk.len()]);1272    }1273    Ok(out)1274}1275fn read_slots(1276    nodes: &Collection,1277    storage: &dyn Storage,1278    geometry: Geometry,1279    start: u32,1280    end: u32,1281    workspace: &mut Workspace,1282) -> Result<Vec<u64>> {1283    let mut out = Vec::with_capacity((end - start + 1) as usize);1284    let first = geometry.data_at + u64::from(start) * geometry.slot_bytes as u64;1285    let total = (end - start + 1) as usize * geometry.slot_bytes;1286    // Borrow one aligned node at a time. The slot width is fixed, but its byte1287    // lanes may straddle adjacent nodes; the small carry is transient.1288    let mut encoded = [0u8; 8];1289    let mut lane = 0;1290    let mut position = first;1291    while position < first + total as u64 {1292        let node = position / NODE_BYTES as u64;1293        let offset = position as usize % NODE_BYTES;1294        let bytes = nodes.read_node(storage, node, workspace)?;1295        let take = (NODE_BYTES - offset).min((first + total as u64 - position) as usize);1296        for byte in &bytes[offset..offset + take] {1297            encoded[lane] = *byte;1298            lane += 1;1299            if lane == geometry.slot_bytes {1300                out.push(u64::from_le_bytes(encoded) & bitmask(geometry.slot_bits));1301                encoded.fill(0);1302                lane = 0;1303            }1304        }1305        position += take as u64;1306    }1307    Ok(out)1308}13091310fn encode_boxes(boxes: &[Keepsake], r: u8, f: u8) -> Vec<u64> {1311    let width = r + f;1312    let mut out = Vec::new();1313    for b in boxes {1314        let pair = |m| (b.fingerprint << r) | m;1315        if b.mementos.len() <= 2 || b.fingerprint == 0 || r < 2 {1316            out.extend(b.mementos.iter().map(|m| pair(*m)));1317        } else {1318            out.push(pair(b.mementos[0]));1319            out.push(*b.mementos.last().unwrap());1320            let count = b.mementos.len() - 2;1321            let mut digits = Vec::new();1322            let base = bitmask(r);1323            let mut left = count as u64;1324            loop {1325                digits.push(left % base);1326                left /= base;1327                if left == 0 {1328                    break;1329                }1330            }1331            let mut chunks = vec![base; digits.len() - 1];1332            chunks.extend(digits.into_iter().rev());1333            chunks.extend_from_slice(&b.mementos[1..b.mementos.len() - 1]);1334            let at = out.len();1335            out.resize(at + (chunks.len() * r as usize).div_ceil(width as usize), 0);1336            for (i, chunk) in chunks.into_iter().enumerate() {1337                put_bits(&mut out[at..], i * r as usize, r, width, chunk);1338            }1339        }1340    }1341    out1342}1343fn decode_boxes(slots: &[u64], r: u8, f: u8, maximum: usize) -> Result<Vec<Keepsake>> {1344    let width = r + f;1345    let mask = bitmask(r);1346    let mut out: Vec<Keepsake> = Vec::new();1347    let mut position = 0;1348    let mut total = 0;1349    while position < slots.len() {1350        let fingerprint = slots[position] >> r;1351        if out.last().is_some_and(|b| b.fingerprint >= fingerprint) {1352            return Err(corrupt());1353        }1354        let mut mementos = vec![slots[position] & mask];1355        if fingerprint != 0 && r >= 2 && position + 1 < slots.len() && slots[position + 1] >> r == 01356        {1357            let largest = slots[position + 1] & mask;1358            let inner = &slots[position + 2..];1359            let mut sentinels = 0usize;1360            while get_bits(inner, sentinels * r as usize, r, width)? == mask {1361                sentinels += 1;1362                if sentinels > 32 {1363                    return Err(corrupt());1364                }1365            }1366            let mut count = 0u64;1367            for i in 0..=sentinels {1368                let digit = get_bits(inner, (sentinels + i) * r as usize, r, width)?;1369                if digit >= mask {1370                    return Err(corrupt());1371                }1372                count = count1373                    .checked_mul(mask)1374                    .and_then(|v| v.checked_add(digit))1375                    .ok_or_else(corrupt)?;1376            }1377            let count = usize::try_from(count).map_err(|_| corrupt())?;1378            if count == 0 || count > maximum.saturating_sub(total + 2) {1379                return Err(corrupt());1380            }1381            let chunks = sentinels * 2 + 1;1382            for i in 0..count {1383                mementos.push(get_bits(inner, (chunks + i) * r as usize, r, width)?);1384            }1385            mementos.push(largest);1386            position += 2 + ((chunks + count) * r as usize).div_ceil(width as usize);1387        } else {1388            position += 1;1389            while position < slots.len() && slots[position] >> r == fingerprint {1390                mementos.push(slots[position] & mask);1391                position += 1;1392            }1393            if fingerprint != 0 && r >= 2 && mementos.len() > 2 {1394                return Err(corrupt());1395            }1396        }1397        total += mementos.len();1398        if total > maximum || mementos.windows(2).any(|p| p[0] > p[1]) {1399            return Err(corrupt());1400        }1401        out.push(Keepsake {1402            fingerprint,1403            mementos,1404        });1405    }1406    Ok(out)1407}1408fn put_bits(slots: &mut [u64], at: usize, bits: u8, width: u8, value: u64) {1409    for bit in 0..bits as usize {1410        let at = at + bit;1411        slots[at / width as usize] |= ((value >> bit) & 1) << (at % width as usize);1412    }1413}1414fn get_bits(slots: &[u64], at: usize, bits: u8, width: u8) -> Result<u64> {1415    if at + bits as usize > slots.len() * width as usize {1416        return Err(corrupt());1417    }1418    let mut out = 0;1419    for bit in 0..bits as usize {1420        let position = at + bit;1421        out |= ((slots[position / width as usize] >> (position % width as usize)) & 1) << bit;1422    }1423    Ok(out)1424}14251426#[cfg(test)]1427#[path = "memento_tests.rs"]1428mod tests;