use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections;
use std::fmt::{Debug, Error, Formatter};
use std::hash::{BuildHasher, Hash, Hasher};
use std::iter::{FromIterator, Iterator, Sum};
use std::mem;
use std::ops::{Add, Index, IndexMut, RangeBounds};
use crate::hashmap::HashMap;
use crate::nodes::btree::{BTreeValue, Insert, Node, Remove};
#[cfg(has_specialisation)]
use crate::util::linear_search_by;
use crate::util::Ref;
pub use crate::nodes::btree::{ConsumingIter, DiffItem, DiffIter, 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))
    }
}
pub struct OrdMap<K, V> {
    size: usize,
    root: Ref<Node<(K, V)>>,
}
impl<K, V> OrdMap<K, V> {
    
    #[must_use]
    pub fn new() -> Self {
        OrdMap {
            size: 0,
            root: Ref::from(Node::new()),
        }
    }
    
    
    
    
    
    #[inline]
    #[must_use]
    #[deprecated(since = "12.3.0", note = "renamed to `unit` for consistency")]
    pub fn singleton(key: K, value: V) -> Self {
        Self::unit(key, value)
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    #[inline]
    #[must_use]
    pub fn unit(key: K, value: V) -> Self {
        OrdMap {
            size: 1,
            root: Ref::from(Node::unit((key, value))),
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.size
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    pub fn clear(&mut self) {
        if !self.is_empty() {
            self.root = Default::default();
            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) -> RangedIter<(K, V)>
    where
        R: RangeBounds<BK>,
        K: Borrow<BK>,
        BK: Ord + ?Sized,
    {
        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::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 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]
    fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
    where
        BK: Ord + ?Sized,
        K: Borrow<BK>,
    {
        let root = Ref::make_mut(&mut self.root);
        root.lookup_mut(key).map(|(_, v)| v)
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    #[inline]
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        let new_root = {
            let root = Ref::make_mut(&mut self.root);
            match root.insert((key, value)) {
                Insert::Replaced((_, old_value)) => return Some(old_value),
                Insert::Added => {
                    self.size += 1;
                    return None;
                }
                Insert::Update(root) => Ref::from(root),
                Insert::Split(left, median, right) => {
                    Ref::from(Node::from_split(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 = Ref::make_mut(&mut self.root);
            match root.remove(k) {
                Remove::NoChange => return None,
                Remove::Removed(pair) => {
                    self.size -= 1;
                    return Some(pair);
                }
                Remove::Update(pair, root) => (Ref::from(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.difference_with_key(other, |_, _, _| None)
    }
    
    
    
    
    #[inline]
    #[must_use]
    pub fn difference_with<F>(self, other: Self, mut f: F) -> Self
    where
        F: FnMut(V, V) -> Option<V>,
    {
        self.difference_with_key(other, |_, a, b| f(a, b))
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    #[must_use]
    pub fn 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 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).cloned().collect()
    }
    
    
    #[must_use]
    pub fn skip(&self, n: usize) -> Self {
        self.iter().skip(n).cloned().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: 'a + Ord + Clone,
    V: 'a + Clone,
{
    Occupied(OccupiedEntry<'a, K, V>),
    Vacant(VacantEntry<'a, K, V>),
}
impl<'a, K, V> Entry<'a, K, V>
where
    K: 'a + Ord + Clone,
    V: 'a + 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: 'a + Ord + Clone,
    V: 'a + 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: 'a + Ord + Clone,
    V: 'a + 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> {
    fn clone(&self) -> Self {
        OrdMap {
            size: self.size,
            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 {
        Ref::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 = Ref::make_mut(&mut self.root);
        match root.lookup_mut(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 {
            d.entry(k, v);
        }
        d.finish()
    }
}
pub struct Iter<'a, A: 'a> {
    it: RangedIter<'a, A>,
}
impl<'a, A> Iterator for Iter<'a, A>
where
    A: 'a + BTreeValue,
{
    type Item = &'a A;
    fn next(&mut self) -> Option<Self::Item> {
        self.it.next()
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.it.remaining, Some(self.it.remaining))
    }
}
impl<'a, A> DoubleEndedIterator for Iter<'a, A>
where
    A: 'a + BTreeValue,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.it.next_back()
    }
}
impl<'a, A> ExactSizeIterator for Iter<'a, A> where A: 'a + BTreeValue {}
pub struct Keys<'a, K: 'a, V: 'a> {
    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> {
        match self.it.next() {
            None => None,
            Some((k, _)) => Some(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: 'a, V: 'a> {
    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> {
        match self.it.next() {
            None => None,
            Some((_, v)) => Some(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 Item = &'a (K, V);
    type IntoIter = Iter<'a, (K, V)>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}
impl<K, V> IntoIterator for OrdMap<K, V>
where
    K: Ord + Clone,
    V: Clone,
{
    type Item = (K, V);
    type IntoIter = ConsumingIter<(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: Eq + Hash, RV> From<collections::HashMap<RK, RV>> for OrdMap<K, V>
where
    K: Ord + Clone + From<RK>,
    V: Clone + From<RV>,
{
    fn from(m: collections::HashMap<RK, RV>) -> OrdMap<K, V> {
        m.into_iter().collect()
    }
}
impl<'a, K, V, OK, OV, RK, RV> From<&'a collections::HashMap<RK, RV>> for OrdMap<K, V>
where
    K: Ord + Clone + From<OK>,
    V: Clone + From<OV>,
    OK: Borrow<RK>,
    OV: Borrow<RV>,
    RK: Hash + Eq + ToOwned<Owned = OK>,
    RV: ToOwned<Owned = OV>,
{
    fn from(m: &'a collections::HashMap<RK, RV>) -> OrdMap<K, V> {
        m.iter()
            .map(|(k, v)| (k.to_owned(), v.to_owned()))
            .collect()
    }
}
impl<K: Ord, V, RK, RV> From<collections::BTreeMap<RK, RV>> for OrdMap<K, V>
where
    K: Ord + Clone + From<RK>,
    V: Clone + From<RV>,
{
    fn from(m: collections::BTreeMap<RK, RV>) -> OrdMap<K, V> {
        m.into_iter().collect()
    }
}
impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a collections::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 collections::BTreeMap<RK, RV>) -> OrdMap<K, V> {
        m.iter()
            .map(|(k, v)| (k.to_owned(), v.to_owned()))
            .collect()
    }
}
impl<K: Ord + Hash + Eq + Clone, V: Clone, S: BuildHasher> From<HashMap<K, V, S>> for OrdMap<K, V> {
    fn from(m: HashMap<K, V, S>) -> Self {
        m.into_iter().collect()
    }
}
impl<'a, K: Ord + Hash + Eq + Clone, V: Clone, S: BuildHasher> From<&'a HashMap<K, V, S>>
    for OrdMap<K, V>
{
    fn from(m: &'a HashMap<K, V, S>) -> Self {
        m.iter().cloned().collect()
    }
}
#[cfg(all(threadsafe, feature = "quickcheck"))]
use quickcheck::{Arbitrary, Gen};
#[cfg(all(threadsafe, feature = "quickcheck"))]
impl<K: Ord + Clone + Arbitrary + Sync, V: Clone + Arbitrary + Sync> Arbitrary for OrdMap<K, V> {
    fn arbitrary<G: Gen>(g: &mut G) -> Self {
        OrdMap::from_iter(Vec::<(K, V)>::arbitrary(g))
    }
}
#[cfg(any(test, feature = "proptest"))]
pub mod proptest {
    use super::*;
    use ::proptest::strategy::{BoxedStrategy, Strategy, ValueTree};
    use std::ops::Range;
    
    
    
    
    
    
    
    
    
    
    
    
    
    pub fn ord_map<K: Strategy + 'static, V: Strategy + 'static>(
        key: K,
        value: V,
        size: Range<usize>,
    ) -> BoxedStrategy<OrdMap<<K::Tree as ValueTree>::Value, <V::Tree as ValueTree>::Value>>
    where
        <K::Tree as ValueTree>::Value: Ord + Clone,
        <V::Tree as ValueTree>::Value: Clone,
    {
        ::proptest::collection::vec((key, value), size.clone())
            .prop_map(OrdMap::from)
            .prop_filter("OrdMap minimum size".to_owned(), move |m| {
                m.len() >= size.start
            })
            .boxed()
    }
}
#[cfg(test)]
mod test {
    use super::proptest::*;
    use super::*;
    use crate::nodes::btree::DiffItem;
    use crate::test::is_sorted;
    use ::proptest::num::{i16, usize};
    use ::proptest::{bool, collection, proptest};
    #[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];
        let range: Vec<(i32, i32)> = map.range(..).cloned().collect();
        assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
        let range: Vec<(i32, i32)> = map.range(..).rev().cloned().collect();
        assert_eq!(vec![(5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range);
        let range: Vec<(i32, i32)> = map.range(2..5).cloned().collect();
        assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range);
        let range: Vec<(i32, i32)> = map.range(2..5).rev().cloned().collect();
        assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range);
        let range: Vec<(i32, i32)> = map.range(3..).cloned().collect();
        assert_eq!(vec![(3, 4), (4, 5), (5, 6)], range);
        let range: Vec<(i32, i32)> = map.range(3..).rev().cloned().collect();
        assert_eq!(vec![(5, 6), (4, 5), (3, 4)], range);
        let range: Vec<(i32, i32)> = map.range(..4).cloned().collect();
        assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
        let range: Vec<(i32, i32)> = map.range(..4).rev().cloned().collect();
        assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
        let range: Vec<(i32, i32)> = map.range(..=3).cloned().collect();
        assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
        let range: Vec<(i32, i32)> = map.range(..=3).rev().cloned().collect();
        assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
    }
    proptest! {
        #[test]
        fn length(ref input in collection::btree_map(i16::ANY, i16::ANY, 0..1000)) {
            let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
            input.len() == map.len()
        }
        #[test]
        fn order(ref input in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
            let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
            is_sorted(map.keys())
        }
        #[test]
        fn overwrite_values(ref vec in collection::vec((i16::ANY, i16::ANY), 1..1000), index_rand in usize::ANY, new_val in i16::ANY) {
            let index = vec[index_rand % vec.len()].0;
            let map1 = OrdMap::from_iter(vec.clone());
            let map2 = map1.update(index, new_val);
            for (k, v) in map2 {
                if k == index {
                    assert_eq!(v, new_val);
                } else {
                    match map1.get(&k) {
                        None => panic!("map1 didn't have key {:?}", k),
                        Some(other_v) => {
                            assert_eq!(v, *other_v);
                        }
                    }
                }
            }
        }
        #[test]
        fn delete_values(ref vec in collection::vec((usize::ANY, usize::ANY), 1..1000), index_rand in usize::ANY) {
            let index = vec[index_rand % vec.len()].0;
            let map1: OrdMap<usize, usize> = OrdMap::from_iter(vec.clone());
            let map2 = map1.without(&index);
            assert_eq!(map1.len(), map2.len() + 1);
            for k in map2.keys() {
                assert_ne!(*k, index);
            }
        }
        #[test]
        fn insert_and_delete_values(
            ref input in ord_map(0usize..64, 0usize..64, 1..1000),
            ref ops in collection::vec((bool::ANY, usize::ANY, usize::ANY), 1..1000)
        ) {
            let mut map = input.clone();
            let mut tree: collections::BTreeMap<usize, usize> = input.iter().cloned().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)
                }
            }
            assert!(map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v))));
        }
        #[test]
        fn proptest_works(ref m in ord_map(0..9999, ".*", 10..100)) {
            assert!(m.len() < 100);
            assert!(m.len() >= 10);
        }
        #[test]
        fn insert_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
            let mut map: OrdMap<i16, i16> = OrdMap::new();
            for (k, v) in m.iter() {
                map = map.update(*k, *v)
            }
            assert_eq!(m.len(), map.len());
        }
        #[test]
        fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
            let map: OrdMap<i16, i16> =
                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
            assert_eq!(m.len(), map.len());
        }
        #[test]
        fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
            let map: OrdMap<i16, i16> =
                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
            assert_eq!(m.len(), map.iter().count());
        }
        #[test]
        fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
            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)));
            assert_eq!(map1, map2);
        }
        #[test]
        fn lookup(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
            let map: OrdMap<i16, i16> =
                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
            for (k, v) in m {
                assert_eq!(Some(*v), map.get(k).cloned());
            }
        }
        #[test]
        fn remove(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
            let mut map: OrdMap<i16, i16> =
                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
            for k in m.keys() {
                let l = map.len();
                assert_eq!(m.get(k).cloned(), map.get(k).cloned());
                map = map.without(k);
                assert_eq!(None, map.get(k));
                assert_eq!(l - 1, map.len());
            }
        }
        #[test]
        fn insert_mut(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
            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);
            }
            assert_eq!(map, mut_map);
        }
        #[test]
        fn remove_mut(ref orig in ord_map(i16::ANY, i16::ANY, 0..1000)) {
            let mut map = orig.clone();
            for key in orig.keys() {
                let len = map.len();
                assert_eq!(orig.get(key), map.get(key));
                assert_eq!(orig.get(key).cloned(), map.remove(key));
                assert_eq!(None, map.get(key));
                assert_eq!(len - 1, map.len());
            }
        }
        #[test]
        fn remove_alien(ref orig in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
            let mut map = OrdMap::<i16, i16>::from(orig.clone());
            for key in orig.keys() {
                let len = map.len();
                assert_eq!(orig.get(key), map.get(key));
                assert_eq!(orig.get(key).cloned(), map.remove(key));
                assert_eq!(None, map.get(key));
                assert_eq!(len - 1, map.len());
            }
        }
        #[test]
        fn delete_and_reinsert(
            ref input in collection::hash_map(i16::ANY, i16::ANY, 1..1000),
            index_rand in usize::ANY
        ) {
            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);
            for key in map2.keys() {
                assert!(*key != index);
            }
            assert_eq!(map1.len(), map2.len() + 1);
            assert_eq!(map1, map3);
        }
        #[test]
        fn exact_size_iterator(ref m in ord_map(i16::ANY, i16::ANY, 1..1000)) {
            let mut should_be = m.len();
            let mut it = m.iter();
            loop {
                assert_eq!(should_be, it.len());
                match it.next() {
                    None => break,
                    Some(_) => should_be -= 1,
                }
            }
            assert_eq!(0, it.len());
        }
        #[test]
        fn diff_added_values(a in ord_map(i16::ANY, i16::ANY, 0..1000), b in ord_map(i16::ANY, i16::ANY, 0..1000)) {
            let ab = a.clone().union(b.clone());
            assert!(a.diff(&ab).eq(b.iter().filter(|&(ref k, _)| !a.contains_key(k)).map(DiffItem::Add)));
        }
        
        
        
        
        
        
        
        
        
        
        
        #[test]
        fn diff_removed_values(a in ord_map(i16::ANY, i16::ANY, 0..1000), b in ord_map(i16::ANY, i16::ANY, 0..1000)) {
            let ab = a.clone().union(b.clone());
            assert!(ab.diff(&a).eq(b.iter().filter(|&(ref k, _)| !a.contains_key(k)).map(DiffItem::Remove)));
        }
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    }
}