ownables 0.1.1

A library that defines the Ownable trait and facilitates mutation by moving or reading from the source.
Documentation
use super::Ownable;
use std::ops::{Deref, DerefMut};

/// A Guard that handles the taken item's manipulation and returns it to source on Drop.
pub struct TakenGuard<'a, T, U>
where
    T: Ownable<Item = U>,
{
    source: &'a mut T,
    value: Option<U>,
}

impl<'a, T, U> TakenGuard<'a, T, U>
where
    T: Ownable<Item = U>,
{
    pub fn new(source: &'a mut T, value: Option<U>) -> Self {
        Self { source, value }
    }
}

impl<'a, T, U> Deref for TakenGuard<'a, T, U>
where
    T: Ownable<Item = U>,
{
    type Target = Option<U>;
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<'a, T, U> DerefMut for TakenGuard<'a, T, U>
where
    T: Ownable<Item = U>,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

impl<'a, T, U> Drop for TakenGuard<'a, T, U>
where
    T: Ownable<Item = U>,
{
    fn drop(&mut self) {
        if let Some(val) = self.value.take() {
            self.source.put_back(val);
        }
    }
}