use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt::{self, Debug};
use std::hash::{Hash, Hasher};
use smallvec::Array;
use crate::SmallOrdSet;
#[derive(Copy, Clone, Default)]
pub struct KeyValuePair<K, V> {
pub key: K,
pub value: V,
}
impl<A, K, V> SmallOrdSet<A>
where
A: Array<Item = KeyValuePair<K, V>>,
K: Ord,
{
pub fn insert_value(&mut self, key: K, value: V) -> bool {
self.insert(KeyValuePair { key, value })
}
pub fn replace_value(&mut self, key: K, value: V) -> Option<V> {
self.replace(KeyValuePair { key, value })
.map(|kvp| kvp.value)
}
pub fn remove_value(&mut self, key: &K) -> Option<V> {
self.remove(key).map(|kvp| kvp.value)
}
pub fn get_value<'a>(&'a self, key: &K) -> Option<&'a V>
where
K: 'a,
{
self.get(key).map(|kvp| &kvp.value)
}
pub fn get_value_mut<'a>(&'a mut self, key: &K) -> Option<&'a mut V>
where
K: 'a,
{
self.get_mut(key).map(|kvp| &mut kvp.value)
}
pub fn keys<'a>(&'a self) -> impl Iterator<Item = &'a K> + Clone
where
KeyValuePair<K, V>: 'a,
{
self.iter().map(|kvp| &kvp.key)
}
pub fn values<'a>(&'a self) -> impl Iterator<Item = &'a V> + Clone
where
KeyValuePair<K, V>: 'a,
{
self.iter().map(|kvp| &kvp.value)
}
}
impl<K: Hash, V> Hash for KeyValuePair<K, V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.key.hash(state)
}
}
impl<K: PartialEq, V> PartialEq for KeyValuePair<K, V> {
fn eq(&self, other: &Self) -> bool {
PartialEq::eq(&self.key, &other.key)
}
}
impl<K: Eq, V> Eq for KeyValuePair<K, V> {}
impl<K: PartialOrd, V> PartialOrd for KeyValuePair<K, V> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
PartialOrd::partial_cmp(&self.key, &other.key)
}
}
impl<K: Ord, V> Ord for KeyValuePair<K, V> {
fn cmp(&self, other: &Self) -> Ordering {
Ord::cmp(&self.key, &other.key)
}
}
impl<K: Debug, V: Debug> Debug for KeyValuePair<K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}: {:?}", self.key, self.value)
}
}
impl<K, V> Borrow<K> for KeyValuePair<K, V> {
fn borrow(&self) -> &K {
&self.key
}
}