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
use std::ops::{Deref, DerefMut}; #[derive(Debug, Clone, Copy, Default, PartialEq, PartialOrd, Eq, Ord, 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 new_take(takeable: &mut Takeable<T>) -> Takeable<T> { Takeable::new(takeable.0.take().unwrap()) } #[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() } }