Skip to main content

mln_wire/
sorted.rs

1//! Hash maps and sets written in key order, so that the same
2//! value always encodes to the same bytes.
3
4#![expect(clippy::disallowed_types, reason = "maps and sets of every hasher, mln_style's among them")]
5
6/// `#[wire(with)]` for a `HashMap` with ordered keys.
7pub mod map {
8    use std::collections::HashMap;
9    use std::hash::{BuildHasher, Hash};
10
11    /// Writes the entries in key order. Keys are unique, so an unstable sort
12    /// gives the same order.
13    pub fn write<K: Ord + crate::Wire, V: crate::Wire, S>(map: &HashMap<K, V, S>, w: &mut crate::Writer) {
14        let mut entries: Vec<(&K, &V)> = map.iter().collect();
15        entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
16        crate::Wire::write(&entries.len(), w);
17        for (k, v) in entries {
18            k.write(w);
19            v.write(w);
20        }
21    }
22
23    pub fn read<K, V, S>(r: &mut crate::Reader<'_>) -> Option<HashMap<K, V, S>>
24    where
25        K: Eq + Hash + crate::Wire,
26        V: crate::Wire,
27        S: BuildHasher + Default,
28    {
29        let len = r.length()?;
30        let mut map = HashMap::with_capacity_and_hasher(len.min(r.rest().len()), S::default());
31        for _ in 0..len {
32            let k = K::read(r)?;
33            map.insert(k, V::read(r)?);
34        }
35        Some(map)
36    }
37}
38
39/// `#[wire(with)]` for a `HashSet` of ordered values.
40pub mod set {
41    use std::collections::HashSet;
42    use std::hash::{BuildHasher, Hash};
43
44    /// Writes the values in order.
45    pub fn write<T: Ord + crate::Wire, S>(set: &HashSet<T, S>, w: &mut crate::Writer) {
46        let mut values: Vec<&T> = set.iter().collect();
47        values.sort_unstable();
48        crate::Wire::write(&values.len(), w);
49        for value in values {
50            value.write(w);
51        }
52    }
53
54    pub fn read<T, S>(r: &mut crate::Reader<'_>) -> Option<HashSet<T, S>>
55    where
56        T: Eq + Hash + crate::Wire,
57        S: BuildHasher + Default,
58    {
59        let len = r.length()?;
60        let mut set = HashSet::with_capacity_and_hasher(len.min(r.rest().len()), S::default());
61        for _ in 0..len {
62            set.insert(T::read(r)?);
63        }
64        Some(set)
65    }
66}