use super::clear::Clear;
#[derive(Clone, Debug)]
pub struct MonotonicMap<K, V>
where
K: PartialOrd,
{
key: Option<K>,
val: V,
}
impl<K, V> Default for MonotonicMap<K, V>
where
K: PartialOrd,
V: Default,
{
fn default() -> Self {
Self {
key: None,
val: Default::default(),
}
}
}
impl<K, V> MonotonicMap<K, V>
where
K: PartialOrd,
{
pub fn new_init(val: V) -> Self {
Self { key: None, val }
}
pub fn get_mut_with(&mut self, key: K, init: impl FnOnce() -> V) -> &mut V {
if self.key.as_ref().map_or(true, |old_key| old_key < &key) {
self.key = Some(key);
self.val = (init)();
}
&mut self.val
}
}
impl<K, V> MonotonicMap<K, V>
where
K: PartialOrd,
V: Default,
{
pub fn get_mut_default(&mut self, key: K) -> &mut V {
self.get_mut_with(key, Default::default)
}
}
impl<K, V> MonotonicMap<K, V>
where
K: PartialOrd,
V: Clear,
{
pub fn get_mut_clear(&mut self, key: K) -> &mut V {
if self.key.as_ref().map_or(true, |old_key| old_key < &key) {
self.key = Some(key);
self.val.clear();
}
&mut self.val
}
}