map.rs

cdk-rsx/crates/cdk-rsx-collections/src/hylix/map.rs

map.rs1,325 lines← SDK documentation
1//! An ordered B-tree with bounded initialized nodes and packed live records.2//!3//! Nodes are ordinary allocations from the shared stable arena, not Store4//! objects. The initialized prefix holds a header, contiguous live keys, live5//! values, then branch-only child identities. One scoped read obtains a node;6//! mutations move packed planes without decoding unchanged owners. Retirement7//! and bulk conversion decode the owners they consume. Spare allocation bytes8//! never contain live owners and are neither decoded nor rewritten.9use super::{Edit, Read, must};10use cdk_rsx_engine_hylix::{11    Block, Codec, Error, HylixValue, Result, Storage, with_storage, with_storage_read,12};13use core::{14    cmp::Ordering,15    marker::PhantomData,16    ops::{Bound, RangeBounds},17};1819#[path = "map_build.rs"]20pub(super) mod build;2122#[cfg(test)]23#[path = "map_decode_tests.rs"]24mod decode_tests;2526const NODE_HEADER: usize = 8;27// Leave room for the arena's 16-byte allocation header in a single initialized28// 4KiB combined read. Very large row codecs still use a three-key minimum.29const TARGET_NODE: usize = 4096 - 16;3031/// Key ordering may read an immutable stable payload through the already32/// borrowed provider. It must not reenter the scoped storage context.33pub trait Key<Q: ?Sized = Self>: HylixValue {34    fn compare(&self, other: &Q, storage: &dyn Storage) -> Ordering;35}36impl<T: HylixValue + Ord> Key<T> for T {37    fn compare(&self, other: &T, _: &dyn Storage) -> Ordering {38        self.cmp(other)39    }40}4142/// A unique owning B-tree carrier. Its root and count are part of its owner's43/// fixed record and change through that owner's write guard.44pub struct Map<K: HylixValue, V: HylixValue> {45    root: Block,46    len: u64,47    marker: PhantomData<fn() -> (K, V)>,48}49struct EncodedNode {50    bytes: std::vec::Vec<u8>,51    count: usize,52    leaf: bool,53}54struct Insertion {55    block: Block,56    node: EncodedNode,57    index: usize,58}59struct Promotion {60    entry: std::vec::Vec<u8>,61    right: Block,62}63struct Node<K, V> {64    entries: std::vec::Vec<(K, V)>,65    children: std::vec::Vec<Block>,66}67impl<K, V> Node<K, V> {68    fn leaf() -> Self {69        Self {70            entries: std::vec::Vec::new(),71            children: std::vec::Vec::new(),72        }73    }74    fn is_leaf(&self) -> bool {75        self.children.is_empty()76    }77}7879impl<K: HylixValue, V: HylixValue> Default for Map<K, V> {80    fn default() -> Self {81        Self::new()82    }83}84impl<K: HylixValue, V: HylixValue> Map<K, V> {85    const CAPACITY: usize = {86        let entry = K::SIZE87            .checked_add(V::SIZE)88            .expect("stable map record overflow")89            .checked_add(Block::SIZE)90            .expect("stable map record overflow");91        let ideal = (TARGET_NODE - NODE_HEADER - Block::SIZE) / entry;92        let bounded = if ideal < 3 {93            394        } else if ideal > 31 {95            3196        } else {97            ideal98        };99        if bounded % 2 == 0 {100            bounded - 1101        } else {102            bounded103        }104    };105    const DEGREE: usize = (Self::CAPACITY + 1) / 2;106    const NODE_SIZE: usize =107        NODE_HEADER + Self::CAPACITY * (K::SIZE + V::SIZE) + (Self::CAPACITY + 1) * Block::SIZE;108109    pub const fn new() -> Self {110        Self {111            root: Block::NULL,112            len: 0,113            marker: PhantomData,114        }115    }116    pub fn len(&self) -> usize {117        usize::try_from(self.len).expect("stable map length exceeds usize")118    }119    pub fn is_empty(&self) -> bool {120        self.len == 0121    }122    /// Compiled node geometry for workload/source receipts.123    pub const fn node_bytes() -> usize {124        Self::NODE_SIZE125    }126    pub const fn node_keys() -> usize {127        Self::CAPACITY128    }129130    fn read_encoded(storage: &dyn Storage, block: Block) -> Result<EncodedNode> {131        let mut encoded = None;132        storage.read_with(block, 0, Self::NODE_SIZE, &mut |bytes| {133            let (count, leaf) = Self::header(bytes)?;134            encoded = Some(EncodedNode {135                bytes: bytes[..Self::encoded_size(count, leaf)].to_vec(),136                count,137                leaf,138            });139            Ok(())140        })?;141        Ok(encoded.expect("Storage::read_with must call its visitor"))142    }143    fn header(bytes: &[u8]) -> Result<(usize, bool)> {144        let count = u16::from_le_bytes(bytes[..2].try_into().unwrap()) as usize;145        if count > Self::CAPACITY || bytes[2] > 1 {146            return Err(Error::Corrupt("stable map node"));147        }148        Ok((count, bytes[2] == 1))149    }150    fn encoded_size(count: usize, leaf: bool) -> usize {151        Self::children_at(count) + if leaf { 0 } else { (count + 1) * Block::SIZE }152    }153    fn key_offset(index: usize) -> usize {154        NODE_HEADER + index * K::SIZE155    }156    fn value_offset(count: usize, index: usize) -> usize {157        NODE_HEADER + count * K::SIZE + index * V::SIZE158    }159    fn children_at(count: usize) -> usize {160        NODE_HEADER + count * (K::SIZE + V::SIZE)161    }162    fn key_in(bytes: &[u8], index: usize) -> Result<K> {163        let at = Self::key_offset(index);164        K::decode(&bytes[at..at + K::SIZE])165    }166    fn key_at(node: &EncodedNode, index: usize) -> Result<K> {167        Self::key_in(&node.bytes, index)168    }169    fn value_in(bytes: &[u8], count: usize, index: usize) -> Result<V> {170        let at = Self::value_offset(count, index);171        V::decode(&bytes[at..at + V::SIZE])172    }173    fn value_at(node: &EncodedNode, index: usize) -> Result<V> {174        Self::value_in(&node.bytes, node.count, index)175    }176    fn child_in(bytes: &[u8], count: usize, leaf: bool, index: usize) -> Result<Option<Block>> {177        if leaf {178            return Ok(None);179        }180        let at = Self::children_at(count) + index * Block::SIZE;181        let child = Block::decode(&bytes[at..at + Block::SIZE])?;182        if child.is_null() {183            return Err(Error::Corrupt("stable map child"));184        }185        Ok(Some(child))186    }187    fn child_at(node: &EncodedNode, index: usize) -> Result<Option<Block>> {188        Self::child_in(&node.bytes, node.count, node.leaf, index)189    }190    fn search_in(191        bytes: &[u8],192        count: usize,193        compare: &impl Fn(&K) -> Ordering,194    ) -> Result<core::result::Result<usize, usize>> {195        let (mut low, mut high) = (0, count);196        while low < high {197            let middle = low + (high - low) / 2;198            match compare(&Self::key_in(bytes, middle)?) {199                Ordering::Less => low = middle + 1,200                Ordering::Greater => high = middle,201                Ordering::Equal => return Ok(Ok(middle)),202            }203        }204        Ok(Err(low))205    }206    fn search(207        node: &EncodedNode,208        compare: &impl Fn(&K) -> Ordering,209    ) -> Result<core::result::Result<usize, usize>> {210        Self::search_in(&node.bytes, node.count, compare)211    }212    fn read_node(storage: &dyn Storage, block: Block) -> Result<Node<K, V>> {213        let mut node = None;214        storage.read_with(block, 0, Self::NODE_SIZE, &mut |bytes| {215            let (count, leaf) = Self::header(bytes)?;216            node = Some(Self::decode_node(bytes, count, leaf)?);217            Ok(())218        })?;219        Ok(node.expect("Storage::read_with must call its visitor"))220    }221    fn decode_node(bytes: &[u8], count: usize, leaf: bool) -> Result<Node<K, V>> {222        let mut node = Node {223            entries: std::vec::Vec::with_capacity(count),224            children: std::vec::Vec::with_capacity(if leaf { 0 } else { count + 1 }),225        };226        if !leaf {227            for index in 0..=count {228                node.children229                    .push(Self::child_in(bytes, count, leaf, index)?.unwrap());230            }231        }232        for index in 0..count {233            node.entries.push((234                Self::key_in(bytes, index)?,235                Self::value_in(bytes, count, index)?,236            ));237        }238        Ok(node)239    }240    fn write_node(storage: &mut dyn Storage, block: Block, node: &Node<K, V>) -> Result<()> {241        assert!(node.entries.len() <= Self::CAPACITY);242        assert!(node.is_leaf() || node.children.len() == node.entries.len() + 1);243        let count = node.entries.len();244        let mut bytes = std::vec![0; Self::encoded_size(count, node.is_leaf())];245        bytes[..2].copy_from_slice(&(count as u16).to_le_bytes());246        bytes[2] = u8::from(node.is_leaf());247        for (i, child) in node.children.iter().enumerate() {248            let at = Self::children_at(count) + i * Block::SIZE;249            child.encode(&mut bytes[at..at + Block::SIZE]);250        }251        for (i, (key, value)) in node.entries.iter().enumerate() {252            let key_at = Self::key_offset(i);253            let value_at = Self::value_offset(count, i);254            key.encode(&mut bytes[key_at..key_at + K::SIZE]);255            value.encode(&mut bytes[value_at..value_at + V::SIZE]);256        }257        storage.write(block, 0, &bytes)258    }259    fn allocate_node(storage: &mut dyn Storage, node: &Node<K, V>) -> Result<Block> {260        let block = storage.allocate(Self::NODE_SIZE as u64)?;261        Self::write_node(storage, block, node)?;262        Ok(block)263    }264    fn empty_encoded(leaf: bool) -> EncodedNode {265        let mut node = EncodedNode {266            bytes: std::vec![0; Self::encoded_size(0, leaf)],267            count: 0,268            leaf,269        };270        node.bytes[2] = u8::from(leaf);271        node272    }273    fn write_encoded(storage: &mut dyn Storage, block: Block, node: &EncodedNode) -> Result<()> {274        debug_assert!(node.count <= Self::CAPACITY);275        debug_assert_eq!(node.bytes.len(), Self::encoded_size(node.count, node.leaf));276        storage.write(block, 0, &node.bytes)277    }278    fn allocate_encoded(storage: &mut dyn Storage, node: &EncodedNode) -> Result<Block> {279        let block = storage.allocate(Self::NODE_SIZE as u64)?;280        Self::write_encoded(storage, block, node)?;281        Ok(block)282    }283    /// Open one entry and, for branches, its right-child slot. Move the later284    /// planes first: their count-dependent destinations overlap the old planes.285    /// Encoded copies transfer existing owners without retain/retire or decoding.286    fn open_entry(node: &mut EncodedNode, index: usize) {287        let old = node.count;288        // One extra entry exists only in the transient workspace, immediately289        // before bottom-up splitting. Persisted nodes never exceed CAPACITY.290        assert!(old <= Self::CAPACITY && index <= old);291        let count = old + 1;292        node.bytes.resize(Self::encoded_size(count, node.leaf), 0);293        if !node.leaf {294            let from = Self::children_at(old);295            let to = Self::children_at(count);296            node.bytes.copy_within(297                from + (index + 1) * Block::SIZE..from + (old + 1) * Block::SIZE,298                to + (index + 2) * Block::SIZE,299            );300            node.bytes301                .copy_within(from..from + (index + 1) * Block::SIZE, to);302        }303        let from = Self::value_offset(old, 0);304        let to = Self::value_offset(count, 0);305        node.bytes.copy_within(306            from + index * V::SIZE..from + old * V::SIZE,307            to + (index + 1) * V::SIZE,308        );309        node.bytes.copy_within(from..from + index * V::SIZE, to);310        node.bytes.copy_within(311            Self::key_offset(index)..Self::key_offset(old),312            Self::key_offset(index + 1),313        );314        node.count = count;315        node.bytes[..2].copy_from_slice(&(count as u16).to_le_bytes());316    }317    fn encode_entry(node: &mut EncodedNode, index: usize, key: &K, value: &V) {318        let at = Self::key_offset(index);319        node.bytes[at..at + K::SIZE].fill(0);320        key.encode(&mut node.bytes[at..at + K::SIZE]);321        let at = Self::value_offset(node.count, index);322        node.bytes[at..at + V::SIZE].fill(0);323        value.encode(&mut node.bytes[at..at + V::SIZE]);324    }325    /// Keep an initialized prefix of entries after a split. Removed bytes no326    /// longer represent owners; their exact encodings already moved elsewhere.327    fn truncate_encoded(node: &mut EncodedNode, count: usize) {328        assert!(count <= node.count);329        let from = Self::value_offset(node.count, 0);330        let to = Self::value_offset(count, 0);331        node.bytes.copy_within(from..from + count * V::SIZE, to);332        if !node.leaf {333            let from = Self::children_at(node.count);334            let to = Self::children_at(count);335            node.bytes336                .copy_within(from..from + (count + 1) * Block::SIZE, to);337        }338        node.count = count;339        node.bytes.truncate(Self::encoded_size(count, node.leaf));340        node.bytes[..2].copy_from_slice(&(count as u16).to_le_bytes());341    }342    /// Removal used to decode every child identity with its owners. Preserve343    /// that validation before moving a branch, without materializing its rows.344    fn read_remove_node(storage: &dyn Storage, block: Block) -> Result<EncodedNode> {345        let node = Self::read_encoded(storage, block)?;346        if !node.leaf {347            for index in 0..=node.count {348                Self::child_at(&node, index)?;349            }350        }351        Ok(node)352    }353    fn copy_entry(source: &EncodedNode, from: usize, target: &mut EncodedNode, to: usize) {354        let source_at = Self::key_offset(from);355        let target_at = Self::key_offset(to);356        target.bytes[target_at..target_at + K::SIZE]357            .copy_from_slice(&source.bytes[source_at..source_at + K::SIZE]);358        let source_at = Self::value_offset(source.count, from);359        let target_at = Self::value_offset(target.count, to);360        target.bytes[target_at..target_at + V::SIZE]361            .copy_from_slice(&source.bytes[source_at..source_at + V::SIZE]);362    }363    fn copy_child(source: &EncodedNode, from: usize, target: &mut EncodedNode, to: usize) {364        let source_at = Self::children_at(source.count) + from * Block::SIZE;365        let target_at = Self::children_at(target.count) + to * Block::SIZE;366        target.bytes[target_at..target_at + Block::SIZE]367            .copy_from_slice(&source.bytes[source_at..source_at + Block::SIZE]);368    }369    /// Close an entry and one branch child. Shrinking moves the earlier planes370    /// first, so their old source bytes cannot be overwritten by the next plane.371    /// The removed owner has already moved to its destination or return value.372    fn close_entry(node: &mut EncodedNode, index: usize, child: usize) {373        let old = node.count;374        assert!(index < old && (node.leaf || child <= old));375        let count = old - 1;376        node.bytes.copy_within(377            Self::key_offset(index + 1)..Self::key_offset(old),378            Self::key_offset(index),379        );380        let from = Self::value_offset(old, 0);381        let to = Self::value_offset(count, 0);382        node.bytes.copy_within(from..from + index * V::SIZE, to);383        node.bytes.copy_within(384            from + (index + 1) * V::SIZE..from + old * V::SIZE,385            to + index * V::SIZE,386        );387        if !node.leaf {388            let from = Self::children_at(old);389            let to = Self::children_at(count);390            node.bytes.copy_within(from..from + child * Block::SIZE, to);391            node.bytes.copy_within(392                from + (child + 1) * Block::SIZE..from + (old + 1) * Block::SIZE,393                to + child * Block::SIZE,394            );395        }396        node.count = count;397        node.bytes.truncate(Self::encoded_size(count, node.leaf));398        node.bytes[..2].copy_from_slice(&(count as u16).to_le_bytes());399    }400    /// Append a separator and its right sibling to a left node. The children401    /// and values move outward before extending keys into their former bytes.402    fn merge_encoded(403        left: &mut EncodedNode,404        parent: &EncodedNode,405        index: usize,406        right: &EncodedNode,407    ) {408        let old = left.count;409        let count = old + 1 + right.count;410        assert!(count <= Self::CAPACITY && left.leaf == right.leaf);411        left.bytes.resize(Self::encoded_size(count, left.leaf), 0);412        if !left.leaf {413            let from = Self::children_at(old);414            let to = Self::children_at(count);415            left.bytes416                .copy_within(from..from + (old + 1) * Block::SIZE, to);417            let from = Self::children_at(right.count);418            let to = to + (old + 1) * Block::SIZE;419            left.bytes[to..to + (right.count + 1) * Block::SIZE]420                .copy_from_slice(&right.bytes[from..]);421        }422        let from = Self::value_offset(old, 0);423        let to = Self::value_offset(count, 0);424        left.bytes.copy_within(from..from + old * V::SIZE, to);425        let from = Self::value_offset(right.count, 0);426        let to = Self::value_offset(count, old + 1);427        left.bytes[to..to + right.count * V::SIZE]428            .copy_from_slice(&right.bytes[from..from + right.count * V::SIZE]);429        let to = Self::key_offset(old + 1);430        left.bytes[to..to + right.count * K::SIZE]431            .copy_from_slice(&right.bytes[NODE_HEADER..Self::key_offset(right.count)]);432        left.count = count;433        left.bytes[..2].copy_from_slice(&(count as u16).to_le_bytes());434        Self::copy_entry(parent, index, left, old);435    }436    fn locate_by(437        &self,438        storage: &dyn Storage,439        compare: &impl Fn(&K) -> Ordering,440    ) -> Result<Option<(V, Block, u64)>> {441        Self::locate_from(storage, self.root, compare)442    }443    fn locate_from(444        storage: &dyn Storage,445        mut block: Block,446        compare: &impl Fn(&K) -> Ordering,447    ) -> Result<Option<(V, Block, u64)>> {448        while !block.is_null() {449            let mut found = None;450            let mut next = Block::NULL;451            storage.read_with(block, 0, Self::NODE_SIZE, &mut |bytes| {452                let (count, leaf) = Self::header(bytes)?;453                match Self::search_in(bytes, count, compare)? {454                    Ok(index) => {455                        found = Some((456                            Self::value_in(bytes, count, index)?,457                            block,458                            Self::value_offset(count, index) as u64,459                        ))460                    }461                    Err(index) => {462                        next = Self::child_in(bytes, count, leaf, index)?.unwrap_or(Block::NULL)463                    }464                }465                Ok(())466            })?;467            if found.is_some() {468                return Ok(found);469            }470            block = next;471        }472        Ok(None)473    }474    fn contains_from(475        storage: &dyn Storage,476        mut block: Block,477        compare: &impl Fn(&K) -> Ordering,478    ) -> Result<bool> {479        // Keep the normal value-read path independent of presence specialization.480        // Header, key search and child validation still use the same primitives.481        while !block.is_null() {482            let mut found = false;483            let mut next = Block::NULL;484            storage.read_with(block, 0, Self::NODE_SIZE, &mut |bytes| {485                let (count, leaf) = Self::header(bytes)?;486                match Self::search_in(bytes, count, compare)? {487                    Ok(_) => found = true,488                    Err(index) => {489                        next = Self::child_in(bytes, count, leaf, index)?.unwrap_or(Block::NULL)490                    }491                }492                Ok(())493            })?;494            if found {495                return Ok(true);496            }497            block = next;498        }499        Ok(false)500    }501    /// Test primary identity with a comparison, without decoding the value.502    /// Node headers, search keys and child identities are still validated.503    /// An explicit value read is required to validate value codec bytes.504    pub fn contains_by(&self, compare: impl Fn(&K) -> Ordering) -> bool {505        must(with_storage_read(|storage| {506            Self::contains_from(storage, self.root, &compare)507        }))508    }509    pub fn get_by(&self, compare: impl Fn(&K) -> Ordering) -> Option<Read<'_, V>> {510        must(with_storage_read(|storage| {511            self.locate_by(storage, &compare)512        }))513        .map(|(value, _, _)| Read::new(value))514    }515    pub fn get_mut_by(&mut self, compare: impl Fn(&K) -> Ordering) -> Option<Edit<'_, V>> {516        must(with_storage_read(|storage| {517            self.locate_by(storage, &compare)518        }))519        .map(|(value, block, at)| Edit::new(value, block, at))520    }521    pub fn clear(&mut self) {522        must(with_storage(|storage| {523            Self::retire_tree(storage, self.root)524        }));525        self.root = Block::NULL;526        self.len = 0;527    }528    fn retire_tree(storage: &mut dyn Storage, block: Block) -> Result<()> {529        if block.is_null() {530            return Ok(());531        }532        let node = Self::read_node(storage, block)?;533        for child in node.children {534            Self::retire_tree(storage, child)?;535        }536        for (key, value) in node.entries {537            key.retire(storage)?;538            value.retire(storage)?;539        }540        storage.deallocate(block)541    }542    pub fn iter(&self) -> Iter<'_, K, V> {543        Iter::new(self)544    }545    pub fn keys(&self) -> impl Iterator<Item = Read<'_, K>> {546        self.iter().map(|(key, _)| key)547    }548    pub fn values(&self) -> impl Iterator<Item = Read<'_, V>> {549        self.iter().map(|(_, value)| value)550    }551}552553impl<K: HylixValue, V: HylixValue> Map<K, V> {554    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<Read<'_, V>>555    where556        K: Key<Q>,557    {558        must(with_storage_read(|storage| {559            self.locate_by(storage, &|saved| saved.compare(key, storage))560        }))561        .map(|(value, _, _)| Read::new(value))562    }563    pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<Edit<'_, V>>564    where565        K: Key<Q>,566    {567        must(with_storage_read(|storage| {568            self.locate_by(storage, &|saved| saved.compare(key, storage))569        }))570        .map(|(value, block, at)| Edit::new(value, block, at))571    }572    pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool573    where574        K: Key<Q>,575    {576        self.get(key).is_some()577    }578}579impl<K: Key<K>, V: HylixValue> Map<K, V> {580    pub fn insert(&mut self, key: K, value: V) -> Option<V> {581        must(with_storage(|storage| self.insert_in(storage, key, value)))582    }583    fn insert_in(&mut self, storage: &mut dyn Storage, key: K, value: V) -> Result<Option<V>> {584        if self.root.is_null() {585            let mut node = Self::empty_encoded(true);586            Self::open_entry(&mut node, 0);587            Self::encode_entry(&mut node, 0, &key, &value);588            self.root = Self::allocate_encoded(storage, &node)?;589            self.len = 1;590            return Ok(None);591        }592        let mut path = std::vec::Vec::new();593        let mut existing = None;594        Self::insertion_path(storage, self.root, &key, &mut path, &mut existing)?;595        if let Some((old, block, at)) = existing {596            key.retire(storage)?;597            cdk_rsx_engine_hylix::write_value(storage, block, at, &value)?;598            return Ok(Some(old));599        }600        let len = self.len.checked_add(1).ok_or(Error::Overflow)?;601        let mut promotion: Option<Promotion> = None;602        // The read-only search retained the leaf and only the ancestors that603        // must receive a split. Every provider loan has ended before mutation.604        for Insertion {605            block,606            mut node,607            index,608        } in path609        {610            Self::open_entry(&mut node, index);611            if let Some(promoted) = promotion.take() {612                Self::place_promotion(&mut node, index, &promoted);613            } else {614                debug_assert!(node.leaf);615                Self::encode_entry(&mut node, index, &key, &value);616            }617            if node.count <= Self::CAPACITY {618                Self::write_encoded(storage, block, &node)?;619                self.len = len;620                return Ok(None);621            }622            promotion = Some(Self::split_overflow(storage, block, node)?);623        }624        let promoted = promotion.expect("a split above the original root needs a new root");625        let mut root = Self::empty_encoded(false);626        self.root627            .encode(&mut root.bytes[NODE_HEADER..NODE_HEADER + Block::SIZE]);628        Self::open_entry(&mut root, 0);629        Self::place_promotion(&mut root, 0, &promoted);630        self.root = Self::allocate_encoded(storage, &root)?;631        self.len = len;632        Ok(None)633    }634635    /// Search each node once. On a miss, copy the leaf and then the necessary636    /// split suffix while unwinding still-valid immutable provider loans. A637    /// nonfull node absorbs its child's split, so higher ancestors need no copy.638    /// A replacement copies no node and leaves `path` allocation-free.639    fn insertion_path(640        storage: &dyn Storage,641        block: Block,642        key: &K,643        path: &mut std::vec::Vec<Insertion>,644        existing: &mut Option<(V, Block, u64)>,645    ) -> Result<()> {646        // The displaced value has one caller-owned slot, even for a very wide647        // codec; recursive search frames carry only its mutable reference.648        storage.read_with(block, 0, Self::NODE_SIZE, &mut |bytes| {649            let (count, leaf) = Self::header(bytes)?;650            let index = match Self::search_in(bytes, count, &|saved| saved.compare(key, storage))? {651                Ok(index) => {652                    *existing = Some((653                        Self::value_in(bytes, count, index)?,654                        block,655                        Self::value_offset(count, index) as u64,656                    ));657                    return Ok(());658                }659                Err(index) => index,660            };661            if let Some(child) = Self::child_in(bytes, count, leaf, index)? {662                Self::insertion_path(storage, child, key, path, existing)?;663            }664            if existing.is_none()665                && path666                    .last()667                    .is_none_or(|entry| entry.node.count == Self::CAPACITY)668            {669                path.push(Insertion {670                    block,671                    index,672                    node: EncodedNode {673                        bytes: bytes[..Self::encoded_size(count, leaf)].to_vec(),674                        count,675                        leaf,676                    },677                });678            }679            Ok(())680        })681    }682683    fn place_promotion(node: &mut EncodedNode, index: usize, promoted: &Promotion) {684        let at = Self::key_offset(index);685        node.bytes[at..at + K::SIZE].copy_from_slice(&promoted.entry[..K::SIZE]);686        let at = Self::value_offset(node.count, index);687        node.bytes[at..at + V::SIZE].copy_from_slice(&promoted.entry[K::SIZE..]);688        let at = Self::children_at(node.count) + (index + 1) * Block::SIZE;689        promoted.right.encode(&mut node.bytes[at..at + Block::SIZE]);690    }691692    fn split_overflow(693        storage: &mut dyn Storage,694        block: Block,695        mut left: EncodedNode,696    ) -> Result<Promotion> {697        debug_assert_eq!(left.count, Self::CAPACITY + 1);698        let middle = Self::DEGREE;699        let right_count = left.count - middle - 1;700        let mut right = Self::empty_encoded(left.leaf);701        right702            .bytes703            .resize(Self::encoded_size(right_count, left.leaf), 0);704        right.count = right_count;705        right.bytes[..2].copy_from_slice(&(right_count as u16).to_le_bytes());706        right.bytes[NODE_HEADER..Self::key_offset(right_count)].copy_from_slice(707            &left.bytes[Self::key_offset(middle + 1)..Self::key_offset(left.count)],708        );709        let from = Self::value_offset(left.count, middle + 1);710        let to = Self::value_offset(right_count, 0);711        right.bytes[to..to + right_count * V::SIZE]712            .copy_from_slice(&left.bytes[from..from + right_count * V::SIZE]);713        if !left.leaf {714            let from = Self::children_at(left.count) + (middle + 1) * Block::SIZE;715            let to = Self::children_at(right_count);716            right.bytes[to..].copy_from_slice(&left.bytes[from..]);717        }718        let mut entry = std::vec![0; K::SIZE + V::SIZE];719        let from = Self::key_offset(middle);720        entry[..K::SIZE].copy_from_slice(&left.bytes[from..from + K::SIZE]);721        let from = Self::value_offset(left.count, middle);722        entry[K::SIZE..].copy_from_slice(&left.bytes[from..from + V::SIZE]);723        let right = Self::allocate_encoded(storage, &right)?;724        Self::truncate_encoded(&mut left, middle);725        Self::write_encoded(storage, block, &left)?;726        Ok(Promotion { entry, right })727    }728    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>729    where730        K: Key<Q>,731    {732        self.remove_entry(key).map(|(key, value)| {733            must(with_storage(|storage| key.retire(storage)));734            value735        })736    }737    pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>738    where739        K: Key<Q>,740    {741        must(with_storage(|storage| {742            if self.root.is_null() {743                return Ok(None);744            }745            let mut root = Self::read_remove_node(storage, self.root)?;746            let removed = Self::remove_from(storage, self.root, &mut root, key)?;747            self.collapse_root(storage, &root)?;748            if removed.is_some() {749                self.len -= 1;750            }751            Ok(removed)752        }))753    }754    fn collapse_root(&mut self, storage: &mut dyn Storage, root: &EncodedNode) -> Result<()> {755        if root.count == 0 {756            let old = self.root;757            self.root = Self::child_at(root, 0)?.unwrap_or(Block::NULL);758            storage.deallocate(old)?;759        }760        Ok(())761    }762    fn remove_from<Q: ?Sized>(763        storage: &mut dyn Storage,764        block: Block,765        node: &mut EncodedNode,766        key: &Q,767    ) -> Result<Option<(K, V)>>768    where769        K: Key<Q>,770    {771        match Self::search(node, &|saved| saved.compare(key, storage))? {772            Ok(index) if node.leaf => {773                let removed = (Self::key_at(node, index)?, Self::value_at(node, index)?);774                Self::close_entry(node, index, index + 1);775                Self::write_encoded(storage, block, node)?;776                Ok(Some(removed))777            }778            Ok(index) => {779                let left_block = Self::child_at(node, index)?.unwrap();780                let mut left = Self::read_remove_node(storage, left_block)?;781                if left.count >= Self::DEGREE {782                    let removed = (Self::key_at(node, index)?, Self::value_at(node, index)?);783                    Self::take_edge(storage, left_block, &mut left, false, &mut |edge, at| {784                        Self::copy_entry(edge, at, node, index);785                        Ok(())786                    })?;787                    Self::write_encoded(storage, block, node)?;788                    return Ok(Some(removed));789                }790                let right_block = Self::child_at(node, index + 1)?.unwrap();791                let mut right = Self::read_remove_node(storage, right_block)?;792                if right.count >= Self::DEGREE {793                    let removed = (Self::key_at(node, index)?, Self::value_at(node, index)?);794                    Self::take_edge(storage, right_block, &mut right, true, &mut |edge, at| {795                        Self::copy_entry(edge, at, node, index);796                        Ok(())797                    })?;798                    Self::write_encoded(storage, block, node)?;799                    return Ok(Some(removed));800                }801                Self::merge_encoded(&mut left, node, index, &right);802                Self::close_entry(node, index, index + 1);803                Self::write_encoded(storage, left_block, &left)?;804                Self::write_encoded(storage, block, node)?;805                storage.deallocate(right_block)?;806                Self::remove_from(storage, left_block, &mut left, key)807            }808            Err(_) if node.leaf => Ok(None),809            Err(index) => {810                let child = Self::read_remove_node(storage, Self::child_at(node, index)?.unwrap())?;811                let (child_block, mut child) =812                    Self::strengthen_child(storage, block, node, index, child)?;813                Self::remove_from(storage, child_block, &mut child, key)814            }815        }816    }817    /// Before descent, give a minimum-sized child an extra entry by rotation or818    /// merging. Exact encodings move between the already initialized workspaces.819    fn strengthen_child(820        storage: &mut dyn Storage,821        parent_block: Block,822        parent: &mut EncodedNode,823        index: usize,824        mut child: EncodedNode,825    ) -> Result<(Block, EncodedNode)> {826        let child_block = Self::child_at(parent, index)?.unwrap();827        if child.count >= Self::DEGREE {828            return Ok((child_block, child));829        }830        let left = if index > 0 {831            let left_block = Self::child_at(parent, index - 1)?.unwrap();832            let mut left = Self::read_remove_node(storage, left_block)?;833            if left.count >= Self::DEGREE {834                Self::open_entry(&mut child, 0);835                Self::copy_entry(parent, index - 1, &mut child, 0);836                Self::copy_entry(&left, left.count - 1, parent, index - 1);837                if !left.leaf {838                    // open_entry leaves child zero in place and opens child839                    // one; a left rotation instead prepends the moved child.840                    let at = Self::children_at(child.count);841                    child842                        .bytes843                        .copy_within(at..at + Block::SIZE, at + Block::SIZE);844                    Self::copy_child(&left, left.count, &mut child, 0);845                }846                let last = left.count - 1;847                Self::close_entry(&mut left, last, last + 1);848                Self::write_encoded(storage, left_block, &left)?;849                Self::write_encoded(storage, child_block, &child)?;850                Self::write_encoded(storage, parent_block, parent)?;851                return Ok((child_block, child));852            }853            Some((left_block, left))854        } else {855            None856        };857        let right = if index < parent.count {858            let right_block = Self::child_at(parent, index + 1)?.unwrap();859            let mut right = Self::read_remove_node(storage, right_block)?;860            if right.count >= Self::DEGREE {861                let last = child.count;862                Self::open_entry(&mut child, last);863                Self::copy_entry(parent, index, &mut child, last);864                Self::copy_entry(&right, 0, parent, index);865                if !right.leaf {866                    Self::copy_child(&right, 0, &mut child, last + 1);867                }868                Self::close_entry(&mut right, 0, 0);869                Self::write_encoded(storage, right_block, &right)?;870                Self::write_encoded(storage, child_block, &child)?;871                Self::write_encoded(storage, parent_block, parent)?;872                return Ok((child_block, child));873            }874            Some((right_block, right))875        } else {876            None877        };878        if let Some((left_block, mut left)) = left {879            Self::merge_encoded(&mut left, parent, index - 1, &child);880            Self::close_entry(parent, index - 1, index);881            Self::write_encoded(storage, left_block, &left)?;882            Self::write_encoded(storage, parent_block, parent)?;883            storage.deallocate(child_block)?;884            Ok((left_block, left))885        } else {886            let (right_block, right) = right.expect("minimum child has a sibling");887            Self::merge_encoded(&mut child, parent, index, &right);888            Self::close_entry(parent, index, index + 1);889            Self::write_encoded(storage, child_block, &child)?;890            Self::write_encoded(storage, parent_block, parent)?;891            storage.deallocate(right_block)?;892            Ok((child_block, child))893        }894    }895    /// The leaf visitor transfers one encoding to its final destination before896    /// the slot closes. Replacement separators do not materialize another owner.897    fn take_edge(898        storage: &mut dyn Storage,899        block: Block,900        node: &mut EncodedNode,901        first: bool,902        visit: &mut impl FnMut(&EncodedNode, usize) -> Result<()>,903    ) -> Result<()> {904        if node.leaf {905            let index = if first { 0 } else { node.count - 1 };906            visit(node, index)?;907            Self::close_entry(node, index, index + 1);908            return Self::write_encoded(storage, block, node);909        }910        let index = if first { 0 } else { node.count };911        let child = Self::read_remove_node(storage, Self::child_at(node, index)?.unwrap())?;912        let (child_block, mut child) = Self::strengthen_child(storage, block, node, index, child)?;913        Self::take_edge(storage, child_block, &mut child, first, visit)914    }915    pub fn first_key_value(&self) -> Option<(Read<'_, K>, Read<'_, V>)> {916        self.iter().next()917    }918    pub fn pop_first(&mut self) -> Option<(K, V)> {919        must(with_storage(|storage| {920            if self.root.is_null() {921                return Ok(None);922            }923            let mut root = Self::read_remove_node(storage, self.root)?;924            let mut removed = None;925            Self::take_edge(storage, self.root, &mut root, true, &mut |node, index| {926                removed = Some((Self::key_at(node, index)?, Self::value_at(node, index)?));927                Ok(())928            })?;929            self.collapse_root(storage, &root)?;930            self.len -= 1;931            Ok(removed)932        }))933    }934    pub fn range<R: RangeBounds<K>>(&self, bounds: R) -> Range<'_, K, V, R> {935        Range {936            inner: Iter::seek(self, bounds.start_bound()),937            bounds,938            finished: false,939        }940    }941    /// Traverse selected keys without decoding or validating their values.942    /// Node headers, search keys and child identities retain the ordinary943    /// range checks. Explicit value reads validate value codec bytes.944    pub fn range_keys<R: RangeBounds<K>>(&self, bounds: R) -> impl Iterator<Item = Read<'_, K>> {945        KeyRange {946            inner: KeyIter::seek(self, bounds.start_bound()),947            bounds,948            finished: false,949        }950    }951}952953impl<K: HylixValue, V: HylixValue> Codec for Map<K, V> {954    const __CODEC_POLICY: [u8; 32] =955        cdk_rsx_source_policy::source_policy!("mod.rs", "map.rs", "map_build.rs");956    const SIZE: usize = Block::SIZE + u64::SIZE;957    fn encode(&self, out: &mut [u8]) {958        self.root.encode(&mut out[..Block::SIZE]);959        self.len.encode(&mut out[Block::SIZE..]);960    }961    fn decode(bytes: &[u8]) -> Result<Self> {962        if bytes.len() != Self::SIZE {963            return Err(Error::Bounds);964        }965        let root = Block::decode(&bytes[..Block::SIZE])?;966        let len = u64::decode(&bytes[Block::SIZE..])?;967        if root.is_null() != (len == 0) {968            return Err(Error::Corrupt("stable map root"));969        }970        Ok(Self {971            root,972            len,973            marker: PhantomData,974        })975    }976}977// SAFETY: every initialized key/value is retired exactly once with its owning978// tree; the decoded carrier has no implicit Rust destructor.979unsafe impl<K: HylixValue, V: HylixValue> HylixValue for Map<K, V> {980    fn retire(self, storage: &mut dyn Storage) -> Result<()> {981        Self::retire_tree(storage, self.root)982    }983}984impl<K: Key<K>, V: HylixValue> Extend<(K, V)> for Map<K, V> {985    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, values: I) {986        for (key, value) in values {987            if let Some(displaced) = self.insert(key, value) {988                super::retire(displaced);989            }990        }991    }992}993impl<K: Key<K>, V: HylixValue> FromIterator<(K, V)> for Map<K, V> {994    fn from_iter<I: IntoIterator<Item = (K, V)>>(values: I) -> Self {995        let mut map = Self::new();996        map.extend(values);997        map998    }999}10001001struct Frame {1002    node: EncodedNode,1003    next: usize,1004}1005/// Streaming traversal retains bounded encoded bytes per tree level. Values1006/// are decoded only when yielded, including early-stop and lower-bound ranges.1007pub struct Iter<'a, K: HylixValue, V: HylixValue> {1008    frames: std::vec::Vec<Frame>,1009    remaining: usize,1010    borrowed: PhantomData<&'a Map<K, V>>,1011}1012impl<'a, K: HylixValue, V: HylixValue> Iter<'a, K, V> {1013    fn new(map: &'a Map<K, V>) -> Self {1014        let mut result = Self {1015            frames: std::vec::Vec::new(),1016            remaining: map.len(),1017            borrowed: PhantomData,1018        };1019        if !map.root.is_null() {1020            result.descend(map.root);1021        }1022        result1023    }1024    fn descend(&mut self, mut block: Block) {1025        loop {1026            let node = must(with_storage_read(|storage| {1027                Map::<K, V>::read_encoded(storage, block)1028            }));1029            let next = must(Map::<K, V>::child_at(&node, 0));1030            self.frames.push(Frame { node, next: 0 });1031            match next {1032                Some(child) => block = child,1033                None => return,1034            }1035        }1036    }1037}1038impl<'a, K: Key<K>, V: HylixValue> Iter<'a, K, V> {1039    fn seek(map: &'a Map<K, V>, start: Bound<&K>) -> Self {1040        if matches!(start, Bound::Unbounded) {1041            return Self::new(map);1042        }1043        let mut result = Self {1044            frames: std::vec::Vec::new(),1045            remaining: map.len(),1046            borrowed: PhantomData,1047        };1048        let mut block = map.root;1049        while !block.is_null() {1050            let (node, index) = must(with_storage_read(|storage| {1051                let node = Map::<K, V>::read_encoded(storage, block)?;1052                let (Bound::Included(start_key) | Bound::Excluded(start_key)) = start else {1053                    unreachable!()1054                };1055                let index =1056                    match Map::<K, V>::search(&node, &|key| key.compare(start_key, storage))? {1057                        Ok(index) => index + usize::from(matches!(start, Bound::Excluded(_))),1058                        Err(index) => index,1059                    };1060                Ok((node, index))1061            }));1062            let next = must(Map::<K, V>::child_at(&node, index));1063            result.frames.push(Frame { node, next: index });1064            block = next.unwrap_or(Block::NULL);1065        }1066        result1067    }1068}1069impl<'a, K: HylixValue, V: HylixValue> Iterator for Iter<'a, K, V> {1070    type Item = (Read<'a, K>, Read<'a, V>);1071    fn next(&mut self) -> Option<Self::Item> {1072        loop {1073            let top = self.frames.last_mut()?;1074            if top.next < top.node.count {1075                let index = top.next;1076                let key = must(Map::<K, V>::key_at(&top.node, index));1077                let value = must(Map::<K, V>::value_at(&top.node, index));1078                top.next += 1;1079                let child = must(Map::<K, V>::child_at(&top.node, top.next));1080                if let Some(child) = child {1081                    self.descend(child);1082                }1083                self.remaining -= 1;1084                return Some((Read::new(key), Read::new(value)));1085            }1086            self.frames.pop();1087        }1088    }1089    fn size_hint(&self) -> (usize, Option<usize>) {1090        (self.remaining, Some(self.remaining))1091    }1092}1093impl<K: HylixValue, V: HylixValue> ExactSizeIterator for Iter<'_, K, V> {}10941095/// A range starts by seeking one root-to-leaf path, without reading its prefix.1096pub struct Range<'a, K: Key<K>, V: HylixValue, R: RangeBounds<K>> {1097    inner: Iter<'a, K, V>,1098    bounds: R,1099    finished: bool,1100}1101impl<'a, K: Key<K>, V: HylixValue, R: RangeBounds<K>> Iterator for Range<'a, K, V, R> {1102    type Item = (Read<'a, K>, Read<'a, V>);1103    fn next(&mut self) -> Option<Self::Item> {1104        if self.finished {1105            return None;1106        }1107        let item = self.inner.next()?;1108        let after = must(with_storage_read(|storage| {1109            Ok(match self.bounds.end_bound() {1110                Bound::Included(end) => item.0.compare(end, storage) == Ordering::Greater,1111                Bound::Excluded(end) => item.0.compare(end, storage) != Ordering::Less,1112                Bound::Unbounded => false,1113            })1114        }));1115        if after {1116            self.finished = true;1117            None1118        } else {1119            Some(item)1120        }1121    }1122    fn size_hint(&self) -> (usize, Option<usize>) {1123        (1124            0,1125            Some(if self.finished {1126                01127            } else {1128                self.inner.remaining1129            }),1130        )1131    }1132}11331134struct KeyIter<'a, K: Key<K>, V: HylixValue> {1135    frames: std::vec::Vec<Frame>,1136    remaining: usize,1137    borrowed: PhantomData<&'a Map<K, V>>,1138}1139impl<'a, K: Key<K>, V: HylixValue> KeyIter<'a, K, V> {1140    fn seek(map: &'a Map<K, V>, start: Bound<&K>) -> Self {1141        let mut result = Self {1142            frames: std::vec::Vec::new(),1143            remaining: map.len(),1144            borrowed: PhantomData,1145        };1146        if !map.root.is_null() {1147            result.descend(map.root, start);1148        }1149        result1150    }1151    fn read_encoded(storage: &dyn Storage, block: Block) -> Result<EncodedNode> {1152        let mut encoded = None;1153        // Retain the original single provider span and its allocation checks.1154        // Only our transient copy omits values: it has Map<K,()> geometry and1155        // is never written to stable storage or treated as an owning map.1156        storage.read_with(block, 0, Map::<K, V>::NODE_SIZE, &mut |source| {1157            let (count, leaf) = Map::<K, V>::header(source)?;1158            let keys_end = Map::<K, V>::key_offset(count);1159            let children_start = Map::<K, V>::children_at(count);1160            let end = Map::<K, V>::encoded_size(count, leaf);1161            let mut bytes = std::vec::Vec::with_capacity(keys_end + (end - children_start));1162            bytes.extend_from_slice(&source[..keys_end]);1163            bytes.extend_from_slice(&source[children_start..end]);1164            encoded = Some(EncodedNode { bytes, count, leaf });1165            Ok(())1166        })?;1167        Ok(encoded.expect("Storage::read_with must call its visitor"))1168    }1169    fn descend(&mut self, mut block: Block, start: Bound<&K>) {1170        loop {1171            let (node, index) = must(with_storage_read(|storage| {1172                let node = Self::read_encoded(storage, block)?;1173                let index = match start {1174                    Bound::Unbounded => 0,1175                    Bound::Included(key) | Bound::Excluded(key) => {1176                        match Map::<K, ()>::search(&node, &|saved| saved.compare(key, storage))? {1177                            Ok(index) => index + usize::from(matches!(start, Bound::Excluded(_))),1178                            Err(index) => index,1179                        }1180                    }1181                };1182                Ok((node, index))1183            }));1184            let next = must(Map::<K, ()>::child_at(&node, index));1185            self.frames.push(Frame { node, next: index });1186            match next {1187                Some(child) => block = child,1188                None => return,1189            }1190        }1191    }1192    fn next_key(&mut self) -> Option<Read<'a, K>> {1193        loop {1194            let top = self.frames.last_mut()?;1195            if top.next < top.node.count {1196                let key = must(Map::<K, ()>::key_at(&top.node, top.next));1197                top.next += 1;1198                let child = must(Map::<K, ()>::child_at(&top.node, top.next));1199                if let Some(child) = child {1200                    self.descend(child, Bound::Unbounded);1201                }1202                self.remaining -= 1;1203                return Some(Read::new(key));1204            }1205            self.frames.pop();1206        }1207    }1208}12091210struct KeyRange<'a, K: Key<K>, V: HylixValue, R: RangeBounds<K>> {1211    inner: KeyIter<'a, K, V>,1212    bounds: R,1213    finished: bool,1214}1215impl<'a, K: Key<K>, V: HylixValue, R: RangeBounds<K>> Iterator for KeyRange<'a, K, V, R> {1216    type Item = Read<'a, K>;1217    fn next(&mut self) -> Option<Self::Item> {1218        if self.finished {1219            return None;1220        }1221        let key = self.inner.next_key()?;1222        let after = must(with_storage_read(|storage| {1223            Ok(match self.bounds.end_bound() {1224                Bound::Included(end) => key.compare(end, storage) == Ordering::Greater,1225                Bound::Excluded(end) => key.compare(end, storage) != Ordering::Less,1226                Bound::Unbounded => false,1227            })1228        }));1229        if after {1230            self.finished = true;1231            None1232        } else {1233            Some(key)1234        }1235    }1236    fn size_hint(&self) -> (usize, Option<usize>) {1237        (1238            0,1239            Some(if self.finished {1240                01241            } else {1242                self.inner.remaining1243            }),1244        )1245    }1246}12471248pub struct Set<T: HylixValue> {1249    values: Map<T, ()>,1250}1251impl<T: HylixValue> Default for Set<T> {1252    fn default() -> Self {1253        Self::new()1254    }1255}1256impl<T: HylixValue> Set<T> {1257    pub const fn new() -> Self {1258        Self { values: Map::new() }1259    }1260    pub fn len(&self) -> usize {1261        self.values.len()1262    }1263    pub fn is_empty(&self) -> bool {1264        self.values.is_empty()1265    }1266    pub fn clear(&mut self) {1267        self.values.clear();1268    }1269    pub fn iter(&self) -> impl Iterator<Item = Read<'_, T>> {1270        self.values.keys()1271    }1272}1273impl<T: Key<T>> Set<T> {1274    pub fn insert(&mut self, value: T) -> bool {1275        self.values.insert(value, ()).is_none()1276    }1277    pub fn remove(&mut self, value: &T) -> bool {1278        self.values.remove(value).is_some()1279    }1280    pub fn contains(&self, value: &T) -> bool {1281        self.values.contains_key(value)1282    }1283    pub fn first(&self) -> Option<Read<'_, T>> {1284        self.iter().next()1285    }1286    pub fn pop_first(&mut self) -> Option<T> {1287        self.values.pop_first().map(|(key, ())| key)1288    }1289    pub fn range<R: RangeBounds<T>>(&self, bounds: R) -> impl Iterator<Item = Read<'_, T>> {1290        self.values.range(bounds).map(|(key, _)| key)1291    }1292}1293impl<T: HylixValue> Codec for Set<T> {1294    const __CODEC_POLICY: [u8; 32] =1295        cdk_rsx_source_policy::source_policy!("mod.rs", "map.rs", "map_build.rs");1296    const SIZE: usize = Map::<T, ()>::SIZE;1297    fn encode(&self, out: &mut [u8]) {1298        self.values.encode(out);1299    }1300    fn decode(bytes: &[u8]) -> Result<Self> {1301        Ok(Self {1302            values: Map::decode(bytes)?,1303        })1304    }1305}1306// SAFETY: ownership is exactly the owning map's key ownership.1307unsafe impl<T: HylixValue> HylixValue for Set<T> {1308    fn retire(self, storage: &mut dyn Storage) -> Result<()> {1309        self.values.retire(storage)1310    }1311}1312impl<T: Key<T>> Extend<T> for Set<T> {1313    fn extend<I: IntoIterator<Item = T>>(&mut self, values: I) {1314        for value in values {1315            self.insert(value);1316        }1317    }1318}1319impl<T: Key<T>> FromIterator<T> for Set<T> {1320    fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self {1321        let mut set = Self::new();1322        set.extend(values);1323        set1324    }1325}