get-trait 0.1.0

Get trait for collectons.
Documentation
//! Entry API for maps.
use get::GetMut;

/// A trait for getting an entry at a given key.
pub trait GetEntry<'a>: GetMut {
    /// The type of an occupied entry.
    type Occupied: OccupiedEntry<'a, Self>;

    /// The type of a vacant entry.
    type Vacant: VacantEntry<'a, Self>;

    /// Gets the entry.
    fn entry(&'a mut self, key: Self::Key) -> Entry<'a, Self>;
}

/// An entry at a given key.
pub enum Entry<'a, T: ?Sized + GetEntry<'a>> {
    /// An entry with a value.
    Occupied(T::Occupied),

    /// An entry without a value.
    Vacant(T::Vacant),
}
impl<'a, T: ?Sized + GetEntry<'a>> Entry<'a, T> {
    /// Gets this entry's value, inserting the given default value if the entry is empty.
    pub fn or_insert(self, default: T::Value) -> &'a mut T::Value {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default),
        }
    }
    /// Similar to `or_insert`, using a closure to create the value if necessary.
    pub fn or_insert_with<F: FnOnce() -> T::Value>(self, default: F) -> &'a mut T::Value {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default()),
        }
    }
}

/// A trait for an entry with a value.
pub trait OccupiedEntry<'a, T: ?Sized + GetEntry<'a>> {
    /// Gets a reference to the key at this entry.
    fn key(&self) -> &T::Key;

    /// Gets a reference to the value at this entry.
    fn get(&self) -> &T::Value;

    /// Gets a mutable reference to the value at this entry.
    fn get_mut(&mut self) -> &mut T::Value;

    /// Inserts the given value into this entry, returning the old value.
    fn insert(&mut self, value: T::Value) -> T::Value;

    /// Consumes this entry handle, yielding a mutable reference to its value.
    fn into_mut(self) -> &'a mut T::Value;

    /// Removes this entry, returning both its key and value.
    fn remove_entry(self) -> (T::Key, T::Value);
}

/// A trait for an entry without a value.
pub trait VacantEntry<'a, T: ?Sized + GetEntry<'a>> {
    /// Gets a reference to the key at this entry.
    fn key(&self) -> &T::Key;

    /// Consumes this entry, yielding back the key instead of inserting.
    fn into_key(self) -> T::Key;

    /// Inserts a value into this entry, yielding a mutable reference to its value.
    fn insert(self, value: T::Value) -> &'a mut T::Value;
}