1use std::borrow::Borrow;
2use std::cmp::Ordering;
3use std::fmt::{self, Debug};
4use std::hash::{Hash, Hasher};
5
6use smallvec::Array;
7
8use crate::SmallOrdSet;
9
10#[derive(Copy, Clone, Default)]
16pub struct KeyValuePair<K, V> {
17 pub key: K,
19 pub value: V,
21}
22
23impl<A, K, V> SmallOrdSet<A>
24where
25 A: Array<Item = KeyValuePair<K, V>>,
26 K: Ord,
27{
28 pub fn insert_value(&mut self, key: K, value: V) -> bool {
32 self.insert(KeyValuePair { key, value })
33 }
34
35 pub fn replace_value(&mut self, key: K, value: V) -> Option<V> {
39 self.replace(KeyValuePair { key, value })
40 .map(|kvp| kvp.value)
41 }
42
43 pub fn remove_value(&mut self, key: &K) -> Option<V> {
47 self.remove(key).map(|kvp| kvp.value)
48 }
49
50 pub fn get_value<'a>(&'a self, key: &K) -> Option<&'a V>
54 where
55 K: 'a,
56 {
57 self.get(key).map(|kvp| &kvp.value)
58 }
59
60 pub fn get_value_mut<'a>(&'a mut self, key: &K) -> Option<&'a mut V>
66 where
67 K: 'a,
68 {
69 self.get_mut(key).map(|kvp| &mut kvp.value)
70 }
71
72 pub fn keys<'a>(&'a self) -> impl Iterator<Item = &'a K> + Clone
74 where
75 KeyValuePair<K, V>: 'a,
76 {
77 self.iter().map(|kvp| &kvp.key)
78 }
79
80 pub fn values<'a>(&'a self) -> impl Iterator<Item = &'a V> + Clone
82 where
83 KeyValuePair<K, V>: 'a,
84 {
85 self.iter().map(|kvp| &kvp.value)
86 }
87}
88
89impl<K: Hash, V> Hash for KeyValuePair<K, V> {
90 fn hash<H: Hasher>(&self, state: &mut H) {
91 self.key.hash(state)
92 }
93}
94
95impl<K: PartialEq, V> PartialEq for KeyValuePair<K, V> {
96 fn eq(&self, other: &Self) -> bool {
97 PartialEq::eq(&self.key, &other.key)
98 }
99}
100
101impl<K: Eq, V> Eq for KeyValuePair<K, V> {}
102
103impl<K: PartialOrd, V> PartialOrd for KeyValuePair<K, V> {
104 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
105 PartialOrd::partial_cmp(&self.key, &other.key)
106 }
107}
108
109impl<K: Ord, V> Ord for KeyValuePair<K, V> {
110 fn cmp(&self, other: &Self) -> Ordering {
111 Ord::cmp(&self.key, &other.key)
112 }
113}
114
115impl<K: Debug, V: Debug> Debug for KeyValuePair<K, V> {
116 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
117 write!(f, "{:?}: {:?}", self.key, self.value)
118 }
119}
120
121impl<K, V> Borrow<K> for KeyValuePair<K, V> {
122 fn borrow(&self) -> &K {
123 &self.key
124 }
125}