Skip to main content

clt_database/alloc/collections/
hash_map.rs

1use std::hash::{BuildHasher, Hash};
2
3use rustc_hash::FxBuildHasher;
4
5use super::{TryClone, TursoFromIterator, TursoHashMapExt, TursoTryWithCapacityExt};
6use crate::alloc::{HashMap, TryReserveError};
7
8impl<K, V, S> TursoHashMapExt<K, V> for HashMap<K, V, S>
9where
10    K: Eq + Hash,
11    S: BuildHasher,
12{
13    #[inline(always)]
14    fn try_insert(&mut self, key: K, value: V) -> Result<Option<V>, TryReserveError> {
15        Ok(self.insert(key, value))
16    }
17}
18
19impl<K, V> TursoTryWithCapacityExt for HashMap<K, V>
20where
21    K: Eq + Hash,
22{
23    #[inline(always)]
24    fn try_with_capacity_ext(capacity: usize) -> Result<Self, TryReserveError> {
25        Ok(HashMap::with_capacity_and_hasher(capacity, FxBuildHasher))
26    }
27}
28
29impl<K, V> TursoFromIterator<(K, V)> for HashMap<K, V>
30where
31    K: Eq + Hash,
32{
33    #[inline(always)]
34    fn try_from_iter<I>(iter: I) -> Result<Self, TryReserveError>
35    where
36        I: IntoIterator<Item = (K, V)>,
37    {
38        Ok(iter.into_iter().collect())
39    }
40
41    #[inline(always)]
42    fn try_extend<I>(&mut self, iter: I) -> Result<(), TryReserveError>
43    where
44        I: IntoIterator<Item = (K, V)>,
45    {
46        self.extend(iter);
47        Ok(())
48    }
49}
50
51impl<K, V> TryClone for HashMap<K, V>
52where
53    K: Clone + Eq + Hash,
54    V: Clone,
55{
56    type Error = TryReserveError;
57
58    #[inline(always)]
59    fn try_clone(&self) -> Result<Self, Self::Error> {
60        let mut cloned = Self::with_hasher(*self.hasher());
61        cloned.try_reserve(self.len())?;
62        // TODO: have a `TryClone` boundary for K and V here instead of `Clone`
63        cloned.extend(self.iter().map(|(key, value)| (key.clone(), value.clone())));
64        Ok(cloned)
65    }
66}