osom_lib_hash_tables/
std_hash_map.rs1#![allow(clippy::implicit_hasher)]
2use core::borrow::Borrow;
3use core::hash::Hash;
4
5use std::collections::{HashMap, hash_map::Entry};
6
7use osom_lib_primitives::length::Length;
8
9use crate::traits::{ImmutableHashTable, MutableHashTable};
10
11impl<TKey, TValue> ImmutableHashTable<TKey, TValue> for HashMap<TKey, TValue>
12where
13 TKey: Hash + Eq,
14{
15 #[inline]
16 fn length(&self) -> Length {
17 Length::try_from_usize(self.len()).unwrap()
18 }
19
20 #[inline]
21 fn contains<Q>(&self, key: &Q) -> bool
22 where
23 TKey: Borrow<Q>,
24 Q: Eq + core::hash::Hash + ?Sized,
25 {
26 self.contains_key(key)
27 }
28
29 #[inline]
30 fn get<Q>(&self, key: &Q) -> Option<&TValue>
31 where
32 TKey: Borrow<Q>,
33 Q: Eq + core::hash::Hash + ?Sized,
34 {
35 self.get(key)
36 }
37
38 #[inline]
39 fn get_key_value<Q>(&self, key: &Q) -> Option<(&TKey, &TValue)>
40 where
41 TKey: Borrow<Q>,
42 Q: Eq + core::hash::Hash + ?Sized,
43 {
44 self.get_key_value(key)
45 }
46
47 #[inline]
48 fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a TKey, &'a TValue)>
49 where
50 TKey: 'a,
51 TValue: 'a,
52 Self: 'a,
53 {
54 self.iter()
55 }
56}
57
58impl<TKey, TValue> MutableHashTable<TKey, TValue> for HashMap<TKey, TValue>
59where
60 TKey: Hash + Eq,
61{
62 #[inline]
63 fn insert(&mut self, key: TKey, value: TValue) -> Option<TValue> {
64 self.insert(key, value)
65 }
66
67 #[inline]
68 fn remove_entry<Q>(&mut self, key: &Q) -> Option<(TKey, TValue)>
69 where
70 TKey: Borrow<Q>,
71 Q: Eq + Hash + ?Sized,
72 {
73 self.remove_entry(key)
74 }
75
76 #[inline]
77 fn insert_or_update_with<FAdd, FUpdate>(&mut self, key: TKey, adder: FAdd, updater: FUpdate) -> &mut TValue
78 where
79 FAdd: FnOnce() -> TValue,
80 FUpdate: FnOnce(&mut TValue),
81 {
82 match self.entry(key) {
83 Entry::Occupied(mut o) => {
84 updater(o.get_mut());
85 o.into_mut()
86 }
87 Entry::Vacant(v) => v.insert(adder()),
88 }
89 }
90
91 #[inline]
92 fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = (&'a TKey, &'a mut TValue)>
93 where
94 TKey: 'a,
95 TValue: 'a,
96 Self: 'a,
97 {
98 self.iter_mut()
99 }
100}