use std::cell::Cell;
use std::error::Error;
use std::any::Any;
use std::{fmt, thread};
pub struct Flag { failed: Cell<bool> }
unsafe impl Send for Flag {}
unsafe impl Sync for Flag {}
impl Flag {
pub fn new() -> Flag {
Flag { failed: Cell::new(false) }
}
#[inline]
pub fn borrow(&self) -> LockResult<Guard> {
let ret = Guard { panicking: thread::panicking() };
if self.get() {
Err(PoisonError::new(ret))
} else {
Ok(ret)
}
}
#[inline]
pub fn done(&self, guard: &Guard) {
if !guard.panicking && thread::panicking() {
self.failed.set(true);
}
}
#[inline]
pub fn get(&self) -> bool {
self.failed.get()
}
}
pub struct Guard {
panicking: bool,
}
pub struct PoisonError<T> {
guard: T,
}
pub enum TryLockError<T> {
Poisoned(PoisonError<T>),
WouldBlock,
}
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
impl<T> fmt::Debug for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"PoisonError { inner: .. }".fmt(f)
}
}
impl<T> fmt::Display for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"poisoned lock: another task failed inside".fmt(f)
}
}
impl<T: Send + Any> Error for PoisonError<T> {
fn description(&self) -> &str {
"poisoned lock: another task failed inside"
}
}
impl<T> PoisonError<T> {
pub fn new(guard: T) -> PoisonError<T> {
PoisonError { guard: guard }
}
pub fn into_inner(self) -> T { self.guard }
pub fn get_ref(&self) -> &T { &self.guard }
pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
}
impl<T> From<PoisonError<T>> for TryLockError<T> {
fn from(err: PoisonError<T>) -> TryLockError<T> {
TryLockError::Poisoned(err)
}
}
impl<T> fmt::Debug for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
TryLockError::WouldBlock => "WouldBlock".fmt(f)
}
}
}
impl<T: Send + Any> fmt::Display for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl<T: Send + Any> Error for TryLockError<T> {
fn description(&self) -> &str {
match *self {
TryLockError::Poisoned(ref p) => p.description(),
TryLockError::WouldBlock => "try_lock failed because the operation would block"
}
}
fn cause(&self) -> Option<&Error> {
match *self {
TryLockError::Poisoned(ref p) => Some(p),
_ => None
}
}
}
pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
-> LockResult<U>
where F: FnOnce(T) -> U {
match result {
Ok(t) => Ok(f(t)),
Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
}
}