slot_arena.rs

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

slot_arena.rs830 lines← SDK documentation
1//! Direct-indexed stable slots with owner-bound generational handles.23const SOURCE_POLICY: [u8; 32] =4    cdk_rsx_source_policy::source_policy!("slot_arena.rs", "indexed.rs");56use crate::{7    BLOCK_BYTES, Collection, CollectionId, Error, Fixed, NODE_BYTES, Result, Storage, Workspace,8    indexed::{logical_at, position},9};10use core::marker::PhantomData;1112const NONE: u64 = u64::MAX;13const LIVE: u64 = u64::MAX - 1;14const RETIRED: u64 = u64::MAX - 2;15const HEADER_BYTES: usize = 16;1617/// A nonowning arena address. Copying it never retains the arena or its value.18///19/// Identity includes the collection, slot index, and generation. A removed slot20/// never becomes valid for the same handle again, including at generation21/// saturation. Handles from another arena reject before reading stable payload.22#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]23#[repr(C)]24pub struct SlotId {25    collection: CollectionId,26    index: u64,27    generation: u64,28}2930// SAFETY: the handle contains only nonowning scalar identity fields.31unsafe impl cdk_rsx_engine_nyxus::NyxusData for SlotId {32    const __NYXUS_POLICY: [u8; 32] = <Self as Fixed>::CONTRACT;33}3435impl Fixed for SlotId {36    const WIDTH: usize = <(CollectionId, u64, u64) as Fixed>::WIDTH;37    const CONTRACT: [u8; 32] = crate::width_contract(38        "minima-slot-id-le-v1",39        Self::WIDTH,40        &[SOURCE_POLICY, crate::MINIMA_POLICY, CollectionId::CONTRACT],41    );4243    fn encode(&self, out: &mut [u8]) {44        self.collection.encode(&mut out[..CollectionId::WIDTH]);45        self.index46            .encode(&mut out[CollectionId::WIDTH..CollectionId::WIDTH + 8]);47        self.generation.encode(&mut out[CollectionId::WIDTH + 8..]);48    }4950    fn decode(bytes: &[u8]) -> Result<Self> {51        let (collection, index, generation) = <(CollectionId, u64, u64)>::decode(bytes)?;52        if generation == 0 {53            return Err(Error::Corrupt("Minima SlotId zero generation"));54        }55        Ok(Self {56            collection,57            index,58            generation,59        })60    }61}6263// SAFETY: the owner identity, index, and generation use canonical fixed bytes;64// derived lexicographic Ord agrees with equality of those exact fields.65unsafe impl crate::FixedKey for SlotId {}6667impl SlotId {68    /// Form a nonowning address from saved identity fields. This constructor69    /// rejects generation zero; the arena checks live owner, bounds, state and70    /// generation on every access. Construction never grants storage authority.71    pub fn new(collection: CollectionId, index: u64, generation: u64) -> Result<Self> {72        if generation == 0 {73            return Err(Error::InvalidInput("Minima SlotId zero generation"));74        }75        Ok(Self {76            collection,77            index,78            generation,79        })80    }8182    pub fn index(self) -> u64 {83        self.index84    }8586    pub fn generation(self) -> u64 {87        self.generation88    }8990    pub fn collection(self) -> CollectionId {91        self.collection92    }93}9495/// Fixed-width stable slots with constant-time allocation and removal.96///97/// Every slot has a 16-byte header: little-endian generation and a word that is98/// either live, retired, or the next free index. The fixed encoded value follows99/// it. Nodes pack `floor(4096 / (16 + T::WIDTH))` slots without straddling.100/// Free-list metadata belongs to the slot layout, never the value encoding.101///102/// Removed slots retain their next generation. Blocks stay allocated until103/// arena retirement, even when every value is removed; this preserves stale104/// address rejection without a second generation index. A slot removed at105/// generation `u64::MAX` retires permanently instead of wrapping. Ordinary Drop106/// retires whole blocks through the collection's rooted allocator authority.107///108/// ```109/// use cdk_rsx_collections_minima::{Arena, SlotArena, Workspace};110/// use cdk_rsx_platform::memory::VecMemory;111/// let mut storage = Arena::format(VecMemory::new()).unwrap();112/// let mut workspace_buffer = cdk_rsx_engine_minima::NodeBuffer::new();113/// let mut workspace = workspace_buffer.workspace();114/// let mut arena = SlotArena::<u64>::new(&mut storage).unwrap();115/// let old = arena.allocate(&mut storage, &7, &mut workspace).unwrap();116/// assert_eq!(arena.remove(&mut storage, old, &mut workspace).unwrap(), Some(7));117/// let current = arena.allocate(&mut storage, &9, &mut workspace).unwrap();118/// assert_eq!(old.index(), current.index());119/// assert_ne!(old.generation(), current.generation());120/// assert_eq!(arena.get(&storage, old, &mut workspace).unwrap(), None);121/// assert_eq!(arena.get(&storage, current, &mut workspace).unwrap(), Some(9));122/// ```123///124/// The slot header must fit beside the value; known invalid widths fail to build:125/// ```compile_fail126/// use cdk_rsx_collections_minima::{Arena, SlotArena};127/// use cdk_rsx_platform::memory::VecMemory;128/// let mut storage = Arena::format(VecMemory::new()).unwrap();129/// let _ = SlotArena::<[u8; 4096]>::new(&mut storage);130/// ```131#[repr(C)]132pub struct SlotArena<T: Fixed> {133    collection: Collection,134    slots: u64,135    len: u64,136    free: u64,137    value: PhantomData<T>,138}139140// SAFETY: only the retained collection directory and scalar metadata are owned.141// Decoded T values and borrowed workspace are never retained in this descriptor.142unsafe impl<T: Fixed> cdk_rsx_engine_nyxus::NyxusData for SlotArena<T> {143    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;144}145146impl<T: Fixed> SlotArena<T> {147    /// Complete fixed-value and collection interpretation contract.148    pub const CONTRACT: [u8; 32] = crate::contract(149        "minima-slot-arena-v1",150        &[],151        &[crate::MINIMA_POLICY, SOURCE_POLICY, T::CONTRACT],152    );153154    pub const SLOT_BYTES: usize = {155        assert!(156            T::WIDTH > 0,157            "Minima SlotArena values must have nonzero width"158        );159        assert!(160            T::WIDTH <= NODE_BYTES - HEADER_BYTES,161            "Minima SlotArena value exceeds a node"162        );163        HEADER_BYTES + T::WIDTH164    };165    pub const SLOTS_PER_NODE: u64 = (NODE_BYTES / Self::SLOT_BYTES) as u64;166167    /// Construct an empty arena without claiming a stable payload block.168    pub fn new(storage: &mut dyn Storage) -> Result<Self> {169        let _ = Self::SLOTS_PER_NODE;170        Ok(Self {171            collection: Collection::new(storage)?,172            slots: 0,173            len: 0,174            free: NONE,175            value: PhantomData,176        })177    }178179    /// Nonowning identity for saving or reconstructing checked slot addresses.180    pub fn identity(&self) -> CollectionId {181        self.collection.identity()182    }183184    pub fn len(&self) -> u64 {185        self.len186    }187188    pub fn is_empty(&self) -> bool {189        self.len == 0190    }191192    /// Number of initialized slots, including free and permanently retired ones.193    pub fn high_water(&self) -> u64 {194        self.slots195    }196197    pub fn block_count(&self) -> usize {198        self.collection.block_count()199    }200201    pub fn allocated_bytes(&self) -> u64 {202        self.block_count() as u64 * BLOCK_BYTES203    }204205    /// Reuse the free-list head or initialize one new slot.206    ///207    /// Reuse reads one 16-byte header and writes one complete slot. Initializing a208    /// new slot reads no payload; crossing block capacity also initializes a new209    /// exclusive 64 KiB block. No allocator scan or per-entry allocation occurs.210    pub fn allocate(211        &mut self,212        storage: &mut dyn Storage,213        value: &T,214        workspace: &mut Workspace,215    ) -> Result<SlotId> {216        let next_len = self.len.checked_add(1).ok_or(Error::Capacity)?;217        let fresh = self.free == NONE;218        let index = if !fresh {219            let index = self.free;220            if index >= self.slots {221                self.collection.validate(storage)?;222                return Err(Error::Corrupt("Minima SlotArena free head"));223            }224            index225        } else {226            if self.slots >= RETIRED {227                self.collection.validate(storage)?;228                return Err(Error::Capacity);229            }230            self.slots231        };232        let (node, at) = position(index, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);233        let address = logical_at(node, at)?;234        let (generation, next_free) = if !fresh {235            self.collection.read_at(236                storage,237                address,238                &mut workspace.bytes_mut()[..HEADER_BYTES],239            )?;240            let (generation, next) = self.header(&workspace.bytes()[..HEADER_BYTES])?;241            if next == LIVE || next == RETIRED {242                return Err(Error::Corrupt("Minima SlotArena free slot"));243            }244            (generation, next)245        } else {246            (1, NONE)247        };248        let nodes = node.checked_add(1).ok_or(Error::Capacity)?;249        let encoded = &mut workspace.bytes_mut()[..Self::SLOT_BYTES];250        encoded[..8].copy_from_slice(&generation.to_le_bytes());251        encoded[8..HEADER_BYTES].copy_from_slice(&LIVE.to_le_bytes());252        value.encode(&mut encoded[HEADER_BYTES..]);253        if fresh && node >= self.collection.node_capacity() {254            self.collection.ensure_nodes(storage, nodes)?;255        }256        self.collection257            .write_at(storage, address, &workspace.bytes()[..Self::SLOT_BYTES])?;258        self.len = next_len;259        if fresh {260            self.slots += 1;261        } else {262            self.free = next_free;263        }264        Ok(SlotId {265            collection: self.collection.identity(),266            index,267            generation,268        })269    }270271    /// Allocate a slice with the same IDs and free-list order as scalar calls.272    ///273    /// All free headers, slot extents and counts are checked before persistent274    /// mutation. Fresh slots need no stable reads. The returned ID vector also275    /// stages the allocation plan; reuse adds one transient index permutation276    /// to reject free-list cycles and group adjacent complete slots per node.277    /// No unrelated slot or node tail is rewritten. Temporary space is bounded278    /// by the input length; provider mutation failures abort for IC rollback.279    pub fn allocate_from_slice(280        &mut self,281        storage: &mut dyn Storage,282        values: &[T],283        workspace: &mut Workspace,284    ) -> Result<Vec<SlotId>> {285        self.collection.validate(storage)?;286        let count = u64::try_from(values.len()).map_err(|_| Error::Capacity)?;287        let next_len = self.len.checked_add(count).ok_or(Error::Capacity)?;288        if values.is_empty() {289            return Ok(Vec::new());290        }291        let collection = self.identity();292        let mut ids = Vec::with_capacity(values.len());293        let mut free = self.free;294        while free != NONE && ids.len() < values.len() {295            if free >= self.slots {296                return Err(Error::Corrupt("Minima SlotArena free head"));297            }298            let (node, at) = position(free, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);299            self.collection.read_at(300                storage,301                logical_at(node, at)?,302                &mut workspace.bytes_mut()[..HEADER_BYTES],303            )?;304            let (generation, next) = self.header(&workspace.bytes()[..HEADER_BYTES])?;305            if next == LIVE || next == RETIRED {306                return Err(Error::Corrupt("Minima SlotArena free slot"));307            }308            ids.push(SlotId {309                collection,310                index: free,311                generation,312            });313            free = next;314        }315        let reused = ids.len();316        let fresh = values.len() - reused;317        let next_slots = self318            .slots319            .checked_add(fresh as u64)320            .filter(|slots| *slots <= RETIRED)321            .ok_or(Error::Capacity)?;322        let mut required_nodes = self.collection.node_capacity();323        if fresh != 0 {324            let (node, at) = position(next_slots - 1, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);325            logical_at(node, at)?326                .checked_add(Self::SLOT_BYTES as u64)327                .ok_or(Error::Capacity)?;328            required_nodes = node.checked_add(1).ok_or(Error::Capacity)?;329            for index in self.slots..next_slots {330                ids.push(SlotId {331                    collection,332                    index,333                    generation: 1,334                });335            }336        }337        // Existing free entries may be in arbitrary order. Sort indices, never338        // the output IDs or their association with the input values.339        let order = if reused != 0 {340            let mut order: Vec<_> = (0..ids.len()).collect();341            order.sort_unstable_by_key(|index| ids[*index].index);342            if order343                .windows(2)344                .any(|pair| ids[pair[0]].index == ids[pair[1]].index)345                || (free != NONE346                    && order347                        .binary_search_by_key(&free, |index| ids[*index].index)348                        .is_ok())349            {350                return Err(Error::Corrupt("Minima SlotArena free cycle"));351            }352            Some(order)353        } else {354            None355        };356        if required_nodes > self.collection.node_capacity() {357            self.collection358                .ensure_nodes(storage, required_nodes)359                .expect("Minima slot batch allocation");360        }361        let input_at = |cursor: usize| order.as_ref().map_or(cursor, |order| order[cursor]);362        let mut cursor = 0;363        while cursor < ids.len() {364            let first = ids[input_at(cursor)].index;365            let (node, at) = position(first, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);366            let remaining = Self::SLOTS_PER_NODE - first % Self::SLOTS_PER_NODE;367            let mut end = cursor + 1;368            while end < ids.len()369                && end - cursor < remaining as usize370                && ids[input_at(end)].index == first + (end - cursor) as u64371            {372                end += 1;373            }374            let bytes = &mut workspace.bytes_mut()[..(end - cursor) * Self::SLOT_BYTES];375            for (input, encoded) in (cursor..end)376                .map(input_at)377                .zip(bytes.chunks_exact_mut(Self::SLOT_BYTES))378            {379                encoded[..8].copy_from_slice(&ids[input].generation.to_le_bytes());380                encoded[8..HEADER_BYTES].copy_from_slice(&LIVE.to_le_bytes());381                values[input].encode(&mut encoded[HEADER_BYTES..]);382            }383            self.collection384                .write_at(385                    storage,386                    logical_at(node, at).expect("preflighted Minima slot address"),387                    bytes,388                )389                .expect("Minima slot batch write");390            cursor = end;391        }392        self.len = next_len;393        self.slots = next_slots;394        self.free = free;395        Ok(ids)396    }397398    /// Check collection, bounds, slot liveness and generation without decoding399    /// the value. A valid slot reads only its 16-byte header, with no workspace.400    pub fn contains(&self, storage: &dyn Storage, id: SlotId) -> Result<bool> {401        if !self.check_address(storage, id)? {402            return Ok(false);403        }404        let (node, at) = position(id.index, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);405        let mut bytes = [0; HEADER_BYTES];406        self.collection407            .read_at(storage, logical_at(node, at)?, &mut bytes)?;408        let (generation, state) = self.header(&bytes)?;409        Ok(state == LIVE && generation == id.generation)410    }411412    /// Read a complete fixed slot once, checking collection, bounds, liveness,413    /// and generation before decoding its value. A stale same-arena address414    /// returns None. The header and value share one provider read.415    pub fn get(416        &self,417        storage: &dyn Storage,418        id: SlotId,419        workspace: &mut Workspace,420    ) -> Result<Option<T>> {421        if !self.check_address(storage, id)? {422            return Ok(None);423        }424        let (node, at) = position(id.index, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);425        self.collection.read_at(426            storage,427            logical_at(node, at)?,428            &mut workspace.bytes_mut()[..Self::SLOT_BYTES],429        )?;430        let bytes = &workspace.bytes()[..Self::SLOT_BYTES];431        let (generation, state) = self.header(&bytes[..HEADER_BYTES])?;432        if state != LIVE || generation != id.generation {433            return Ok(None);434        }435        T::decode(&bytes[HEADER_BYTES..]).map(Some)436    }437438    /// Visit addresses in nondecreasing slot-index order, reading each node439    /// group once. Duplicates are allowed; each address independently checks440    /// its live state and generation, and stale/out-of-bounds addresses visit441    /// `None` just like `get`.442    ///443    /// Foreign owners and invalid ordering reject before payload reads or444    /// visitor calls. The caller controls result storage. Each fetch spans its445    /// first requested slot through its last, bounded by one node, with no446    /// allocation or retained cache. Return false to stop after that visit.447    pub fn get_many(448        &self,449        storage: &dyn Storage,450        ids: &[SlotId],451        mut visit: impl FnMut(SlotId, Option<T>) -> bool,452        workspace: &mut Workspace,453    ) -> Result<usize> {454        if ids455            .iter()456            .any(|id| id.collection != self.collection.identity())457        {458            self.collection.validate(storage)?;459            return Err(Error::InvalidInput("Minima SlotArena foreign owner"));460        }461        if ids.windows(2).any(|pair| pair[0].index > pair[1].index) {462            self.collection.validate(storage)?;463            return Err(Error::InvalidInput(464                "Minima SlotArena addresses must be sorted",465            ));466        }467        self.collection.validate(storage)?;468        let mut cursor = 0;469        while cursor < ids.len() {470            let first = ids[cursor];471            if first.index >= self.slots || first.generation == 0 {472                cursor += 1;473                if !visit(first, None) {474                    return Ok(cursor);475                }476                continue;477            }478            let (node, at) = position(first.index, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);479            let remaining = (Self::SLOTS_PER_NODE - first.index % Self::SLOTS_PER_NODE)480                .min(self.slots - first.index);481            let mut group_end = cursor + 1;482            // Owner/order preflight makes the subtraction nonnegative; the483            // smaller node/high-water extent excludes uninitialized slots.484            while group_end < ids.len() && ids[group_end].index - first.index < remaining {485                group_end += 1;486            }487            let span = (ids[group_end - 1].index - first.index + 1) as usize * Self::SLOT_BYTES;488            self.collection.read_at(489                storage,490                logical_at(node, at)?,491                &mut workspace.bytes_mut()[..span],492            )?;493            let bytes = &workspace.bytes()[..span];494            while cursor < group_end {495                let id = ids[cursor];496                let at = (id.index - first.index) as usize * Self::SLOT_BYTES;497                let slot = &bytes[at..at + Self::SLOT_BYTES];498                let value = if id.generation == 0 {499                    None500                } else {501                    let (generation, state) = self.header(&slot[..HEADER_BYTES])?;502                    if state == LIVE && generation == id.generation {503                        Some(T::decode(&slot[HEADER_BYTES..])?)504                    } else {505                        None506                    }507                };508                cursor += 1;509                if !visit(id, value) {510                    return Ok(cursor);511                }512            }513        }514        Ok(cursor)515    }516517    /// Replace a live value. Returns false for a stale same-arena address.518    pub fn set(519        &mut self,520        storage: &mut dyn Storage,521        id: SlotId,522        value: &T,523        workspace: &mut Workspace,524    ) -> Result<bool> {525        if !self.check_address(storage, id)? {526            return Ok(false);527        }528        let (node, at) = position(id.index, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);529        self.collection.read_at(530            storage,531            logical_at(node, at)?,532            &mut workspace.bytes_mut()[..HEADER_BYTES],533        )?;534        let (generation, state) = self.header(&workspace.bytes()[..HEADER_BYTES])?;535        if state != LIVE || generation != id.generation {536            return Ok(false);537        }538        let address = logical_at(node, at + HEADER_BYTES)?;539        value.encode(&mut workspace.bytes_mut()[..T::WIDTH]);540        self.collection541            .write_at(storage, address, &workspace.bytes()[..T::WIDTH])?;542        Ok(true)543    }544545    /// Remove a live value and link its incremented generation onto the free546    /// list. A saturated generation is permanently retired, never reused.547    pub fn remove(548        &mut self,549        storage: &mut dyn Storage,550        id: SlotId,551        workspace: &mut Workspace,552    ) -> Result<Option<T>> {553        if !self.check_address(storage, id)? {554            return Ok(None);555        }556        let (node, at) = position(id.index, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);557        self.collection.read_at(558            storage,559            logical_at(node, at)?,560            &mut workspace.bytes_mut()[..Self::SLOT_BYTES],561        )?;562        let bytes = &workspace.bytes()[..Self::SLOT_BYTES];563        let (generation, state) = self.header(&bytes[..HEADER_BYTES])?;564        if state != LIVE || generation != id.generation {565            return Ok(None);566        }567        let value = T::decode(&bytes[HEADER_BYTES..])?;568        let (next_generation, next) = if generation == u64::MAX {569            (generation, RETIRED)570        } else {571            (generation + 1, self.free)572        };573        let encoded = &mut workspace.bytes_mut()[..HEADER_BYTES];574        encoded[..8].copy_from_slice(&next_generation.to_le_bytes());575        encoded[8..].copy_from_slice(&next.to_le_bytes());576        self.collection.write_at(577            storage,578            logical_at(node, at)?,579            &workspace.bytes()[..HEADER_BYTES],580        )?;581        self.len -= 1;582        if next != RETIRED {583            self.free = id.index;584        }585        Ok(Some(value))586    }587588    /// Remove a live slot without reading or decoding its value.589    ///590    /// Like `remove`, this checks the collection, provider root, bounds, live591    /// state and generation, then advances the generation and free list. It592    /// reads and writes only the 16-byte slot header and needs no workspace.593    /// The uninterpreted payload is discarded: unlike `remove`, this operation594    /// does not validate its encoded bits or construct a decoded `T`. Fixed595    /// payloads own no stable allocations. A stale same-arena address returns596    /// false; a saturated generation is permanently retired.597    pub fn remove_discard(&mut self, storage: &mut dyn Storage, id: SlotId) -> Result<bool> {598        if !self.check_address(storage, id)? {599            return Ok(false);600        }601        let (node, at) = position(id.index, Self::SLOTS_PER_NODE, Self::SLOT_BYTES);602        let address = logical_at(node, at)?;603        let mut bytes = [0; HEADER_BYTES];604        self.collection.read_at(storage, address, &mut bytes)?;605        let (generation, state) = self.header(&bytes)?;606        if state != LIVE || generation != id.generation {607            return Ok(false);608        }609        let (next_generation, next) = if generation == u64::MAX {610            (generation, RETIRED)611        } else {612            (generation + 1, self.free)613        };614        bytes[..8].copy_from_slice(&next_generation.to_le_bytes());615        bytes[8..].copy_from_slice(&next.to_le_bytes());616        self.collection.write_at(storage, address, &bytes)?;617        self.len -= 1;618        if next != RETIRED {619            self.free = id.index;620        }621        Ok(true)622    }623624    pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {625        self.collection.retire(storage)626    }627628    fn check_address(&self, storage: &dyn Storage, id: SlotId) -> Result<bool> {629        if id.collection != self.collection.identity() {630            self.collection.validate(storage)?;631            return Err(Error::InvalidInput("Minima SlotArena foreign owner"));632        }633        if id.index >= self.slots || id.generation == 0 {634            self.collection.validate(storage)?;635            return Ok(false);636        }637        // Nonempty read_at validates the live owner and block generation before638        // lending any bytes. No extra retained authority borrow is needed here.639        Ok(true)640    }641642    fn header(&self, bytes: &[u8]) -> Result<(u64, u64)> {643        let generation = u64::from_le_bytes(bytes[..8].try_into().unwrap());644        let next = u64::from_le_bytes(bytes[8..HEADER_BYTES].try_into().unwrap());645        if generation == 0646            || (next != LIVE && next != RETIRED && next != NONE && next >= self.slots)647        {648            return Err(Error::Corrupt("Minima SlotArena slot header"));649        }650        Ok((generation, next))651    }652}653654#[cfg(test)]655mod tests {656    use super::*;657    use crate::Arena;658    use cdk_rsx_platform::memory::VecMemory;659660    #[test]661    fn presence_rejects_corrupt_slot_headers() {662        let mut storage = Arena::format(VecMemory::new()).unwrap();663        let mut buffer = crate::NodeBuffer::new();664        let mut workspace = buffer.workspace();665        let mut slots = SlotArena::<u64>::new(&mut storage).unwrap();666        let id = slots.allocate(&mut storage, &7, &mut workspace).unwrap();667        for (generation, state) in [(0u64, LIVE), (1, slots.slots)] {668            let mut bytes = [0; HEADER_BYTES];669            bytes[..8].copy_from_slice(&generation.to_le_bytes());670            bytes[8..].copy_from_slice(&state.to_le_bytes());671            slots.collection.write_at(&mut storage, 0, &bytes).unwrap();672            assert_eq!(673                slots.contains(&storage, id),674                Err(Error::Corrupt("Minima SlotArena slot header"))675            );676            let before = (slots.len, slots.slots, slots.free);677            assert_eq!(678                slots.remove_discard(&mut storage, id),679                Err(Error::Corrupt("Minima SlotArena slot header"))680            );681            assert_eq!((slots.len, slots.slots, slots.free), before);682        }683    }684685    #[test]686    fn batch_free_cycle_rejects_before_mutating_slots_or_counters() {687        let mut storage = Arena::format(VecMemory::new()).unwrap();688        let mut buffer = crate::NodeBuffer::new();689        let mut w = buffer.workspace();690        let mut slots = SlotArena::<u64>::new(&mut storage).unwrap();691        let ids = slots692            .allocate_from_slice(&mut storage, &[1, 2], &mut w)693            .unwrap();694        for id in ids {695            slots.remove(&mut storage, id, &mut w).unwrap();696        }697        slots698            .collection699            .write_at(&mut storage, 8, &1u64.to_le_bytes())700            .unwrap();701        let before = (slots.len, slots.slots, slots.free);702        let mut bytes_before = [0; 48];703        slots704            .collection705            .read_at(&storage, 0, &mut bytes_before)706            .unwrap();707        for values in [&[3, 4][..], &[3, 4, 5][..]] {708            assert_eq!(709                slots.allocate_from_slice(&mut storage, values, &mut w),710                Err(Error::Corrupt("Minima SlotArena free cycle"))711            );712        }713        assert_eq!((slots.len, slots.slots, slots.free), before);714        let mut bytes_after = [0; 48];715        slots716            .collection717            .read_at(&storage, 0, &mut bytes_after)718            .unwrap();719        assert_eq!(bytes_after, bytes_before);720    }721722    #[test]723    fn batch_arithmetic_rejects_before_payload_allocation() {724        let mut storage = Arena::format(VecMemory::new()).unwrap();725        let mut buffer = crate::NodeBuffer::new();726        let mut w = buffer.workspace();727        let mut slots = SlotArena::<u64>::new(&mut storage).unwrap();728        for high_water in [RETIRED, u64::MAX / SlotArena::<u64>::SLOT_BYTES as u64] {729            slots.slots = high_water;730            assert_eq!(731                slots.allocate_from_slice(&mut storage, &[1], &mut w),732                Err(Error::Capacity)733            );734            assert_eq!(slots.slots, high_water);735            assert_eq!(slots.len, 0);736            assert_eq!(slots.block_count(), 0);737        }738        slots.slots = 0;739        slots.len = u64::MAX;740        assert_eq!(741            slots.allocate_from_slice(&mut storage, &[1], &mut w),742            Err(Error::Capacity)743        );744        assert_eq!(storage.root().allocated_blocks(), 0);745    }746747    #[test]748    fn saturated_generation_retires_instead_of_wrapping() {749        let mut storage = Arena::format(VecMemory::new()).unwrap();750        let mut workspace_buffer = cdk_rsx_engine_minima::NodeBuffer::new();751        let mut workspace = workspace_buffer.workspace();752        let mut slots = SlotArena::<u64>::new(&mut storage).unwrap();753        let first = slots.allocate(&mut storage, &7, &mut workspace).unwrap();754        // Model an arena that has reached the final generation. The test writes755        // only through the owning collection and constructs its matching handle.756        slots757            .collection758            .write_at(&mut storage, 0, &u64::MAX.to_le_bytes())759            .unwrap();760        let last = SlotId {761            generation: u64::MAX,762            ..first763        };764        assert_eq!(765            slots.remove(&mut storage, last, &mut workspace).unwrap(),766            Some(7)767        );768        assert!(!slots.contains(&storage, last).unwrap());769        assert_eq!(slots.get(&storage, last, &mut workspace).unwrap(), None);770        let next = slots.allocate(&mut storage, &8, &mut workspace).unwrap();771        assert!(slots.contains(&storage, next).unwrap());772        assert_ne!(last.index(), next.index());773        assert_eq!(next.generation(), 1);774        assert_eq!(slots.high_water(), 2);775        assert_eq!(slots.len(), 1);776    }777778    #[test]779    fn discard_retires_saturated_generations_without_reuse() {780        let mut storage = Arena::format(VecMemory::new()).unwrap();781        let mut buffer = crate::NodeBuffer::new();782        let mut workspace = buffer.workspace();783        let mut slots = SlotArena::<u64>::new(&mut storage).unwrap();784        let first = slots.allocate(&mut storage, &7, &mut workspace).unwrap();785        slots786            .collection787            .write_at(&mut storage, 0, &u64::MAX.to_le_bytes())788            .unwrap();789        let last = SlotId {790            generation: u64::MAX,791            ..first792        };793        assert!(slots.remove_discard(&mut storage, last).unwrap());794        assert!(!slots.remove_discard(&mut storage, last).unwrap());795        assert_eq!(slots.len(), 0);796        let next = slots.allocate(&mut storage, &8, &mut workspace).unwrap();797        assert_eq!((next.index(), next.generation()), (1, 1));798        assert_eq!(slots.get(&storage, last, &mut workspace).unwrap(), None);799        assert_eq!(slots.get(&storage, next, &mut workspace).unwrap(), Some(8));800    }801802    #[test]803    fn discard_does_not_decode_payload_but_ordinary_remove_still_validates_it() {804        let mut storage = Arena::format(VecMemory::new()).unwrap();805        let mut buffer = crate::NodeBuffer::new();806        let mut workspace = buffer.workspace();807        let mut slots = SlotArena::<bool>::new(&mut storage).unwrap();808        let id = slots.allocate(&mut storage, &true, &mut workspace).unwrap();809        slots810            .collection811            .write_at(&mut storage, HEADER_BYTES as u64, &[2])812            .unwrap();813        let before = (slots.len, slots.slots, slots.free);814        assert_eq!(815            slots.remove(&mut storage, id, &mut workspace),816            Err(Error::Corrupt("fixed bool"))817        );818        assert_eq!((slots.len, slots.slots, slots.free), before);819        assert!(slots.remove_discard(&mut storage, id).unwrap());820        assert_eq!(slots.len(), 0);821        let next = slots822            .allocate(&mut storage, &false, &mut workspace)823            .unwrap();824        assert_eq!((next.index(), next.generation()), (id.index(), 2));825        assert_eq!(826            slots.get(&storage, next, &mut workspace).unwrap(),827            Some(false)828        );829    }830}