Skip to main content

commonware_utils/
ordered.rs

1//! Ordered collections that guarantee sorted, deduplicated items.
2
3#[cfg(not(feature = "std"))]
4use alloc::vec::Vec;
5use bytes::BufMut;
6use commonware_codec::{
7    Buf, EncodeSize, MaxEncodeSize, RangeCfg, Read, Write, util::max_items_size,
8};
9use core::{
10    fmt,
11    hash::Hash,
12    ops::{Deref, Index, Range},
13};
14use hashbrown::HashSet;
15use thiserror::Error;
16
17type Hasher = ahash::RandomState;
18
19#[cfg(not(feature = "std"))]
20type VecIntoIter<T> = alloc::vec::IntoIter<T>;
21#[cfg(feature = "std")]
22type VecIntoIter<T> = std::vec::IntoIter<T>;
23
24/// Errors that can occur when interacting with ordered collections.
25#[derive(Error, Debug, PartialEq, Eq)]
26pub enum Error {
27    /// A key was duplicated.
28    #[error("duplicate key")]
29    DuplicateKey,
30
31    /// A value was duplicated.
32    #[error("duplicate value")]
33    DuplicateValue,
34}
35
36use crate::{Faults, Participant, TryFromIterator};
37
38/// An ordered, deduplicated collection of items.
39#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub struct Set<T>(Vec<T>);
41
42impl<T: fmt::Debug> fmt::Debug for Set<T> {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        f.debug_tuple("Set").field(&self.0).finish()
45    }
46}
47
48impl<T> Default for Set<T> {
49    fn default() -> Self {
50        Self(Vec::new())
51    }
52}
53
54impl<T: Ord> Set<T> {
55    /// Creates a new [`Set`] from an iterator, removing duplicates.
56    ///
57    /// Unlike [`FromIterator`] and [`From`], this method tolerates duplicate
58    /// items by silently discarding them.
59    pub fn from_iter_dedup<I: IntoIterator<Item = T>>(iter: I) -> Self {
60        let mut items: Vec<T> = iter.into_iter().collect();
61        items.sort();
62        items.dedup();
63        Self(items)
64    }
65}
66
67impl<T> Set<T> {
68    /// Returns the size of the ordered collection.
69    pub const fn len(&self) -> usize {
70        self.0.len()
71    }
72
73    /// Returns `true` if the collection is empty.
74    pub const fn is_empty(&self) -> bool {
75        self.0.is_empty()
76    }
77
78    /// Returns an item by index, if it exists.
79    pub fn get(&self, index: usize) -> Option<&T> {
80        self.0.get(index)
81    }
82
83    /// Returns the position of a given item in the collection, if it exists.
84    pub fn position(&self, item: &T) -> Option<usize>
85    where
86        T: Ord,
87    {
88        self.0.binary_search(item).ok()
89    }
90
91    /// Returns an iterator over the items in the collection.
92    pub fn iter(&self) -> core::slice::Iter<'_, T> {
93        self.into_iter()
94    }
95}
96
97impl<T: Write> Write for Set<T> {
98    fn write(&self, buf: &mut impl BufMut) {
99        self.0.write(buf);
100    }
101}
102
103impl<T: EncodeSize> EncodeSize for Set<T> {
104    fn encode_size(&self) -> usize {
105        self.0.encode_size()
106    }
107}
108
109impl<T: MaxEncodeSize> Set<T> {
110    /// Returns an upper bound on the encoded size of a set of at most `len` items.
111    pub fn max_encode_size(len: usize) -> usize {
112        max_items_size(len, T::MAX_ENCODE_SIZE)
113    }
114}
115
116impl<T: Read + Ord> Read for Set<T> {
117    type Cfg = (RangeCfg<usize>, T::Cfg);
118
119    fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, commonware_codec::Error> {
120        let items = Vec::<T>::read_cfg(buf, cfg)?;
121        for i in 1..items.len() {
122            if items[i - 1] >= items[i] {
123                return Err(commonware_codec::Error::Invalid(
124                    "Set",
125                    "items must be sorted and unique",
126                ));
127            }
128        }
129        Ok(Self(items))
130    }
131}
132
133impl<T: Ord> TryFromIterator<T> for Set<T> {
134    type Error = Error;
135
136    /// Attempts to create a [`Set`] from an iterator.
137    ///
138    /// Returns an error if there are duplicate items.
139    fn try_from_iter<I: IntoIterator<Item = T>>(iter: I) -> Result<Self, Self::Error> {
140        let mut items: Vec<T> = iter.into_iter().collect();
141        items.sort();
142        let len = items.len();
143        items.dedup();
144        if items.len() != len {
145            return Err(Error::DuplicateKey);
146        }
147        Ok(Self(items))
148    }
149}
150
151impl<T: Ord> TryFrom<Vec<T>> for Set<T> {
152    type Error = Error;
153
154    fn try_from(items: Vec<T>) -> Result<Self, Self::Error> {
155        Self::try_from_iter(items)
156    }
157}
158
159impl<T: Ord + Clone> TryFrom<&[T]> for Set<T> {
160    type Error = Error;
161
162    fn try_from(items: &[T]) -> Result<Self, Self::Error> {
163        Self::try_from_iter(items.iter().cloned())
164    }
165}
166
167impl<T: Ord, const N: usize> TryFrom<[T; N]> for Set<T> {
168    type Error = Error;
169
170    fn try_from(items: [T; N]) -> Result<Self, Self::Error> {
171        Self::try_from_iter(items)
172    }
173}
174
175impl<T: Ord + Clone, const N: usize> TryFrom<&[T; N]> for Set<T> {
176    type Error = Error;
177
178    fn try_from(items: &[T; N]) -> Result<Self, Self::Error> {
179        Self::try_from(items.as_slice())
180    }
181}
182
183impl<T> IntoIterator for Set<T> {
184    type Item = T;
185    type IntoIter = VecIntoIter<T>;
186
187    fn into_iter(self) -> Self::IntoIter {
188        self.0.into_iter()
189    }
190}
191
192impl<'a, T> IntoIterator for &'a Set<T> {
193    type Item = &'a T;
194    type IntoIter = core::slice::Iter<'a, T>;
195
196    fn into_iter(self) -> Self::IntoIter {
197        self.0.iter()
198    }
199}
200
201impl<T> Index<usize> for Set<T> {
202    type Output = T;
203
204    fn index(&self, index: usize) -> &Self::Output {
205        &self.0[index]
206    }
207}
208
209impl<T> Index<Range<usize>> for Set<T> {
210    type Output = [T];
211
212    fn index(&self, index: Range<usize>) -> &Self::Output {
213        &self.0[index]
214    }
215}
216
217impl<T> AsRef<[T]> for Set<T> {
218    fn as_ref(&self) -> &[T] {
219        &self.0
220    }
221}
222
223impl<T: fmt::Display> fmt::Display for Set<T> {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
225        write!(f, "[")?;
226        for (i, item) in self.0.iter().enumerate() {
227            if i > 0 {
228                write!(f, ", ")?;
229            }
230            write!(f, "{item}")?;
231        }
232        write!(f, "]")
233    }
234}
235
236impl<T> From<Set<T>> for Vec<T> {
237    fn from(set: Set<T>) -> Self {
238        set.0
239    }
240}
241
242#[cfg(feature = "arbitrary")]
243impl<T> arbitrary::Arbitrary<'_> for Set<T>
244where
245    T: for<'a> arbitrary::Arbitrary<'a> + Ord,
246{
247    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
248        let vec = Vec::<T>::arbitrary(u)?;
249        Ok(Self::from_iter_dedup(vec))
250    }
251}
252
253/// Extension trait for [`Set`] participant sets providing quorum and index utilities.
254pub trait Quorum {
255    /// The type of items in this set.
256    type Item: Ord;
257
258    /// Returns the quorum value for this participant set using the given fault model.
259    ///
260    /// ## Panics
261    ///
262    /// Panics if the number of participants exceeds `u32::MAX`.
263    fn quorum<M: Faults>(&self) -> u32;
264
265    /// Returns the maximum number of faults tolerated by this participant set.
266    ///
267    /// ## Panics
268    ///
269    /// Panics if the number of participants exceeds `u32::MAX`.
270    fn max_faults<M: Faults>(&self) -> u32;
271
272    /// Returns the participant key at the given index.
273    fn key(&self, index: Participant) -> Option<&Self::Item>;
274
275    /// Returns the index for the given participant key, if present.
276    ///
277    /// ## Panics
278    ///
279    /// Panics if the participant index exceeds `u32::MAX`.
280    fn index(&self, key: &Self::Item) -> Option<Participant>;
281}
282
283impl<T: Ord> Quorum for Set<T> {
284    type Item = T;
285
286    fn quorum<M: Faults>(&self) -> u32 {
287        M::quorum(u32::try_from(self.len()).expect("too many participants"))
288    }
289
290    fn max_faults<M: Faults>(&self) -> u32 {
291        M::max_faults(self.len())
292    }
293
294    fn key(&self, index: Participant) -> Option<&Self::Item> {
295        self.get(index.into())
296    }
297
298    fn index(&self, key: &Self::Item) -> Option<Participant> {
299        self.position(key).map(Participant::from_usize)
300    }
301}
302
303/// An ordered, deduplicated collection of key-value pairs.
304#[derive(Clone, PartialEq, Eq, Hash)]
305pub struct Map<K, V> {
306    keys: Set<K>,
307    values: Vec<V>,
308}
309
310impl<K: Ord, V> Map<K, V> {
311    /// Creates a new [`Map`] from an iterator, removing duplicate keys.
312    ///
313    /// Unlike [`FromIterator`] and [`From`], this method tolerates duplicate
314    /// keys by silently discarding them (keeping the first occurrence).
315    pub fn from_iter_dedup<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
316        let mut items: Vec<(K, V)> = iter.into_iter().collect();
317        items.sort_by(|(lk, _), (rk, _)| lk.cmp(rk));
318        items.dedup_by(|l, r| l.0 == r.0);
319
320        let mut keys = Vec::with_capacity(items.len());
321        let mut values = Vec::with_capacity(items.len());
322        for (key, value) in items {
323            keys.push(key);
324            values.push(value);
325        }
326
327        Self {
328            keys: Set(keys),
329            values,
330        }
331    }
332}
333
334impl<K, V> Default for Map<K, V> {
335    fn default() -> Self {
336        Self {
337            keys: Set::default(),
338            values: Vec::new(),
339        }
340    }
341}
342
343impl<K, V> Map<K, V> {
344    /// Creates a map from ordered keys and corresponding values, reusing both allocations.
345    ///
346    /// Each value is paired with the key at the same index. Returns `None` if
347    /// the lengths differ.
348    ///
349    /// # Examples
350    ///
351    /// ```
352    /// use commonware_utils::ordered::{Map, Set};
353    ///
354    /// let keys = Set::try_from([3, 1, 2]).unwrap();
355    /// let map = Map::from_parts(keys, vec!["one", "two", "three"]).unwrap();
356    /// assert_eq!(map.get_value(&2), Some(&"two"));
357    /// ```
358    pub fn from_parts(keys: Set<K>, values: Vec<V>) -> Option<Self> {
359        if keys.len() != values.len() {
360            return None;
361        }
362        Some(Self { keys, values })
363    }
364
365    /// Returns the number of entries in the map.
366    pub const fn len(&self) -> usize {
367        self.keys.len()
368    }
369
370    /// Returns `true` if the map is empty.
371    pub const fn is_empty(&self) -> bool {
372        self.keys.is_empty()
373    }
374
375    /// Returns a key by index, if it exists.
376    pub fn get(&self, index: usize) -> Option<&K> {
377        self.keys.get(index)
378    }
379
380    /// Returns the position of the provided key, if it exists.
381    pub fn position(&self, key: &K) -> Option<usize>
382    where
383        K: Ord,
384    {
385        self.keys.position(key)
386    }
387
388    /// Returns the ordered keys as a [`Set`] reference.
389    pub const fn keys(&self) -> &Set<K> {
390        &self.keys
391    }
392
393    /// Consumes the map and returns the ordered keys.
394    pub fn into_keys(self) -> Set<K> {
395        self.keys
396    }
397
398    /// Returns the associated value at `index`, if it exists.
399    pub fn value(&self, index: usize) -> Option<&V> {
400        self.values.get(index)
401    }
402
403    /// Returns the associated value for `key`, if it exists.
404    pub fn get_value(&self, key: &K) -> Option<&V>
405    where
406        K: Ord,
407    {
408        self.position(key).and_then(|index| self.values.get(index))
409    }
410
411    /// Returns a mutable reference to the associated value for `key`, if it exists.
412    pub fn get_value_mut(&mut self, key: &K) -> Option<&mut V>
413    where
414        K: Ord,
415    {
416        self.position(key)
417            .and_then(|index| self.values.get_mut(index))
418    }
419
420    /// Returns the associated values.
421    pub fn values(&self) -> &[V] {
422        &self.values
423    }
424
425    /// Returns a mutable reference to the associated values
426    pub fn values_mut(&mut self) -> &mut [V] {
427        &mut self.values
428    }
429
430    /// Maps each value in key order, cloning the keys without sorting or validating them.
431    ///
432    /// The closure receives references to the key and value. The new values may
433    /// borrow from this map.
434    ///
435    /// # Examples
436    ///
437    /// ```
438    /// use commonware_utils::ordered::Map;
439    ///
440    /// let map = Map::try_from([(4, "four"), (1, "one")]).unwrap();
441    /// let lengths = map.map_values(|_, value| value.len());
442    /// assert_eq!(lengths.keys(), map.keys());
443    /// assert_eq!(lengths.values(), &[3, 4]);
444    /// ```
445    pub fn map_values<'a, U, F>(&'a self, mut f: F) -> Map<K, U>
446    where
447        K: Clone,
448        F: FnMut(&'a K, &'a V) -> U,
449    {
450        let values = self
451            .iter_pairs()
452            .map(|(key, value)| f(key, value))
453            .collect();
454        Map {
455            keys: self.keys.clone(),
456            values,
457        }
458    }
459
460    /// Fallible version of [`Self::map_values`].
461    ///
462    /// Returns the first error without calling the closure for subsequent entries.
463    /// Clones the keys only on success.
464    ///
465    /// # Examples
466    ///
467    /// ```
468    /// use commonware_utils::ordered::Map;
469    ///
470    /// let map = Map::try_from([(2, "invalid"), (1, "10")]).unwrap();
471    /// let result = map.try_map_values(|_, value| value.parse::<u32>());
472    /// assert!(result.is_err());
473    /// assert_eq!(map.values(), &["10", "invalid"]);
474    /// ```
475    pub fn try_map_values<'a, U, E, F>(&'a self, mut f: F) -> Result<Map<K, U>, E>
476    where
477        K: Clone,
478        F: FnMut(&'a K, &'a V) -> Result<U, E>,
479    {
480        let mut values = Vec::with_capacity(self.len());
481        for (key, value) in self.iter_pairs() {
482            values.push(f(key, value)?);
483        }
484        Ok(Map {
485            keys: self.keys.clone(),
486            values,
487        })
488    }
489
490    /// Consumes the map and maps each value in key order, reusing the key allocation.
491    ///
492    /// The closure receives a reference to the key and the owned value. Keys are
493    /// not cloned, sorted, or validated.
494    ///
495    /// # Examples
496    ///
497    /// ```
498    /// use commonware_utils::ordered::Map;
499    ///
500    /// let map = Map::try_from([(2, String::from("two")), (1, String::from("one"))]).unwrap();
501    /// let bytes = map.map_values_into(|_, value| value.into_bytes());
502    /// assert_eq!(bytes.keys().as_ref(), &[1, 2]);
503    /// assert_eq!(bytes.values(), &[b"one".to_vec(), b"two".to_vec()]);
504    /// ```
505    pub fn map_values_into<U, F>(self, mut f: F) -> Map<K, U>
506    where
507        F: FnMut(&K, V) -> U,
508    {
509        let Self { keys, values } = self;
510        let values = keys
511            .iter()
512            .zip(values)
513            .map(|(key, value)| f(key, value))
514            .collect();
515        Map { keys, values }
516    }
517
518    /// Fallible version of [`Self::map_values_into`].
519    ///
520    /// Returns the first error without calling the closure for subsequent entries.
521    ///
522    /// # Examples
523    ///
524    /// ```
525    /// use commonware_utils::ordered::Map;
526    ///
527    /// let map = Map::try_from([(2, String::from("20")), (1, String::from("10"))]).unwrap();
528    /// let parsed = map.try_map_values_into(|_, value| value.parse::<u32>()).unwrap();
529    /// assert_eq!(parsed.keys().as_ref(), &[1, 2]);
530    /// assert_eq!(parsed.values(), &[10, 20]);
531    /// ```
532    pub fn try_map_values_into<U, E, F>(self, mut f: F) -> Result<Map<K, U>, E>
533    where
534        F: FnMut(&K, V) -> Result<U, E>,
535    {
536        let Self { keys, values } = self;
537        let mut mapped = Vec::with_capacity(keys.len());
538        for (key, value) in keys.iter().zip(values) {
539            mapped.push(f(key, value)?);
540        }
541        Ok(Map {
542            keys,
543            values: mapped,
544        })
545    }
546
547    /// Truncates the map to at most `len` entries.
548    pub fn truncate(&mut self, len: usize) {
549        self.keys.0.truncate(len);
550        self.values.truncate(len);
551    }
552
553    /// Returns a zipped iterator over keys and values.
554    pub fn iter_pairs(&self) -> impl ExactSizeIterator<Item = (&K, &V)> + DoubleEndedIterator {
555        self.keys.iter().zip(self.values.iter())
556    }
557
558    /// Returns a zipped iterator over keys and mutable references to values.
559    ///
560    /// This is provided because the borrow checker does not let you combine
561    /// the other functions yourself.
562    pub fn iter_pairs_mut(
563        &mut self,
564    ) -> impl ExactSizeIterator<Item = (&K, &mut V)> + DoubleEndedIterator {
565        self.keys.iter().zip(self.values.iter_mut())
566    }
567
568    /// Returns an iterator over the ordered keys.
569    pub fn iter(&self) -> core::slice::Iter<'_, K> {
570        self.keys.iter()
571    }
572}
573
574impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Map<K, V> {
575    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
576        f.debug_tuple("Map")
577            .field(&self.iter_pairs().collect::<Vec<_>>())
578            .finish()
579    }
580}
581
582impl<K: fmt::Display, V: fmt::Display> fmt::Display for Map<K, V> {
583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
584        write!(f, "[")?;
585        for (i, (key, value)) in self.iter_pairs().enumerate() {
586            if i > 0 {
587                write!(f, ", ")?;
588            }
589            write!(f, "({key}, {value})")?;
590        }
591        write!(f, "]")
592    }
593}
594
595impl<K, V> AsRef<[K]> for Map<K, V> {
596    fn as_ref(&self) -> &[K] {
597        self.keys.as_ref()
598    }
599}
600
601impl<K, V> AsRef<Set<K>> for Map<K, V> {
602    fn as_ref(&self) -> &Set<K> {
603        &self.keys
604    }
605}
606
607impl<K, V> Deref for Map<K, V> {
608    type Target = Set<K>;
609
610    fn deref(&self) -> &Self::Target {
611        &self.keys
612    }
613}
614
615impl<K: Ord, V> TryFromIterator<(K, V)> for Map<K, V> {
616    type Error = Error;
617
618    /// Attempts to create a [`Map`] from an iterator.
619    ///
620    /// Returns an error if there are duplicate keys.
621    fn try_from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Result<Self, Self::Error> {
622        let mut items: Vec<(K, V)> = iter.into_iter().collect();
623        items.sort_by(|(lk, _), (rk, _)| lk.cmp(rk));
624        let len = items.len();
625        items.dedup_by(|l, r| l.0 == r.0);
626        if items.len() != len {
627            return Err(Error::DuplicateKey);
628        }
629
630        let mut keys = Vec::with_capacity(items.len());
631        let mut values = Vec::with_capacity(items.len());
632        for (key, value) in items {
633            keys.push(key);
634            values.push(value);
635        }
636
637        Ok(Self {
638            keys: Set(keys),
639            values,
640        })
641    }
642}
643
644impl<K: Ord, V> TryFrom<Vec<(K, V)>> for Map<K, V> {
645    type Error = Error;
646
647    fn try_from(items: Vec<(K, V)>) -> Result<Self, Self::Error> {
648        Self::try_from_iter(items)
649    }
650}
651
652impl<K: Ord + Clone, V: Clone> TryFrom<&[(K, V)]> for Map<K, V> {
653    type Error = Error;
654
655    fn try_from(items: &[(K, V)]) -> Result<Self, Self::Error> {
656        Self::try_from_iter(items.iter().cloned())
657    }
658}
659
660impl<K: Ord, V, const N: usize> TryFrom<[(K, V); N]> for Map<K, V> {
661    type Error = Error;
662
663    fn try_from(items: [(K, V); N]) -> Result<Self, Self::Error> {
664        Self::try_from_iter(items)
665    }
666}
667
668impl<K: Ord + Clone, V: Clone, const N: usize> TryFrom<&[(K, V); N]> for Map<K, V> {
669    type Error = Error;
670
671    fn try_from(items: &[(K, V); N]) -> Result<Self, Self::Error> {
672        Self::try_from(items.as_slice())
673    }
674}
675
676impl<K, V> From<Map<K, V>> for Vec<(K, V)> {
677    fn from(wrapped: Map<K, V>) -> Self {
678        wrapped.into_iter().collect()
679    }
680}
681
682impl<K: Write, V: Write> Write for Map<K, V> {
683    fn write(&self, buf: &mut impl BufMut) {
684        self.keys.write(buf);
685        self.values.write(buf);
686    }
687}
688
689impl<K: EncodeSize, V: EncodeSize> EncodeSize for Map<K, V> {
690    fn encode_size(&self) -> usize {
691        self.keys.encode_size() + self.values.encode_size()
692    }
693}
694
695impl<K: MaxEncodeSize, V> Map<K, V> {
696    /// Returns an upper bound on the encoded size of a map of at most `len` entries whose values
697    /// encode to at most `value` bytes each.
698    pub fn max_encode_size(len: usize, value: usize) -> usize {
699        Set::<K>::max_encode_size(len) + max_items_size(len, value)
700    }
701}
702
703impl<K: Read + Ord, V: Read> Read for Map<K, V> {
704    type Cfg = (RangeCfg<usize>, K::Cfg, V::Cfg);
705
706    fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, commonware_codec::Error> {
707        let (range_cfg, key_cfg, value_cfg) = cfg;
708        let keys = Set::<K>::read_cfg(buf, &(*range_cfg, key_cfg.clone()))?;
709        let values = Vec::<V>::read_cfg(buf, &(RangeCfg::exact(keys.len()), value_cfg.clone()))?;
710        Ok(Self { keys, values })
711    }
712}
713
714impl<K, V> IntoIterator for Map<K, V> {
715    type Item = (K, V);
716    type IntoIter = MapIntoIter<K, V>;
717
718    fn into_iter(self) -> Self::IntoIter {
719        MapIntoIter {
720            keys: self.keys.into_iter(),
721            values: self.values.into_iter(),
722        }
723    }
724}
725
726impl<'a, K, V> IntoIterator for &'a Map<K, V> {
727    type Item = (&'a K, &'a V);
728    type IntoIter = core::iter::Zip<core::slice::Iter<'a, K>, core::slice::Iter<'a, V>>;
729
730    fn into_iter(self) -> Self::IntoIter {
731        self.keys.iter().zip(self.values.iter())
732    }
733}
734
735/// An iterator over owned key-value pairs.
736pub struct MapIntoIter<K, V> {
737    keys: VecIntoIter<K>,
738    values: VecIntoIter<V>,
739}
740
741impl<K, V> Iterator for MapIntoIter<K, V> {
742    type Item = (K, V);
743
744    fn next(&mut self) -> Option<Self::Item> {
745        let key = self.keys.next()?;
746        let value = self.values.next()?;
747        Some((key, value))
748    }
749
750    fn size_hint(&self) -> (usize, Option<usize>) {
751        self.keys.size_hint()
752    }
753}
754
755impl<K, V> ExactSizeIterator for MapIntoIter<K, V> {}
756
757impl<K, V> DoubleEndedIterator for MapIntoIter<K, V> {
758    fn next_back(&mut self) -> Option<Self::Item> {
759        let key = self.keys.next_back()?;
760        let value = self.values.next_back()?;
761        Some((key, value))
762    }
763}
764
765#[cfg(feature = "arbitrary")]
766impl<K, V> arbitrary::Arbitrary<'_> for Map<K, V>
767where
768    K: for<'a> arbitrary::Arbitrary<'a> + Ord,
769    V: for<'a> arbitrary::Arbitrary<'a>,
770{
771    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
772        let vec = Vec::<(K, V)>::arbitrary(u)?;
773        Ok(Self::from_iter_dedup(vec))
774    }
775}
776
777/// An ordered, deduplicated collection of key-value pairs with unique values.
778#[derive(Clone, PartialEq, Eq, Hash)]
779pub struct BiMap<K, V> {
780    inner: Map<K, V>,
781}
782
783impl<K, V> Default for BiMap<K, V> {
784    fn default() -> Self {
785        Self {
786            inner: Map::default(),
787        }
788    }
789}
790
791impl<K, V> BiMap<K, V> {
792    /// Returns the number of entries in the map.
793    pub const fn len(&self) -> usize {
794        self.inner.len()
795    }
796
797    /// Returns `true` if the map is empty.
798    pub const fn is_empty(&self) -> bool {
799        self.inner.is_empty()
800    }
801
802    /// Returns a key by index, if it exists.
803    pub fn get(&self, index: usize) -> Option<&K> {
804        self.inner.get(index)
805    }
806
807    /// Returns the position of the provided key, if it exists.
808    pub fn position(&self, key: &K) -> Option<usize>
809    where
810        K: Ord,
811    {
812        self.inner.position(key)
813    }
814
815    /// Returns the ordered keys as a [`Set`] reference.
816    pub const fn keys(&self) -> &Set<K> {
817        self.inner.keys()
818    }
819
820    /// Consumes the map and returns the ordered keys.
821    pub fn into_keys(self) -> Set<K> {
822        self.inner.into_keys()
823    }
824
825    /// Returns the associated value at `index`, if it exists.
826    pub fn value(&self, index: usize) -> Option<&V> {
827        self.inner.value(index)
828    }
829
830    /// Returns the associated value for `key`, if it exists.
831    pub fn get_value(&self, key: &K) -> Option<&V>
832    where
833        K: Ord,
834    {
835        self.inner.get_value(key)
836    }
837
838    /// Returns the associated key for `value`, if it exists.
839    pub fn get_key(&self, value: &V) -> Option<&K>
840    where
841        V: PartialEq,
842    {
843        self.inner
844            .values()
845            .iter()
846            .position(|v| v == value)
847            .map(|idx| &self.inner.keys()[idx])
848    }
849
850    /// Returns the associated values.
851    pub fn values(&self) -> &[V] {
852        self.inner.values()
853    }
854
855    /// Returns a zipped iterator over keys and values.
856    pub fn iter_pairs(&self) -> impl ExactSizeIterator<Item = (&K, &V)> + DoubleEndedIterator {
857        self.inner.iter_pairs()
858    }
859
860    /// Returns an iterator over the ordered keys.
861    pub fn iter(&self) -> core::slice::Iter<'_, K> {
862        self.inner.iter()
863    }
864}
865
866impl<K: Ord, V: Eq + Hash> TryFromIterator<(K, V)> for BiMap<K, V> {
867    type Error = Error;
868
869    /// Attempts to create a [`BiMap`] from an iterator of key-value pairs.
870    ///
871    /// Returns an error if any key or value is duplicated.
872    fn try_from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Result<Self, Self::Error> {
873        let map = <Map<K, V> as TryFromIterator<(K, V)>>::try_from_iter(iter)?;
874        Self::try_from(map)
875    }
876}
877
878impl<K, V: Eq + Hash> TryFrom<Map<K, V>> for BiMap<K, V> {
879    type Error = Error;
880
881    fn try_from(map: Map<K, V>) -> Result<Self, Self::Error> {
882        {
883            let mut seen = HashSet::with_capacity_and_hasher(map.values.len(), Hasher::default());
884            for value in map.values.iter() {
885                if !seen.insert(value) {
886                    return Err(Error::DuplicateValue);
887                }
888            }
889        }
890        Ok(Self { inner: map })
891    }
892}
893
894impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for BiMap<K, V> {
895    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896        f.debug_tuple("BiMap")
897            .field(&self.inner.iter_pairs().collect::<Vec<_>>())
898            .finish()
899    }
900}
901
902impl<K: fmt::Display, V: fmt::Display> fmt::Display for BiMap<K, V> {
903    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
904        write!(f, "[")?;
905        for (i, (key, value)) in self.iter_pairs().enumerate() {
906            if i > 0 {
907                write!(f, ", ")?;
908            }
909            write!(f, "({key}, {value})")?;
910        }
911        write!(f, "]")
912    }
913}
914
915impl<K, V> AsRef<[K]> for BiMap<K, V> {
916    fn as_ref(&self) -> &[K] {
917        self.inner.as_ref()
918    }
919}
920
921impl<K, V> AsRef<Set<K>> for BiMap<K, V> {
922    fn as_ref(&self) -> &Set<K> {
923        self.inner.as_ref()
924    }
925}
926
927impl<K, V> Deref for BiMap<K, V> {
928    type Target = Set<K>;
929
930    fn deref(&self) -> &Self::Target {
931        &self.inner
932    }
933}
934
935impl<K: Ord + Clone, V: Clone + Eq + Hash> TryFrom<&[(K, V)]> for BiMap<K, V> {
936    type Error = Error;
937
938    fn try_from(items: &[(K, V)]) -> Result<Self, Self::Error> {
939        Self::try_from_iter(items.iter().cloned())
940    }
941}
942
943impl<K: Ord, V: Eq + Hash> TryFrom<Vec<(K, V)>> for BiMap<K, V> {
944    type Error = Error;
945
946    fn try_from(items: Vec<(K, V)>) -> Result<Self, Self::Error> {
947        Self::try_from_iter(items)
948    }
949}
950
951impl<K: Ord, V: Eq + Hash, const N: usize> TryFrom<[(K, V); N]> for BiMap<K, V> {
952    type Error = Error;
953
954    fn try_from(items: [(K, V); N]) -> Result<Self, Self::Error> {
955        Self::try_from_iter(items)
956    }
957}
958
959impl<K: Ord + Clone, V: Clone + Eq + Hash, const N: usize> TryFrom<&[(K, V); N]> for BiMap<K, V> {
960    type Error = Error;
961
962    fn try_from(items: &[(K, V); N]) -> Result<Self, Self::Error> {
963        Self::try_from(items.as_slice())
964    }
965}
966
967impl<K, V> From<BiMap<K, V>> for Vec<(K, V)> {
968    fn from(wrapped: BiMap<K, V>) -> Self {
969        wrapped.inner.into()
970    }
971}
972
973impl<K: Write, V: Write> Write for BiMap<K, V> {
974    fn write(&self, buf: &mut impl BufMut) {
975        self.inner.write(buf);
976    }
977}
978
979impl<K: EncodeSize, V: EncodeSize> EncodeSize for BiMap<K, V> {
980    fn encode_size(&self) -> usize {
981        self.inner.encode_size()
982    }
983}
984
985impl<K: Read + Ord, V: Eq + Hash + Read> Read for BiMap<K, V> {
986    type Cfg = (RangeCfg<usize>, K::Cfg, V::Cfg);
987
988    fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, commonware_codec::Error> {
989        let inner = Map::<K, V>::read_cfg(buf, cfg)?;
990        Self::try_from(inner).map_err(|_| {
991            commonware_codec::Error::Invalid(
992                "BiMap",
993                "duplicate value detected during deserialization",
994            )
995        })
996    }
997}
998
999impl<K, V> IntoIterator for BiMap<K, V> {
1000    type Item = (K, V);
1001    type IntoIter = MapIntoIter<K, V>;
1002
1003    fn into_iter(self) -> Self::IntoIter {
1004        self.inner.into_iter()
1005    }
1006}
1007
1008impl<'a, K, V> IntoIterator for &'a BiMap<K, V> {
1009    type Item = (&'a K, &'a V);
1010    type IntoIter = core::iter::Zip<core::slice::Iter<'a, K>, core::slice::Iter<'a, V>>;
1011
1012    fn into_iter(self) -> Self::IntoIter {
1013        self.inner.iter().zip(self.inner.values().iter())
1014    }
1015}
1016
1017#[cfg(feature = "arbitrary")]
1018impl<K, V> arbitrary::Arbitrary<'_> for BiMap<K, V>
1019where
1020    K: for<'a> arbitrary::Arbitrary<'a> + Ord,
1021    V: for<'a> arbitrary::Arbitrary<'a> + Ord + Hash,
1022{
1023    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
1024        let mut vec = Vec::<(K, V)>::arbitrary(u)?;
1025        vec.sort_by(|(lk, _), (rk, _)| lk.cmp(rk));
1026        vec.dedup_by(|l, r| l.0 == r.0);
1027        vec.sort_by(|(_, lv), (_, rv)| lv.cmp(rv));
1028        vec.dedup_by(|l, r| l.1 == r.1);
1029        Self::try_from_iter(vec).map_err(|_| arbitrary::Error::IncorrectFormat)
1030    }
1031}
1032
1033#[cfg(test)]
1034mod test {
1035    use super::*;
1036    use core::cell::Cell;
1037    use rstest::rstest;
1038
1039    #[test]
1040    fn test_sorted_unique_construct_unseal() {
1041        const CASE: [u8; 12] = [1, 3, 2, 5, 4, 3, 1, 7, 9, 6, 8, 4];
1042        const EXPECTED: [u8; 9] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1043
1044        let sorted = Set::from_iter_dedup(CASE);
1045        assert_eq!(sorted.iter().copied().collect::<Vec<_>>(), EXPECTED);
1046
1047        let unsealed: Vec<_> = sorted.into();
1048        assert_eq!(unsealed, EXPECTED);
1049    }
1050
1051    #[test]
1052    fn test_sorted_unique_codec_roundtrip() {
1053        const CASE: [u8; 9] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1054        let sorted: Set<_> = CASE.try_into().unwrap();
1055
1056        let mut buf = Vec::with_capacity(sorted.encode_size());
1057        sorted.write(&mut buf);
1058        let decoded =
1059            Set::<u8>::read_cfg(&mut bytes::Bytes::from(buf), &(RangeCfg::from(0..=9), ()))
1060                .unwrap();
1061
1062        assert_eq!(sorted, decoded);
1063    }
1064
1065    #[test]
1066    fn test_sorted_unique_display() {
1067        const CASE: [u8; 9] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1068
1069        #[derive(Ord, PartialOrd, Eq, PartialEq)]
1070        struct Example(u8);
1071        impl fmt::Display for Example {
1072            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1073                write!(f, "ex({})", self.0)
1074            }
1075        }
1076        let sorted: Set<_> = Set::try_from_iter(CASE.into_iter().map(Example)).unwrap();
1077        assert_eq!(
1078            sorted.to_string(),
1079            "[ex(1), ex(2), ex(3), ex(4), ex(5), ex(6), ex(7), ex(8), ex(9)]"
1080        );
1081    }
1082
1083    #[test]
1084    fn test_set_from_iter_dedup() {
1085        let items = [3u8, 1u8, 2u8, 2u8];
1086        let set = Set::from_iter_dedup(items);
1087        assert_eq!(set.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3]);
1088    }
1089
1090    #[test]
1091    fn test_set_try_from_duplicate() {
1092        let result: Result<Set<u8>, _> = vec![3u8, 1u8, 2u8, 2u8].try_into();
1093        assert_eq!(result, Err(Error::DuplicateKey));
1094    }
1095
1096    #[test]
1097    fn test_set_try_from_iter_duplicate() {
1098        let items = vec![3u8, 1u8, 2u8, 2u8];
1099        let result = Set::try_from_iter(items);
1100        assert_eq!(result, Err(Error::DuplicateKey));
1101    }
1102
1103    #[test]
1104    fn test_map_from_iter_dedup() {
1105        let items = vec![(3u8, "c"), (1u8, "a"), (2u8, "b"), (1u8, "duplicate")];
1106        let map = Map::from_iter_dedup(items);
1107
1108        assert_eq!(map.len(), 3);
1109        assert_eq!(map.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3]);
1110        assert_eq!(map.get_value(&1), Some(&"a"));
1111        assert_eq!(map.get_value(&4), None);
1112        assert_eq!(map.value(1), Some(&"b"));
1113    }
1114
1115    #[test]
1116    fn test_map_try_from() {
1117        let pairs = vec![(3u8, "c"), (1u8, "a"), (2u8, "b")];
1118        let wrapped: Map<_, _> = pairs.try_into().unwrap();
1119
1120        assert_eq!(wrapped.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3]);
1121        assert_eq!(wrapped.get_value(&2), Some(&"b"));
1122    }
1123
1124    #[test]
1125    fn test_map_try_from_duplicate() {
1126        let result: Result<Map<u8, &str>, _> =
1127            vec![(3u8, "c"), (1u8, "a"), (2u8, "b"), (1u8, "duplicate")].try_into();
1128        assert_eq!(result, Err(Error::DuplicateKey));
1129    }
1130
1131    #[test]
1132    fn test_map_try_from_iter_duplicate() {
1133        let pairs = vec![(3u8, "c"), (1u8, "a"), (2u8, "b"), (1u8, "duplicate")];
1134        let result = Map::try_from_iter(pairs);
1135        assert_eq!(result, Err(Error::DuplicateKey));
1136    }
1137
1138    #[test]
1139    fn test_map_deref_to_set() {
1140        fn sum(set: &Set<u8>) -> u32 {
1141            set.iter().map(|v| *v as u32).sum()
1142        }
1143
1144        let map: Map<_, _> = vec![(2u8, "b"), (1u8, "a")].try_into().unwrap();
1145        assert_eq!(sum(&map), 3);
1146    }
1147
1148    #[test]
1149    fn test_map_from_set() {
1150        let set: Set<_> = vec![(3u8, 'a'), (1u8, 'b'), (2u8, 'c')].try_into().unwrap();
1151        let wrapped: Map<_, _> = Map::try_from_iter(set.clone()).unwrap();
1152
1153        assert_eq!(
1154            set.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
1155            wrapped.keys().iter().copied().collect::<Vec<_>>(),
1156        );
1157    }
1158
1159    #[test]
1160    fn test_map_from_parts_reuses_allocations() {
1161        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1162        struct Key(u8);
1163        #[derive(Debug, PartialEq, Eq)]
1164        struct Value(u8);
1165
1166        let keys = Set::try_from([Key(3), Key(1), Key(2)]).unwrap();
1167        let values = vec![Value(30), Value(10), Value(10)];
1168        let keys_ptr = keys.as_ref().as_ptr();
1169        let values_ptr = values.as_ptr();
1170
1171        let map = Map::from_parts(keys, values).unwrap();
1172        assert_eq!(map.keys().as_ref().as_ptr(), keys_ptr);
1173        assert_eq!(map.values().as_ptr(), values_ptr);
1174        assert_eq!(map.keys().as_ref(), &[Key(1), Key(2), Key(3)]);
1175        assert_eq!(map.values(), &[Value(30), Value(10), Value(10)]);
1176    }
1177
1178    #[rstest]
1179    fn test_map_from_parts_lengths(
1180        #[values(0, 1, 3)] keys_len: usize,
1181        #[values(0, 1, 3)] values_len: usize,
1182    ) {
1183        let keys = Set::try_from_iter(0..keys_len).unwrap();
1184        let map = Map::from_parts(keys, vec![(); values_len]);
1185        assert_eq!(map.is_some(), keys_len == values_len);
1186        if let Some(map) = map {
1187            assert_eq!(map.len(), keys_len);
1188            assert_eq!(map.values().len(), values_len);
1189        }
1190    }
1191
1192    #[test]
1193    fn test_map_into_keys() {
1194        let map: Map<_, _> = vec![(3u8, "c"), (1u8, "a"), (2u8, "b")].try_into().unwrap();
1195        let keys = map.into_keys();
1196        assert_eq!(keys.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3]);
1197    }
1198
1199    #[test]
1200    fn test_values_mut() {
1201        let mut map: Map<u8, u8> = vec![(1u8, 10u8), (2, 20)].try_into().unwrap();
1202        for value in map.values_mut() {
1203            *value += 1;
1204        }
1205        assert_eq!(map.values(), &[11, 21]);
1206    }
1207
1208    #[test]
1209    fn test_map_values_borrowed() {
1210        struct Value(u8);
1211
1212        let map = Map::try_from([(3, Value(30)), (1, Value(10)), (2, Value(20))]).unwrap();
1213        let mapped = map.map_values(|key, value| (key, &value.0));
1214        let tried = map
1215            .try_map_values(|key, value| Ok::<_, ()>((key, &value.0)))
1216            .unwrap();
1217        for result in [mapped, tried] {
1218            assert_eq!(result.keys(), map.keys());
1219            assert_eq!(result.values(), &[(&1, &10), (&2, &20), (&3, &30)]);
1220        }
1221        assert_eq!(map.get_value(&2).unwrap().0, 20);
1222    }
1223
1224    #[rstest]
1225    #[case::infallible(false)]
1226    #[case::fallible(true)]
1227    fn test_map_values_into_reuses_keys(#[case] fallible: bool) {
1228        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1229        struct Key(u8);
1230        struct Value(u8);
1231
1232        let map = Map::try_from([
1233            (Key(3), Value(30)),
1234            (Key(1), Value(10)),
1235            (Key(2), Value(20)),
1236        ])
1237        .unwrap();
1238        let keys_ptr = map.keys().as_ref().as_ptr();
1239        let mut visited = Vec::new();
1240        let mut transform = |key: &Key, value: Value| {
1241            visited.push(key.0);
1242            key.0 + value.0
1243        };
1244        let mapped = if fallible {
1245            map.try_map_values_into(|key, value| Ok::<_, ()>(transform(key, value)))
1246                .unwrap()
1247        } else {
1248            map.map_values_into(transform)
1249        };
1250        assert_eq!(visited, [1, 2, 3]);
1251        assert_eq!(mapped.keys().as_ref().as_ptr(), keys_ptr);
1252        assert_eq!(mapped.keys().as_ref(), &[Key(1), Key(2), Key(3)]);
1253        assert_eq!(mapped.values(), &[11, 22, 33]);
1254    }
1255
1256    #[test]
1257    fn test_map_values_empty() {
1258        let map = Map::<u8, ()>::default();
1259        let mapped: Map<_, u32> = map.map_values(|_, _| unreachable!());
1260        assert!(mapped.is_empty());
1261        let mapped: Result<Map<_, u32>, ()> = map.try_map_values(|_, _| unreachable!());
1262        assert!(mapped.unwrap().is_empty());
1263        let mapped: Map<_, u32> = map.clone().map_values_into(|_, _| unreachable!());
1264        assert!(mapped.is_empty());
1265        let mapped: Result<Map<_, u32>, ()> = map.try_map_values_into(|_, _| unreachable!());
1266        assert!(mapped.unwrap().is_empty());
1267    }
1268
1269    #[rstest]
1270    #[case::borrowed(false)]
1271    #[case::owned(true)]
1272    fn test_try_map_values_error(#[case] owned: bool, #[values(1, 2, 3)] failed_key: usize) {
1273        struct Tracked<'a>(&'a Cell<usize>);
1274
1275        impl Drop for Tracked<'_> {
1276            fn drop(&mut self) {
1277                self.0.set(self.0.get() + 1);
1278            }
1279        }
1280
1281        let input_drops = Cell::new(0);
1282        let output_drops = Cell::new(0);
1283        let map = Map::try_from_iter((1..=3).map(|key| (key, Tracked(&input_drops)))).unwrap();
1284        let mut visited = Vec::new();
1285        let mut transform = |key: &usize| {
1286            visited.push(*key);
1287            if *key == failed_key {
1288                Err(*key)
1289            } else {
1290                Ok(Tracked(&output_drops))
1291            }
1292        };
1293        let result = if owned {
1294            map.try_map_values_into(|key, _| transform(key))
1295        } else {
1296            map.try_map_values(|key, _| transform(key))
1297        };
1298        assert_eq!(result.err(), Some(failed_key));
1299        assert_eq!(visited, (1..=failed_key).collect::<Vec<_>>());
1300        assert_eq!(input_drops.get(), if owned { 3 } else { 0 });
1301        assert_eq!(output_drops.get(), failed_key - 1);
1302    }
1303
1304    #[test]
1305    fn test_pair_iterators() {
1306        fn check(mut pairs: impl ExactSizeIterator<Item = (u8, u8)> + DoubleEndedIterator) {
1307            assert_eq!(pairs.len(), 3);
1308            assert_eq!(pairs.next(), Some((1, 10)));
1309            assert_eq!(pairs.len(), 2);
1310            assert_eq!(pairs.next_back(), Some((3, 30)));
1311            assert_eq!(pairs.len(), 1);
1312            assert_eq!(pairs.next_back(), Some((2, 20)));
1313            assert_eq!(pairs.len(), 0);
1314            assert_eq!(pairs.next(), None);
1315            assert_eq!(pairs.next_back(), None);
1316        }
1317
1318        let mut map = Map::try_from([(3, 30), (1, 10), (2, 20)]).unwrap();
1319        check(map.iter_pairs().map(|(&key, &value)| (key, value)));
1320        check(map.iter_pairs_mut().map(|(&key, value)| {
1321            let previous = *value;
1322            *value += key;
1323            (key, previous)
1324        }));
1325        assert_eq!(map.values(), &[11, 22, 33]);
1326        let bimap = BiMap::try_from([(3, 30), (1, 10), (2, 20)]).unwrap();
1327        check(bimap.iter_pairs().map(|(&key, &value)| (key, value)));
1328    }
1329
1330    #[test]
1331    fn test_map_allows_duplicate_values() {
1332        let items = vec![(1u8, "a"), (2u8, "b"), (3u8, "a")];
1333        let map: Map<_, _> = items.try_into().unwrap();
1334        assert_eq!(map.len(), 3);
1335        assert_eq!(map.get_value(&1), Some(&"a"));
1336        assert_eq!(map.get_value(&3), Some(&"a"));
1337    }
1338
1339    #[test]
1340    fn test_bimap_duplicate_value_error() {
1341        let items = vec![(1u8, "a"), (2u8, "b"), (3u8, "a")];
1342        let result = BiMap::try_from_iter(items);
1343        assert_eq!(result, Err(Error::DuplicateValue));
1344    }
1345
1346    #[test]
1347    fn test_bimap_no_duplicate_values() {
1348        let items = vec![(1u8, "a"), (2u8, "b"), (3u8, "c")];
1349        let result = BiMap::try_from_iter(items);
1350        assert!(result.is_ok());
1351        let map = result.unwrap();
1352        assert_eq!(map.len(), 3);
1353        assert_eq!(map.get_value(&1), Some(&"a"));
1354        assert_eq!(map.get_value(&2), Some(&"b"));
1355        assert_eq!(map.get_value(&3), Some(&"c"));
1356    }
1357
1358    #[test]
1359    fn test_bimap_try_from_map() {
1360        let items = vec![(1u8, "a"), (2u8, "b"), (3u8, "c")];
1361        let map: Map<_, _> = items.try_into().unwrap();
1362        let bimap = BiMap::try_from(map).unwrap();
1363        assert_eq!(bimap.len(), 3);
1364        assert_eq!(bimap.get_value(&1), Some(&"a"));
1365    }
1366
1367    #[test]
1368    fn test_bimap_get_key() {
1369        let items = vec![(1u8, "a"), (2u8, "b"), (3u8, "c")];
1370        let bimap: BiMap<_, _> = items.try_into().unwrap();
1371        assert_eq!(bimap.get_key(&"a"), Some(&1));
1372        assert_eq!(bimap.get_key(&"b"), Some(&2));
1373        assert_eq!(bimap.get_key(&"c"), Some(&3));
1374        assert_eq!(bimap.get_key(&"d"), None);
1375    }
1376
1377    #[test]
1378    fn test_bimap_try_from_map_duplicate() {
1379        let items = vec![(1u8, "a"), (2u8, "b"), (3u8, "a")];
1380        let map: Map<_, _> = items.try_into().unwrap();
1381        let result = BiMap::try_from(map);
1382        assert_eq!(result, Err(Error::DuplicateValue));
1383    }
1384
1385    #[test]
1386    fn test_bimap_decode_rejects_duplicate_values() {
1387        let items = vec![(1u8, 10u8), (2, 20), (3, 10)];
1388        let map: Map<_, _> = items.try_into().unwrap();
1389
1390        let mut buf = Vec::with_capacity(map.encode_size());
1391        map.write(&mut buf);
1392
1393        let cfg = (RangeCfg::from(0..=10), (), ());
1394        let result = BiMap::<u8, u8>::read_cfg(&mut bytes::Bytes::from(buf), &cfg);
1395        assert!(result.is_err());
1396    }
1397
1398    #[test]
1399    fn test_set_decode_rejects_duplicates() {
1400        let items: Vec<u8> = vec![1, 2, 2, 3];
1401        let mut buf = Vec::new();
1402        items.write(&mut buf);
1403
1404        let cfg = (RangeCfg::from(0..=10), ());
1405        let result = Set::<u8>::read_cfg(&mut bytes::Bytes::from(buf), &cfg);
1406        assert!(result.is_err());
1407    }
1408
1409    #[test]
1410    fn test_set_decode_rejects_unsorted() {
1411        let items: Vec<u8> = vec![1, 3, 2, 4];
1412        let mut buf = Vec::new();
1413        items.write(&mut buf);
1414
1415        let cfg = (RangeCfg::from(0..=10), ());
1416        let result = Set::<u8>::read_cfg(&mut bytes::Bytes::from(buf), &cfg);
1417        assert!(result.is_err());
1418    }
1419
1420    #[test]
1421    fn test_set_decode_accepts_valid() {
1422        let items: Vec<u8> = vec![1, 2, 3, 4];
1423        let mut buf = Vec::new();
1424        items.write(&mut buf);
1425
1426        let cfg = (RangeCfg::from(0..=10), ());
1427        let result = Set::<u8>::read_cfg(&mut bytes::Bytes::from(buf), &cfg);
1428        assert!(result.is_ok());
1429        assert_eq!(result.unwrap().iter().copied().collect::<Vec<_>>(), items);
1430    }
1431
1432    #[test]
1433    fn test_map_decode_rejects_duplicate_keys() {
1434        let keys: Vec<u8> = vec![1, 2, 2, 3];
1435        let values: Vec<u8> = vec![10, 20, 30, 40];
1436        let mut buf = Vec::new();
1437        keys.write(&mut buf);
1438        values.write(&mut buf);
1439
1440        let cfg = (RangeCfg::from(0..=10), (), ());
1441        let result = Map::<u8, u8>::read_cfg(&mut bytes::Bytes::from(buf), &cfg);
1442        assert!(result.is_err());
1443    }
1444
1445    #[test]
1446    fn test_map_decode_rejects_unsorted_keys() {
1447        let keys: Vec<u8> = vec![1, 3, 2, 4];
1448        let values: Vec<u8> = vec![10, 20, 30, 40];
1449        let mut buf = Vec::new();
1450        keys.write(&mut buf);
1451        values.write(&mut buf);
1452
1453        let cfg = (RangeCfg::from(0..=10), (), ());
1454        let result = Map::<u8, u8>::read_cfg(&mut bytes::Bytes::from(buf), &cfg);
1455        assert!(result.is_err());
1456    }
1457
1458    #[test]
1459    fn test_map_decode_accepts_valid() {
1460        let keys: Vec<u8> = vec![1, 2, 3, 4];
1461        let values: Vec<u8> = vec![10, 20, 30, 40];
1462        let mut buf = Vec::new();
1463        keys.write(&mut buf);
1464        values.write(&mut buf);
1465
1466        let cfg = (RangeCfg::from(0..=10), (), ());
1467        let result = Map::<u8, u8>::read_cfg(&mut bytes::Bytes::from(buf), &cfg);
1468        assert!(result.is_ok());
1469        let map = result.unwrap();
1470        assert_eq!(map.keys().iter().copied().collect::<Vec<_>>(), keys);
1471        assert_eq!(map.values(), values.as_slice());
1472    }
1473
1474    #[cfg(feature = "arbitrary")]
1475    mod conformance {
1476        use super::*;
1477        use commonware_codec::conformance::CodecConformance;
1478
1479        commonware_conformance::conformance_tests! {
1480            CodecConformance<Set<u32>>,
1481            CodecConformance<Map<u32, u32>>,
1482            CodecConformance<BiMap<u32, u32>>,
1483        }
1484    }
1485}