use super::KeyValueComparer;
use crate::cache::{IKeyValueCollection, SortOptimisations, SortReason};
use std::fmt;
use std::ops::Deref;
use std::rc::Rc;
pub struct KeyValueCollection<T, K> {
items: Rc<[(K, T)]>,
comparer: KeyValueComparer<T, K>,
sort_reason: SortReason,
optimisations: SortOptimisations,
}
impl<T, K> Clone for KeyValueCollection<T, K> {
fn clone(&self) -> Self {
Self { items: self.items.clone(), comparer: self.comparer.clone(), sort_reason: self.sort_reason, optimisations: self.optimisations }
}
}
impl<T, K> Default for KeyValueCollection<T, K> {
fn default() -> Self {
Self::empty()
}
}
impl<T, K> KeyValueCollection<T, K> {
pub fn new(items: Vec<(K, T)>, comparer: KeyValueComparer<T, K>, sort_reason: SortReason, optimisations: SortOptimisations) -> Self {
Self { items: Rc::from(items), comparer, sort_reason, optimisations }
}
pub fn empty() -> Self {
Self::new(Vec::new(), KeyValueComparer::new(None), SortReason::InitialLoad, SortOptimisations::NONE)
}
pub fn comparer(&self) -> &KeyValueComparer<T, K> {
&self.comparer
}
pub fn count(&self) -> usize {
self.items.len()
}
pub fn optimisations(&self) -> SortOptimisations {
self.optimisations
}
pub fn sort_reason(&self) -> SortReason {
self.sort_reason
}
pub fn items(&self) -> &[(K, T)] {
&self.items
}
pub fn to_vec(&self) -> Vec<(K, T)>
where
T: Clone,
K: Clone,
{
self.items.to_vec()
}
pub fn values(&self) -> impl Iterator<Item = &T> {
self.items.iter().map(|(_, value)| value)
}
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.items.iter().map(|(key, _)| key)
}
pub fn ptr_eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.items, &other.items)
}
}
impl<T, K> Deref for KeyValueCollection<T, K> {
type Target = [(K, T)];
fn deref(&self) -> &Self::Target {
&self.items
}
}
impl<'a, T, K> IntoIterator for &'a KeyValueCollection<T, K> {
type Item = &'a (K, T);
type IntoIter = std::slice::Iter<'a, (K, T)>;
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
impl<T: PartialEq, K: PartialEq> PartialEq for KeyValueCollection<T, K> {
fn eq(&self, other: &Self) -> bool {
self.items == other.items
}
}
impl<T: fmt::Debug, K: fmt::Debug> fmt::Debug for KeyValueCollection<T, K> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.items.iter()).finish()
}
}
impl<T, K> IKeyValueCollection<T, K> for KeyValueCollection<T, K> {
fn comparer(&self) -> &KeyValueComparer<T, K> {
&self.comparer
}
fn optimisations(&self) -> SortOptimisations {
self.optimisations
}
fn sort_reason(&self) -> SortReason {
self.sort_reason
}
fn items(&self) -> &[(K, T)] {
&self.items
}
}