From 05b0b24acaf304d89101e9f5bea8989c495c0f44 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Wed, 25 Sep 2024 20:55:52 -0400 Subject: Better error implementation --- src/poisonable/error.rs | 22 ++++++++++++++++++++++ src/poisonable/poisonable.rs | 18 ++++++++---------- 2 files changed, 30 insertions(+), 10 deletions(-) (limited to 'src/poisonable') diff --git a/src/poisonable/error.rs b/src/poisonable/error.rs index 98a167c..2384953 100644 --- a/src/poisonable/error.rs +++ b/src/poisonable/error.rs @@ -17,6 +17,28 @@ impl fmt::Display for PoisonError { impl Error for PoisonError {} +impl PoisonError { + #[must_use] + pub const fn new(guard: Guard) -> Self { + Self { guard } + } + + #[must_use] + pub fn into_inner(self) -> Guard { + self.guard + } + + #[must_use] + pub const fn get_ref(&self) -> &Guard { + &self.guard + } + + #[must_use] + pub fn get_mut(&mut self) -> &mut Guard { + &mut self.guard + } +} + impl<'flag, 'key, G, Key> fmt::Debug for TryLockPoisonableError<'flag, 'key, G, Key> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { diff --git a/src/poisonable/poisonable.rs b/src/poisonable/poisonable.rs index 6c78346..f774e2d 100644 --- a/src/poisonable/poisonable.rs +++ b/src/poisonable/poisonable.rs @@ -26,7 +26,7 @@ unsafe impl Lockable for Poisonable { if self.is_poisoned() { Ok(ref_guard) } else { - Err(PoisonError { guard: ref_guard }) + Err(PoisonError::new(ref_guard)) } } @@ -39,7 +39,7 @@ unsafe impl Lockable for Poisonable { if self.is_poisoned() { Ok(ref_guard) } else { - Err(PoisonError { guard: ref_guard }) + Err(PoisonError::new(ref_guard)) } } } @@ -71,11 +71,11 @@ impl Poisonable { _phantom: PhantomData, }; - if self.is_poisoned() { - Ok(guard) - } else { - Err(PoisonError { guard }) + if !self.is_poisoned() { + return Err(PoisonError::new(guard)); } + + Ok(guard) } pub fn lock<'flag, 'key, Key: Keyable + 'key>( @@ -118,7 +118,7 @@ impl Poisonable { pub fn into_inner(self) -> PoisonResult { if self.is_poisoned() { - Err(PoisonError { guard: self.inner }) + Err(PoisonError::new(self.inner)) } else { Ok(self.inner) } @@ -126,9 +126,7 @@ impl Poisonable { pub fn get_mut(&mut self) -> PoisonResult<&mut L> { if self.is_poisoned() { - Err(PoisonError { - guard: &mut self.inner, - }) + Err(PoisonError::new(&mut self.inner)) } else { Ok(&mut self.inner) } -- cgit v1.2.3