sync: encapsulate TryLockError variants (#1980)

As there is currently only one variant, make the error type an opaque
struct.
This commit is contained in:
Carl Lerche 2019-12-18 11:50:56 -08:00 committed by GitHub
parent 0c0f682010
commit b0836ece7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -73,25 +73,17 @@ unsafe impl<T> Send for Mutex<T> where T: Send {}
unsafe impl<T> Sync for Mutex<T> where T: Send {} unsafe impl<T> Sync for Mutex<T> where T: Send {}
unsafe impl<'a, T> Sync for MutexGuard<'a, T> where T: Send + Sync {} unsafe impl<'a, T> Sync for MutexGuard<'a, T> where T: Send + Sync {}
/// An enumeration of possible errors associated with a `TryLockResult` /// Error returned from the [`Mutex::try_lock`] function.
/// which can occur while trying to acquire a lock from the `try_lock` ///
/// method on a `Mutex`. /// A `try_lock` operation can only fail if the mutex is already locked.
///
/// [`Mutex::try_lock`]: Mutex::try_lock
#[derive(Debug)] #[derive(Debug)]
pub enum TryLockError { pub struct TryLockError(());
/// The lock could not be acquired at this time because the operation
/// would otherwise block.
WouldBlock,
}
impl fmt::Display for TryLockError { impl fmt::Display for TryLockError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!( write!(fmt, "{}", "operation would block")
fmt,
"{}",
match self {
TryLockError::WouldBlock => "operation would block"
}
)
} }
} }
@ -134,7 +126,7 @@ impl<T> Mutex<T> {
let mut permit = semaphore::Permit::new(); let mut permit = semaphore::Permit::new();
match permit.try_acquire(&self.s) { match permit.try_acquire(&self.s) {
Ok(_) => Ok(MutexGuard { lock: self, permit }), Ok(_) => Ok(MutexGuard { lock: self, permit }),
Err(_) => Err(TryLockError::WouldBlock), Err(_) => Err(TryLockError(())),
} }
} }
} }