use crate::stable_hasher::{HashStable, StableHasher};
use crate::sync::{MappedReadGuard, ReadGuard, RwLock};
pub struct Steal<T> {
value: RwLock<Option<T>>,
}
impl<T> Steal<T> {
pub fn new(value: T) -> Self {
Steal { value: RwLock::new(Some(value)) }
}
pub fn borrow(&self) -> MappedReadGuard<'_, T> {
ReadGuard::map(self.value.borrow(), |opt| match *opt {
None => panic!("attempted to read from stolen value"),
Some(ref v) => v,
})
}
pub fn steal(&self) -> T {
let value_ref = &mut *self.value.try_write().expect("stealing value which is locked");
let value = value_ref.take();
value.expect("attempt to read from stolen value")
}
}
impl<CTX, T: HashStable<CTX>> HashStable<CTX> for Steal<T> {
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
self.borrow().hash_stable(hcx, hasher);
}
}