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 108 109 110 111 112
use std::ops::{Deref, DerefMut}; use std::fmt::Debug; use std::hash::Hash; pub struct Takeable<T>(Option<T>); impl<T> Takeable<T> { #[inline] pub fn new(value: T) -> Takeable<T> { Takeable(Some(value)) } #[inline] pub fn new_empty() -> Takeable<T> { Takeable(None) } #[inline] pub fn take(takeable: &mut Takeable<T>) -> T { takeable.0.take().unwrap() } #[inline] pub fn try_take(takeable: &mut Takeable<T>) -> Option<T> { takeable.0.take() } #[inline] pub fn insert(takeable: &mut Takeable<T>, new_takeable: T) -> Option<T> { let ret = takeable.0.take(); takeable.0 = Some(new_takeable); ret } #[inline] pub fn to_opt(takeable: Takeable<T>) -> Option<T> { takeable.0 } } impl<T> From<Option<T>> for Takeable<T> { #[inline] fn from(op: Option<T>) -> Self { Takeable(op) } } impl<T> Deref for Takeable<T> { type Target = T; #[inline] fn deref(&self) -> &Self::Target { self.0.as_ref().unwrap() } } impl<T> DerefMut for Takeable<T> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { self.0.as_mut().unwrap() } } impl<T: Debug> Debug for Takeable<T> { #[inline] 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> { #[inline] fn clone(&self) -> Self { Takeable::new(self.deref().clone()) } } impl<T: Default> Default for Takeable<T> { #[inline] fn default() -> Self { Takeable::new(Default::default()) } } impl<T: PartialEq> PartialEq for Takeable<T> { #[inline] fn eq(&self, other: &Self) -> bool { self.deref().eq(other) } } impl<T: Eq> Eq for Takeable<T> {} impl<T: PartialOrd> PartialOrd for Takeable<T> { #[inline] fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> { self.deref().partial_cmp(other) } } impl<T: Ord> Ord for Takeable<T> { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { self.deref().cmp(other) } } impl<T: Hash> Hash for Takeable<T> { #[inline] fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) { self.deref().hash(state); } }