1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
use std::ops::{Deref, DerefMut};
use std::fmt::Debug;
use std::hash::Hash;

pub struct Takeable<T> {
    inner: Option<T>,
}

impl<T> Takeable<T> {
    #[inline]
    pub fn new(value: T) -> Takeable<T> {
        Takeable {inner: Some(value)}
    }

    #[inline]
    pub fn new_empty() -> Takeable<T> {
        Takeable {inner: None}
    }

    #[inline]
    pub fn take(slot: &mut Takeable<T>) -> T {
        slot.inner.take().unwrap()
    }
}

impl<T> Deref for Takeable<T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.inner.as_ref().unwrap()
    }
}

impl<T> DerefMut for Takeable<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.as_mut().unwrap()
    }
}

impl<T: Debug> Debug for Takeable<T> {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        fmt.debug_tuple("Takeable").field(self.deref()).finish()
    }
}

impl<T: Clone> Clone for Takeable<T> {
    fn clone(&self) -> Self {
        Takeable::new(self.deref().clone())
    }

    fn clone_from(&mut self, source: &Self) {
        self.deref_mut().clone_from(source);
    }
}

impl<T: Default> Default for Takeable<T> {
    fn default() -> Self {
        Takeable::new(Default::default())
    }
}

impl<T: PartialEq> PartialEq for Takeable<T> {
    fn eq(&self, other: &Self) -> bool {
        self.deref().eq(other)
    }

    fn ne(&self, other: &Self) -> bool {
        self.deref().ne(other)
    }
}

impl<T: Eq> Eq for Takeable<T> {}

impl<T: PartialOrd> PartialOrd for Takeable<T> {
    fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
        self.deref().partial_cmp(other)
    }

    fn lt(&self, other: &Self) -> bool {
        self.deref().lt(other)
    }

    fn le(&self, other: &Self) -> bool {
        self.deref().le(other)
    }

    fn gt(&self, other: &Self) -> bool {
        self.deref().gt(other)
    }

    fn ge(&self, other: &Self) -> bool {
        self.deref().ge(other)
    }
}

impl<T: Ord> Ord for Takeable<T> {
    fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
        self.deref().cmp(other)
    }
}

impl<T: Hash> Hash for Takeable<T> {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.deref().hash(state);
    }
}