use sp_std::{
borrow::{
Borrow,
ToOwned,
},
cmp::Ordering,
collections::btree_map::{
self,
BTreeMap,
},
fmt::{
Debug,
Error,
Formatter,
},
hash::{
Hash,
Hasher,
},
iter::{
FromIterator,
Iterator,
Sum,
},
mem,
ops::{
Add,
Index,
IndexMut,
RangeBounds,
},
vec::Vec,
};
#[cfg(has_specialisation)]
use crate::util::linear_search_by;
use crate::{
nodes::btree::{
BTreeValue,
Insert,
Node,
Remove,
},
util::{
Pool,
PoolRef,
},
};
pub use crate::nodes::btree::{
ConsumingIter,
DiffItem as NodeDiffItem,
DiffIter as NodeDiffIter,
Iter as RangedIter,
};
#[macro_export]
macro_rules! ordmap {
() => { $crate::ordmap::OrdMap::new() };
( $( $key:expr => $value:expr ),* ) => {{
let mut map = $crate::ordmap::OrdMap::new();
$({
map.insert($key, $value);
})*;
map
}};
}
#[cfg(not(has_specialisation))]
impl<K: Ord, V> BTreeValue for (K, V) {
type Key = K;
fn ptr_eq(&self, _other: &Self) -> bool { false }
fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>, {
slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
}
fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
slice.binary_search_by(|value| value.0.cmp(&key.0))
}
fn cmp_keys<BK>(&self, other: &BK) -> Ordering
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>, {
Self::Key::borrow(&self.0).cmp(other)
}
fn cmp_values(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) }
}
#[cfg(has_specialisation)]
impl<K: Ord, V> BTreeValue for (K, V) {
type Key = K;
fn ptr_eq(&self, _other: &Self) -> bool { false }
default fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>, {
slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
}
default fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
slice.binary_search_by(|value| value.0.cmp(&key.0))
}
fn cmp_keys<BK>(&self, other: &BK) -> Ordering
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>, {
Self::Key::borrow(&self.0).cmp(other)
}
fn cmp_values(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) }
}
#[cfg(has_specialisation)]
impl<K: Ord + Copy, V> BTreeValue for (K, V) {
fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>, {
linear_search_by(slice, |value| Self::Key::borrow(&value.0).cmp(key))
}
fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
linear_search_by(slice, |value| value.0.cmp(&key.0))
}
}
def_pool!(OrdMapPool<K, V>, Node<(K, V)>);
pub struct OrdMap<K, V> {
size: usize,
pool: OrdMapPool<K, V>,
root: PoolRef<Node<(K, V)>>,
}
impl<K, V> OrdMap<K, V> {
#[must_use]
pub fn new() -> Self {
let pool = OrdMapPool::default();
let root = PoolRef::default(&pool.0);
OrdMap { size: 0, pool, root }
}
#[cfg(feature = "pool")]
#[must_use]
pub fn with_pool(pool: &OrdMapPool<K, V>) -> Self {
let root = PoolRef::default(&pool.0);
OrdMap { size: 0, pool: pool.clone(), root }
}
#[inline]
#[must_use]
pub fn unit(key: K, value: V) -> Self {
let pool = OrdMapPool::default();
let root = PoolRef::new(&pool.0, Node::unit((key, value)));
OrdMap { size: 1, pool, root }
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool { self.len() == 0 }
pub fn ptr_eq(&self, other: &Self) -> bool {
sp_std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root)
}
#[inline]
#[must_use]
pub fn len(&self) -> usize { self.size }
#[cfg(feature = "pool")]
pub fn pool(&self) -> &OrdMapPool<K, V> { &self.pool }
pub fn clear(&mut self) {
if !self.is_empty() {
self.root = PoolRef::default(&self.pool.0);
self.size = 0;
}
}
}
impl<K, V> OrdMap<K, V>
where K: Ord
{
#[must_use]
pub fn get_max(&self) -> Option<&(K, V)> { self.root.max() }
#[must_use]
pub fn get_min(&self) -> Option<&(K, V)> { self.root.min() }
#[must_use]
pub fn iter(&self) -> Iter<'_, K, V> {
Iter { it: RangedIter::new(&self.root, self.size, ..) }
}
#[must_use]
pub fn range<R, BK>(&self, range: R) -> Iter<'_, K, V>
where
R: RangeBounds<BK>,
K: Borrow<BK>,
BK: Ord + ?Sized, {
Iter { it: RangedIter::new(&self.root, self.size, range) }
}
#[must_use]
pub fn keys(&self) -> Keys<'_, K, V> { Keys { it: self.iter() } }
#[must_use]
pub fn values(&self) -> Values<'_, K, V> { Values { it: self.iter() } }
#[must_use]
pub fn diff<'a>(&'a self, other: &'a Self) -> DiffIter<'a, K, V> {
DiffIter { it: NodeDiffIter::new(&self.root, &other.root) }
}
#[must_use]
pub fn get<BK>(&self, key: &BK) -> Option<&V>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.root.lookup(key).map(|(_, v)| v)
}
#[must_use]
pub fn get_key_value<BK>(&self, key: &BK) -> Option<(&K, &V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.root.lookup(key).map(|&(ref k, ref v)| (k, v))
}
#[must_use]
pub fn get_prev<BK>(&self, key: &BK) -> Option<(&K, &V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.root.lookup_prev(key).map(|(k, v)| (k, v))
}
#[must_use]
pub fn get_next<BK>(&self, key: &BK) -> Option<(&K, &V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.root.lookup_next(key).map(|(k, v)| (k, v))
}
#[must_use]
pub fn contains_key<BK>(&self, k: &BK) -> bool
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.get(k).is_some()
}
#[must_use]
pub fn is_submap_by<B, RM, F>(&self, other: RM, mut cmp: F) -> bool
where
F: FnMut(&V, &B) -> bool,
RM: Borrow<OrdMap<K, B>>, {
self
.iter()
.all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
}
#[must_use]
pub fn is_proper_submap_by<B, RM, F>(&self, other: RM, cmp: F) -> bool
where
F: FnMut(&V, &B) -> bool,
RM: Borrow<OrdMap<K, B>>, {
self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
}
#[must_use]
pub fn is_submap<RM>(&self, other: RM) -> bool
where
V: PartialEq,
RM: Borrow<Self>, {
self.is_submap_by(other.borrow(), PartialEq::eq)
}
#[must_use]
pub fn is_proper_submap<RM>(&self, other: RM) -> bool
where
V: PartialEq,
RM: Borrow<Self>, {
self.is_proper_submap_by(other.borrow(), PartialEq::eq)
}
}
impl<K, V> OrdMap<K, V>
where
K: Ord + Clone,
V: Clone,
{
#[must_use]
pub fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
root.lookup_mut(&self.pool.0, key).map(|(_, v)| v)
}
#[must_use]
pub fn get_prev_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
let pool = &self.pool.0;
PoolRef::make_mut(pool, &mut self.root)
.lookup_prev_mut(pool, key)
.map(|(ref k, ref mut v)| (k, v))
}
#[must_use]
pub fn get_next_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
let pool = &self.pool.0;
PoolRef::make_mut(pool, &mut self.root)
.lookup_next_mut(pool, key)
.map(|(ref k, ref mut v)| (k, v))
}
#[inline]
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
let new_root = {
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
match root.insert(&self.pool.0, (key, value)) {
Insert::Replaced((_, old_value)) => return Some(old_value),
Insert::Added => {
self.size += 1;
return None;
}
Insert::Split(left, median, right) => PoolRef::new(
&self.pool.0,
Node::new_from_split(&self.pool.0, left, median, right),
),
}
};
self.size += 1;
self.root = new_root;
None
}
#[inline]
pub fn remove<BK>(&mut self, k: &BK) -> Option<V>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.remove_with_key(k).map(|(_, v)| v)
}
pub fn remove_with_key<BK>(&mut self, k: &BK) -> Option<(K, V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
let (new_root, removed_value) = {
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
match root.remove(&self.pool.0, k) {
Remove::NoChange => return None,
Remove::Removed(pair) => {
self.size -= 1;
return Some(pair);
}
Remove::Update(pair, root) => {
(PoolRef::new(&self.pool.0, root), Some(pair))
}
}
};
self.size -= 1;
self.root = new_root;
removed_value
}
#[must_use]
pub fn update(&self, key: K, value: V) -> Self {
let mut out = self.clone();
out.insert(key, value);
out
}
#[must_use]
pub fn update_with<F>(self, k: K, v: V, f: F) -> Self
where F: FnOnce(V, V) -> V {
self.update_with_key(k, v, |_, v1, v2| f(v1, v2))
}
#[must_use]
pub fn update_with_key<F>(self, k: K, v: V, f: F) -> Self
where F: FnOnce(&K, V, V) -> V {
match self.extract_with_key(&k) {
None => self.update(k, v),
Some((_, v2, m)) => {
let out_v = f(&k, v2, v);
m.update(k, out_v)
}
}
}
#[must_use]
pub fn update_lookup_with_key<F>(
self,
k: K,
v: V,
f: F,
) -> (Option<V>, Self)
where
F: FnOnce(&K, &V, V) -> V,
{
match self.extract_with_key(&k) {
None => (None, self.update(k, v)),
Some((_, v2, m)) => {
let out_v = f(&k, &v2, v);
(Some(v2), m.update(k, out_v))
}
}
}
#[must_use]
pub fn alter<F>(&self, f: F, k: K) -> Self
where F: FnOnce(Option<V>) -> Option<V> {
let pop = self.extract_with_key(&k);
match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) {
(None, None) => self.clone(),
(Some(v), None) => self.update(k, v),
(None, Some((_, _, m))) => m,
(Some(v), Some((_, _, m))) => m.update(k, v),
}
}
#[must_use]
pub fn without<BK>(&self, k: &BK) -> Self
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.extract(k).map(|(_, m)| m).unwrap_or_else(|| self.clone())
}
#[must_use]
pub fn extract<BK>(&self, k: &BK) -> Option<(V, Self)>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.extract_with_key(k).map(|(_, v, m)| (v, m))
}
#[must_use]
pub fn extract_with_key<BK>(&self, k: &BK) -> Option<(K, V, Self)>
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
let mut out = self.clone();
let result = out.remove_with_key(k);
result.map(|(k, v)| (k, v, out))
}
#[inline]
#[must_use]
pub fn union(mut self, other: Self) -> Self {
for (k, v) in other {
self.entry(k).or_insert(v);
}
self
}
#[inline]
#[must_use]
pub fn union_with<F>(self, other: Self, mut f: F) -> Self
where F: FnMut(V, V) -> V {
self.union_with_key(other, |_, v1, v2| f(v1, v2))
}
#[must_use]
pub fn union_with_key<F>(mut self, other: Self, mut f: F) -> Self
where F: FnMut(&K, V, V) -> V {
for (key, right_value) in other {
match self.remove(&key) {
None => {
self.insert(key, right_value);
}
Some(left_value) => {
let final_value = f(&key, left_value, right_value);
self.insert(key, final_value);
}
}
}
self
}
#[must_use]
pub fn unions<I>(i: I) -> Self
where I: IntoIterator<Item = Self> {
i.into_iter().fold(Self::default(), Self::union)
}
#[must_use]
pub fn unions_with<I, F>(i: I, f: F) -> Self
where
I: IntoIterator<Item = Self>,
F: Fn(V, V) -> V, {
i.into_iter().fold(Self::default(), |a, b| a.union_with(b, &f))
}
#[must_use]
pub fn unions_with_key<I, F>(i: I, f: F) -> Self
where
I: IntoIterator<Item = Self>,
F: Fn(&K, V, V) -> V, {
i.into_iter().fold(Self::default(), |a, b| a.union_with_key(b, &f))
}
#[inline]
#[must_use]
pub fn difference(self, other: Self) -> Self {
self.symmetric_difference(other)
}
#[inline]
#[must_use]
pub fn symmetric_difference(self, other: Self) -> Self {
self.symmetric_difference_with_key(other, |_, _, _| None)
}
#[inline]
#[must_use]
pub fn difference_with<F>(self, other: Self, f: F) -> Self
where F: FnMut(V, V) -> Option<V> {
self.symmetric_difference_with(other, f)
}
#[inline]
#[must_use]
pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
where F: FnMut(V, V) -> Option<V> {
self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
}
#[must_use]
pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
where F: FnMut(&K, V, V) -> Option<V> {
self.symmetric_difference_with_key(other, f)
}
#[must_use]
pub fn symmetric_difference_with_key<F>(
mut self,
other: Self,
mut f: F,
) -> Self
where
F: FnMut(&K, V, V) -> Option<V>,
{
let mut out = Self::default();
for (key, right_value) in other {
match self.remove(&key) {
None => {
out.insert(key, right_value);
}
Some(left_value) => {
if let Some(final_value) = f(&key, left_value, right_value) {
out.insert(key, final_value);
}
}
}
}
out.union(self)
}
#[inline]
#[must_use]
pub fn relative_complement(mut self, other: Self) -> Self {
for (key, _) in other {
let _ = self.remove(&key);
}
self
}
#[inline]
#[must_use]
pub fn intersection(self, other: Self) -> Self {
self.intersection_with_key(other, |_, v, _| v)
}
#[inline]
#[must_use]
pub fn intersection_with<B, C, F>(
self,
other: OrdMap<K, B>,
mut f: F,
) -> OrdMap<K, C>
where
B: Clone,
C: Clone,
F: FnMut(V, B) -> C,
{
self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
}
#[must_use]
pub fn intersection_with_key<B, C, F>(
mut self,
other: OrdMap<K, B>,
mut f: F,
) -> OrdMap<K, C>
where
B: Clone,
C: Clone,
F: FnMut(&K, V, B) -> C,
{
let mut out = OrdMap::<K, C>::default();
for (key, right_value) in other {
match self.remove(&key) {
None => (),
Some(left_value) => {
let result = f(&key, left_value, right_value);
out.insert(key, result);
}
}
}
out
}
#[must_use]
pub fn split<BK>(&self, split: &BK) -> (Self, Self)
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
let (l, _, r) = self.split_lookup(split);
(l, r)
}
#[must_use]
pub fn split_lookup<BK>(&self, split: &BK) -> (Self, Option<V>, Self)
where
BK: Ord + ?Sized,
K: Borrow<BK>, {
self.iter().fold((ordmap![], None, ordmap![]), |(l, m, r), (k, v)| match k
.borrow()
.cmp(split)
{
Ordering::Less => (l.update(k.clone(), v.clone()), m, r),
Ordering::Equal => (l, Some(v.clone()), r),
Ordering::Greater => (l, m, r.update(k.clone(), v.clone())),
})
}
#[must_use]
pub fn take(&self, n: usize) -> Self {
self.iter().take(n).map(|(k, v)| (k.clone(), v.clone())).collect()
}
#[must_use]
pub fn skip(&self, n: usize) -> Self {
self.iter().skip(n).map(|(k, v)| (k.clone(), v.clone())).collect()
}
#[must_use]
pub fn without_min(&self) -> (Option<V>, Self) {
let (pop, next) = self.without_min_with_key();
(pop.map(|(_, v)| v), next)
}
#[must_use]
pub fn without_min_with_key(&self) -> (Option<(K, V)>, Self) {
match self.get_min() {
None => (None, self.clone()),
Some((k, _)) => {
let (key, value, next) = self.extract_with_key(k).unwrap();
(Some((key, value)), next)
}
}
}
#[must_use]
pub fn without_max(&self) -> (Option<V>, Self) {
let (pop, next) = self.without_max_with_key();
(pop.map(|(_, v)| v), next)
}
#[must_use]
pub fn without_max_with_key(&self) -> (Option<(K, V)>, Self) {
match self.get_max() {
None => (None, self.clone()),
Some((k, _)) => {
let (key, value, next) = self.extract_with_key(k).unwrap();
(Some((key, value)), next)
}
}
}
#[must_use]
pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
if self.contains_key(&key) {
Entry::Occupied(OccupiedEntry { map: self, key })
}
else {
Entry::Vacant(VacantEntry { map: self, key })
}
}
}
pub enum Entry<'a, K, V>
where
K: Ord + Clone,
V: Clone, {
Occupied(OccupiedEntry<'a, K, V>),
Vacant(VacantEntry<'a, K, V>),
}
impl<'a, K, V> Entry<'a, K, V>
where
K: Ord + Clone,
V: Clone,
{
pub fn or_insert(self, default: V) -> &'a mut V {
self.or_insert_with(|| default)
}
pub fn or_insert_with<F>(self, default: F) -> &'a mut V
where F: FnOnce() -> V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default()),
}
}
pub fn or_default(self) -> &'a mut V
where V: Default {
self.or_insert_with(Default::default)
}
#[must_use]
pub fn key(&self) -> &K {
match self {
Entry::Occupied(entry) => entry.key(),
Entry::Vacant(entry) => entry.key(),
}
}
pub fn and_modify<F>(mut self, f: F) -> Self
where F: FnOnce(&mut V) {
match &mut self {
Entry::Occupied(ref mut entry) => f(entry.get_mut()),
Entry::Vacant(_) => (),
}
self
}
}
pub struct OccupiedEntry<'a, K, V>
where
K: Ord + Clone,
V: Clone, {
map: &'a mut OrdMap<K, V>,
key: K,
}
impl<'a, K, V> OccupiedEntry<'a, K, V>
where
K: 'a + Ord + Clone,
V: 'a + Clone,
{
#[must_use]
pub fn key(&self) -> &K { &self.key }
pub fn remove_entry(self) -> (K, V) {
self
.map
.remove_with_key(&self.key)
.expect("ordmap::OccupiedEntry::remove_entry: key has vanished!")
}
#[must_use]
pub fn get(&self) -> &V { self.map.get(&self.key).unwrap() }
#[must_use]
pub fn get_mut(&mut self) -> &mut V { self.map.get_mut(&self.key).unwrap() }
#[must_use]
pub fn into_mut(self) -> &'a mut V { self.map.get_mut(&self.key).unwrap() }
pub fn insert(&mut self, value: V) -> V {
mem::replace(self.get_mut(), value)
}
pub fn remove(self) -> V { self.remove_entry().1 }
}
pub struct VacantEntry<'a, K, V>
where
K: Ord + Clone,
V: Clone, {
map: &'a mut OrdMap<K, V>,
key: K,
}
impl<'a, K, V> VacantEntry<'a, K, V>
where
K: 'a + Ord + Clone,
V: 'a + Clone,
{
#[must_use]
pub fn key(&self) -> &K { &self.key }
#[must_use]
pub fn into_key(self) -> K { self.key }
pub fn insert(self, value: V) -> &'a mut V {
self.map.insert(self.key.clone(), value);
self.map.get_mut(&self.key).unwrap()
}
}
impl<K, V> Clone for OrdMap<K, V> {
#[inline]
fn clone(&self) -> Self {
OrdMap { size: self.size, pool: self.pool.clone(), root: self.root.clone() }
}
}
#[cfg(not(has_specialisation))]
impl<K, V> PartialEq for OrdMap<K, V>
where
K: Ord + PartialEq,
V: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.len() == other.len() && self.diff(other).next().is_none()
}
}
#[cfg(has_specialisation)]
impl<K, V> PartialEq for OrdMap<K, V>
where
K: Ord + PartialEq,
V: PartialEq,
{
default fn eq(&self, other: &Self) -> bool {
self.len() == other.len() && self.diff(other).next().is_none()
}
}
#[cfg(has_specialisation)]
impl<K, V> PartialEq for OrdMap<K, V>
where
K: Ord + Eq,
V: Eq,
{
fn eq(&self, other: &Self) -> bool {
PoolRef::ptr_eq(&self.root, &other.root)
|| (self.len() == other.len() && self.diff(other).next().is_none())
}
}
impl<K: Ord + Eq, V: Eq> Eq for OrdMap<K, V> {}
impl<K, V> PartialOrd for OrdMap<K, V>
where
K: Ord,
V: PartialOrd,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.iter().partial_cmp(other.iter())
}
}
impl<K, V> Ord for OrdMap<K, V>
where
K: Ord,
V: Ord,
{
fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other.iter()) }
}
impl<K, V> Hash for OrdMap<K, V>
where
K: Ord + Hash,
V: Hash,
{
fn hash<H>(&self, state: &mut H)
where H: Hasher {
for i in self.iter() {
i.hash(state);
}
}
}
impl<K, V> Default for OrdMap<K, V> {
fn default() -> Self { Self::new() }
}
impl<'a, K, V> Add for &'a OrdMap<K, V>
where
K: Ord + Clone,
V: Clone,
{
type Output = OrdMap<K, V>;
fn add(self, other: Self) -> Self::Output {
self.clone().union(other.clone())
}
}
impl<K, V> Add for OrdMap<K, V>
where
K: Ord + Clone,
V: Clone,
{
type Output = OrdMap<K, V>;
fn add(self, other: Self) -> Self::Output { self.union(other) }
}
impl<K, V> Sum for OrdMap<K, V>
where
K: Ord + Clone,
V: Clone,
{
fn sum<I>(it: I) -> Self
where I: Iterator<Item = Self> {
it.fold(Self::default(), |a, b| a + b)
}
}
impl<K, V, RK, RV> Extend<(RK, RV)> for OrdMap<K, V>
where
K: Ord + Clone + From<RK>,
V: Clone + From<RV>,
{
fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = (RK, RV)> {
for (key, value) in iter {
self.insert(From::from(key), From::from(value));
}
}
}
impl<'a, BK, K, V> Index<&'a BK> for OrdMap<K, V>
where
BK: Ord + ?Sized,
K: Ord + Borrow<BK>,
{
type Output = V;
fn index(&self, key: &BK) -> &Self::Output {
match self.root.lookup(key) {
None => panic!("OrdMap::index: invalid key"),
Some(&(_, ref value)) => value,
}
}
}
impl<'a, BK, K, V> IndexMut<&'a BK> for OrdMap<K, V>
where
BK: Ord + ?Sized,
K: Ord + Clone + Borrow<BK>,
V: Clone,
{
fn index_mut(&mut self, key: &BK) -> &mut Self::Output {
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
match root.lookup_mut(&self.pool.0, key) {
None => panic!("OrdMap::index: invalid key"),
Some(&mut (_, ref mut value)) => value,
}
}
}
impl<K, V> Debug for OrdMap<K, V>
where
K: Ord + Debug,
V: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut d = f.debug_map();
for (k, v) in self.iter() {
d.entry(k, v);
}
d.finish()
}
}
pub struct Iter<'a, K, V> {
it: RangedIter<'a, (K, V)>,
}
impl<'a, K, V> Iterator for Iter<'a, K, V>
where (K, V): 'a + BTreeValue
{
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|(k, v)| (k, v))
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.it.remaining, Some(self.it.remaining))
}
}
impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V>
where (K, V): 'a + BTreeValue
{
fn next_back(&mut self) -> Option<Self::Item> {
self.it.next_back().map(|(k, v)| (k, v))
}
}
impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> where (K, V): 'a + BTreeValue {}
pub struct DiffIter<'a, K, V> {
it: NodeDiffIter<'a, (K, V)>,
}
#[derive(PartialEq, Eq, Debug)]
pub enum DiffItem<'a, K, V> {
Add(&'a K, &'a V),
Update {
old: (&'a K, &'a V),
new: (&'a K, &'a V),
},
Remove(&'a K, &'a V),
}
impl<'a, K, V> Iterator for DiffIter<'a, K, V>
where (K, V): 'a + BTreeValue + PartialEq
{
type Item = DiffItem<'a, K, V>;
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|item| match item {
NodeDiffItem::Add((k, v)) => DiffItem::Add(k, v),
NodeDiffItem::Update { old: (oldk, oldv), new: (newk, newv) } => {
DiffItem::Update { old: (oldk, oldv), new: (newk, newv) }
}
NodeDiffItem::Remove((k, v)) => DiffItem::Remove(k, v),
})
}
}
pub struct Keys<'a, K, V> {
it: Iter<'a, K, V>,
}
impl<'a, K, V> Iterator for Keys<'a, K, V>
where
K: 'a + Ord,
V: 'a,
{
type Item = &'a K;
fn next(&mut self) -> Option<Self::Item> { self.it.next().map(|(k, _)| k) }
fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() }
}
impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V>
where
K: 'a + Ord,
V: 'a,
{
fn next_back(&mut self) -> Option<Self::Item> {
match self.it.next_back() {
None => None,
Some((k, _)) => Some(k),
}
}
}
impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V>
where
K: 'a + Ord,
V: 'a,
{
}
pub struct Values<'a, K, V> {
it: Iter<'a, K, V>,
}
impl<'a, K, V> Iterator for Values<'a, K, V>
where
K: 'a + Ord,
V: 'a,
{
type Item = &'a V;
fn next(&mut self) -> Option<Self::Item> { self.it.next().map(|(_, v)| v) }
fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() }
}
impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V>
where
K: 'a + Ord,
V: 'a,
{
fn next_back(&mut self) -> Option<Self::Item> {
match self.it.next_back() {
None => None,
Some((_, v)) => Some(v),
}
}
}
impl<'a, K, V> ExactSizeIterator for Values<'a, K, V>
where
K: 'a + Ord,
V: 'a,
{
}
impl<K, V, RK, RV> FromIterator<(RK, RV)> for OrdMap<K, V>
where
K: Ord + Clone + From<RK>,
V: Clone + From<RV>,
{
fn from_iter<T>(i: T) -> Self
where T: IntoIterator<Item = (RK, RV)> {
let mut m = OrdMap::default();
for (k, v) in i {
m.insert(From::from(k), From::from(v));
}
m
}
}
impl<'a, K, V> IntoIterator for &'a OrdMap<K, V>
where K: Ord
{
type IntoIter = Iter<'a, K, V>;
type Item = (&'a K, &'a V);
fn into_iter(self) -> Self::IntoIter { self.iter() }
}
impl<K, V> IntoIterator for OrdMap<K, V>
where
K: Ord + Clone,
V: Clone,
{
type IntoIter = ConsumingIter<(K, V)>;
type Item = (K, V);
fn into_iter(self) -> Self::IntoIter {
ConsumingIter::new(&self.root, self.size)
}
}
impl<K, V> AsRef<OrdMap<K, V>> for OrdMap<K, V> {
fn as_ref(&self) -> &Self { self }
}
impl<'m, 'k, 'v, K, V, OK, OV> From<&'m OrdMap<&'k K, &'v V>> for OrdMap<OK, OV>
where
K: Ord + ToOwned<Owned = OK> + ?Sized,
V: ToOwned<Owned = OV> + ?Sized,
OK: Ord + Clone + Borrow<K>,
OV: Clone + Borrow<V>,
{
fn from(m: &OrdMap<&K, &V>) -> Self {
m.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect()
}
}
impl<'a, K, V, RK, RV, OK, OV> From<&'a [(RK, RV)]> for OrdMap<K, V>
where
K: Ord + Clone + From<OK>,
V: Clone + From<OV>,
OK: Borrow<RK>,
OV: Borrow<RV>,
RK: ToOwned<Owned = OK>,
RV: ToOwned<Owned = OV>,
{
fn from(m: &'a [(RK, RV)]) -> OrdMap<K, V> {
m.iter().map(|&(ref k, ref v)| (k.to_owned(), v.to_owned())).collect()
}
}
impl<K, V, RK, RV> From<Vec<(RK, RV)>> for OrdMap<K, V>
where
K: Ord + Clone + From<RK>,
V: Clone + From<RV>,
{
fn from(m: Vec<(RK, RV)>) -> OrdMap<K, V> { m.into_iter().collect() }
}
impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a Vec<(RK, RV)>> for OrdMap<K, V>
where
K: Ord + Clone + From<OK>,
V: Clone + From<OV>,
OK: Borrow<RK>,
OV: Borrow<RV>,
RK: ToOwned<Owned = OK>,
RV: ToOwned<Owned = OV>,
{
fn from(m: &'a Vec<(RK, RV)>) -> OrdMap<K, V> {
m.iter().map(|&(ref k, ref v)| (k.to_owned(), v.to_owned())).collect()
}
}
impl<K: Ord, V, RK, RV> From<BTreeMap<RK, RV>> for OrdMap<K, V>
where
K: Ord + Clone + From<RK>,
V: Clone + From<RV>,
{
fn from(m: BTreeMap<RK, RV>) -> OrdMap<K, V> { m.into_iter().collect() }
}
impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a btree_map::BTreeMap<RK, RV>>
for OrdMap<K, V>
where
K: Ord + Clone + From<OK>,
V: Clone + From<OV>,
OK: Borrow<RK>,
OV: Borrow<RV>,
RK: Ord + ToOwned<Owned = OK>,
RV: ToOwned<Owned = OV>,
{
fn from(m: &'a btree_map::BTreeMap<RK, RV>) -> OrdMap<K, V> {
m.iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::test::is_sorted;
use rand::{
random,
seq::SliceRandom,
thread_rng,
Rng,
};
#[test]
fn iterates_in_order() {
let map = ordmap! {
2 => 22,
1 => 11,
3 => 33,
8 => 88,
9 => 99,
4 => 44,
5 => 55,
7 => 77,
6 => 66
};
let mut it = map.iter();
assert_eq!(it.next(), Some((&1, &11)));
assert_eq!(it.next(), Some((&2, &22)));
assert_eq!(it.next(), Some((&3, &33)));
assert_eq!(it.next(), Some((&4, &44)));
assert_eq!(it.next(), Some((&5, &55)));
assert_eq!(it.next(), Some((&6, &66)));
assert_eq!(it.next(), Some((&7, &77)));
assert_eq!(it.next(), Some((&8, &88)));
assert_eq!(it.next(), Some((&9, &99)));
assert_eq!(it.next(), None);
}
#[test]
fn into_iter() {
let map = ordmap! {
2 => 22,
1 => 11,
3 => 33,
8 => 88,
9 => 99,
4 => 44,
5 => 55,
7 => 77,
6 => 66
};
let mut vec = vec![];
for (k, v) in map {
assert_eq!(k * 11, v);
vec.push(k)
}
assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
}
#[test]
fn deletes_correctly() {
let map = ordmap! {
2 => 22,
1 => 11,
3 => 33,
8 => 88,
9 => 99,
4 => 44,
5 => 55,
7 => 77,
6 => 66
};
assert_eq!(map.extract(&11), None);
let (popped, less) = map.extract(&5).unwrap();
assert_eq!(popped, 55);
let mut it = less.iter();
assert_eq!(it.next(), Some((&1, &11)));
assert_eq!(it.next(), Some((&2, &22)));
assert_eq!(it.next(), Some((&3, &33)));
assert_eq!(it.next(), Some((&4, &44)));
assert_eq!(it.next(), Some((&6, &66)));
assert_eq!(it.next(), Some((&7, &77)));
assert_eq!(it.next(), Some((&8, &88)));
assert_eq!(it.next(), Some((&9, &99)));
assert_eq!(it.next(), None);
}
#[test]
fn debug_output() {
assert_eq!(
format!("{:?}", ordmap! { 3 => 4, 5 => 6, 1 => 2 }),
"{1: 2, 3: 4, 5: 6}"
);
}
#[test]
fn equality2() {
let v1 = "1".to_string();
let v2 = "1".to_string();
assert_eq!(v1, v2);
let p1 = Vec::<String>::new();
let p2 = Vec::<String>::new();
assert_eq!(p1, p2);
let c1 = OrdMap::unit(v1, p1);
let c2 = OrdMap::unit(v2, p2);
assert_eq!(c1, c2);
}
#[test]
fn insert_remove_single_mut() {
let mut m = OrdMap::new();
m.insert(0, 0);
assert_eq!(OrdMap::unit(0, 0), m);
m.remove(&0);
assert_eq!(OrdMap::new(), m);
}
#[test]
fn double_ended_iterator_1() {
let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
let mut it = m.iter();
assert_eq!(Some((&1, &1)), it.next());
assert_eq!(Some((&4, &4)), it.next_back());
assert_eq!(Some((&2, &2)), it.next());
assert_eq!(Some((&3, &3)), it.next_back());
assert_eq!(None, it.next());
}
#[test]
fn double_ended_iterator_2() {
let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
let mut it = m.iter();
assert_eq!(Some((&1, &1)), it.next());
assert_eq!(Some((&4, &4)), it.next_back());
assert_eq!(Some((&2, &2)), it.next());
assert_eq!(Some((&3, &3)), it.next_back());
assert_eq!(None, it.next_back());
}
#[test]
fn safe_mutation() {
let v1 = OrdMap::from_iter((0..131_072).map(|i| (i, i)));
let mut v2 = v1.clone();
v2.insert(131_000, 23);
assert_eq!(Some(&23), v2.get(&131_000));
assert_eq!(Some(&131_000), v1.get(&131_000));
}
#[test]
fn index_operator() {
let mut map = ordmap! {1 => 2, 3 => 4, 5 => 6};
assert_eq!(4, map[&3]);
map[&3] = 8;
assert_eq!(ordmap! {1 => 2, 3 => 8, 5 => 6}, map);
}
#[test]
fn entry_api() {
let mut map = ordmap! {"bar" => 5};
map.entry(&"foo").and_modify(|v| *v += 5).or_insert(1);
assert_eq!(1, map[&"foo"]);
map.entry(&"foo").and_modify(|v| *v += 5).or_insert(1);
assert_eq!(6, map[&"foo"]);
map.entry(&"bar").and_modify(|v| *v += 5).or_insert(1);
assert_eq!(10, map[&"bar"]);
assert_eq!(10, match map.entry(&"bar") {
Entry::Occupied(entry) => entry.remove(),
_ => panic!(),
});
assert!(!map.contains_key(&"bar"));
}
#[test]
fn match_string_keys_with_string_slices() {
let mut map: OrdMap<String, i32> =
From::from(ºap! { "foo" => &1, "bar" => &2, "baz" => &3 });
assert_eq!(Some(&1), map.get("foo"));
map = map.without("foo");
assert_eq!(Some(3), map.remove("baz"));
map["bar"] = 8;
assert_eq!(8, map["bar"]);
}
#[test]
fn ranged_iter() {
let map: OrdMap<i32, i32> = ordmap![1=>2, 2=>3, 3=>4, 4=>5, 5=>6, 7=>8];
let range: Vec<(i32, i32)> = map.range(..).map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (7, 8)], range);
let range: Vec<(i32, i32)> =
map.range(..).rev().map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range);
let range: Vec<(i32, i32)> =
map.range(2..5).map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range);
let range: Vec<(i32, i32)> =
map.range(2..5).rev().map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range);
let range: Vec<(i32, i32)> =
map.range(3..).map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(3, 4), (4, 5), (5, 6), (7, 8)], range);
let range: Vec<(i32, i32)> =
map.range(3..).rev().map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4)], range);
let range: Vec<(i32, i32)> =
map.range(..4).map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
let range: Vec<(i32, i32)> =
map.range(..4).rev().map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
let range: Vec<(i32, i32)> =
map.range(..=3).map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
let range: Vec<(i32, i32)> =
map.range(..=3).rev().map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
let range: Vec<(i32, i32)> =
map.range(..6).map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
let range: Vec<(i32, i32)> =
map.range(..=6).map(|(k, v)| (*k, *v)).collect();
assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
}
#[test]
fn issue_124() {
let mut map = OrdMap::new();
let contents = include_str!("test-fixtures/issue_124.txt");
for line in contents.lines() {
if line.starts_with("insert ") {
map.insert(line[7..].parse::<u32>().unwrap(), 0);
}
else if line.starts_with("remove ") {
map.remove(&line[7..].parse::<u32>().unwrap());
}
}
}
quickcheck! {
fn length(input: btree_map::BTreeMap<i16, i16>) -> bool {
let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
input.len() == map.len()
}
fn order(input: btree_map::BTreeMap<i16, i16>) -> bool {
let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
is_sorted(map.keys())
}
fn overwrite_values(vec: Vec<(i16, i16)>) -> bool {
if vec.len() == 0 {
return true;
}
let mut rng = thread_rng();
let index_rand: i16 = rng.gen_range(0..vec.len()) as i16;
let new_val: i16 = random();
let map1 = OrdMap::from_iter(vec.clone());
let map2 = map1.update(index_rand, new_val);
let mut res = true;
for (k, v) in map2 {
if k == index_rand {
res = res && v == new_val;
} else {
match map1.get(&k) {
None => panic!("map1 didn't have key {:?}", k),
Some(other_v) => {
res = res && v == *other_v
}
}
}
}
res
}
fn delete_values(vec: Vec<(usize, usize)>) -> bool {
if vec.len() == 0 {
return true;
}
let mut rng = thread_rng();
let index = vec.choose(&mut rng).unwrap().0;
let map1: OrdMap<usize, usize> = OrdMap::from_iter(vec.clone());
let map2 = map1.without(&index);
let mut res = true;
res = res && map1.len() == map2.len() + 1;
for k in map2.keys() {
res = res && *k != index;
}
res
}
fn insert_and_delete_values(
input: OrdMap<usize,usize>,
ops: Vec<(bool, usize, usize)>
) -> bool {
let mut map = input.clone();
let mut tree: btree_map::BTreeMap<usize, usize> = input.iter().map(|(k, v)| (*k, *v)).collect();
for (ins, key, val) in &ops {
if *ins {
tree.insert(*key, *val);
map = map.update(*key, *val)
} else {
tree.remove(key);
map = map.without(key)
}
}
map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v)))
}
fn insert_and_length(m: btree_map::BTreeMap<i16, i16>) -> bool {
let mut map: OrdMap<i16, i16> = OrdMap::new();
for (k, v) in m.iter() {
map = map.update(*k, *v)
}
m.len() == map.len()
}
fn from_iterator(m: BTreeMap<i16, i16>) -> bool {
let map: OrdMap<i16, i16> =
FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
m.len() == map.len()
}
fn iterate_over(m: BTreeMap<i16,i16>) -> bool {
let map: OrdMap<i16, i16> =
FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
m.len() == map.iter().count()
}
fn equality(m: BTreeMap<i16, i16>) -> bool {
let map1: OrdMap<i16, i16> =
FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
let map2: OrdMap<i16, i16> =
FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
map1 == map2
}
fn lookup(m: BTreeMap<i16, i16>) -> bool {
let map: OrdMap<i16, i16> =
FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
for (k, v) in m.iter() {
if Some(*v) != map.get(k).cloned() {
return false;
}
}
true
}
fn remove(m: BTreeMap<i16, i16>) -> bool {
let mut map: OrdMap<i16, i16> =
FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
let mut res = true;
for k in m.keys() {
let l = map.len();
res = res && m.get(k).cloned() == map.get(k).cloned();
map = map.without(k);
res = res && None == map.get(k) && l - 1 == map.len();
}
res
}
fn insert_mut(m: BTreeMap<i16, i16>) -> bool {
let mut mut_map = OrdMap::new();
let mut map = OrdMap::new();
for (k, v) in m.iter() {
map = map.update(*k, *v);
mut_map.insert(*k, *v);
}
map == mut_map
}
fn remove_mut(orig: BTreeMap<i16, i16>) -> bool {
let mut map = orig.clone();
let mut res = true;
for key in orig.keys() {
let len = map.len();
res = res && orig.get(key) == map.get(key);
res = res && orig.get(key).cloned() == map.remove(key);
res = res && None == map.get(key);
res = res && len - 1 == map.len();
}
res
}
fn remove_alien(orig: BTreeMap<i16, i16>) -> bool {
let mut map = OrdMap::<i16, i16>::from(orig.clone());
let mut res = true;
for key in orig.keys() {
let len = map.len();
res = orig.get(key) == map.get(key)
&& orig.get(key).cloned() == map.remove(key)
&& None == map.get(key)
&& len - 1 == map.len()
}
res
}
fn delete_and_reinsert(
input: BTreeMap<i16, i16>,
index_rand: usize
) -> bool {
if input.len() == 0 {
return true;
}
let index = *input.keys().nth(index_rand % input.len()).unwrap();
let map1 = OrdMap::from_iter(input.clone());
let (val, map2): (i16, _) = map1.extract(&index).unwrap();
let map3 = map2.update(index, val);
let mut res = true;
for key in map2.keys() {
res = res && *key != index;
}
res
&& map1.len() == map2.len() + 1
&& map1 == map3
}
fn exact_size_iterator(m: OrdMap<i16, i16>) -> bool {
let mut should_be = m.len();
let mut it = m.iter();
let mut res = true;
loop {
res = res && should_be == it.len();
match it.next() {
None => break,
Some(_) => should_be -= 1,
}
}
res && 0 == it.len()
}
fn diff_all_values(a: Vec<(usize, usize)>, b: Vec<(usize, usize)>) -> bool {
let a: OrdMap<usize, usize> = OrdMap::from(a);
let b: OrdMap<usize, usize> = OrdMap::from(b);
let diff: Vec<_> = a.diff(&b).collect();
let union = b.clone().union(a.clone());
let expected: Vec<_> = union.iter().filter_map(|(k, v)| {
if a.contains_key(&k) {
if b.contains_key(&k) {
let old = a.get(&k).unwrap();
if old != v {
Some(DiffItem::Update {
old: (k, old),
new: (k, v),
})
} else {
None
}
} else {
Some(DiffItem::Remove(k, v))
}
} else {
Some(DiffItem::Add(k, v))
}
}).collect();
expected == diff
}
}
}