use std::cell::UnsafeCell; use std::ops::Deref; pub struct OptCell(UnsafeCell>); impl OptCell { #[inline] pub fn new(val: Option) -> OptCell { OptCell(UnsafeCell::new(val)) } #[inline] pub fn set(&self, val: T) { unsafe { let opt = self.0.get(); debug_assert!((*opt).is_none()); *opt = Some(val) } } #[inline] pub unsafe fn get_mut(&mut self) -> &mut T { let opt = &mut *self.0.get(); opt.as_mut().unwrap() } } impl Deref for OptCell { type Target = Option; #[inline] fn deref<'a>(&'a self) -> &'a Option { unsafe { &*self.0.get() } } } impl Clone for OptCell { #[inline] fn clone(&self) -> OptCell { OptCell::new((**self).clone()) } }