ranked_semaphore/
error.rs

1use std::fmt;
2
3/// Error returned from acquire operations when the semaphore has been closed.
4#[derive(Debug)]
5pub struct AcquireError(());
6
7/// Error returned from try_acquire operations.
8#[derive(Debug, PartialEq, Eq)]
9pub enum TryAcquireError {
10    /// The semaphore has been closed and cannot issue new permits.
11    Closed,
12    /// The semaphore has no available permits.
13    NoPermits,
14}
15
16impl AcquireError {
17    pub(crate) fn closed() -> AcquireError {
18        AcquireError(())
19    }
20}
21
22impl fmt::Display for AcquireError {
23    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
24        write!(fmt, "semaphore closed")
25    }
26}
27
28impl std::error::Error for AcquireError {}
29
30impl TryAcquireError {
31    /// Returns `true` if the error was caused by a closed semaphore.
32    pub fn is_closed(&self) -> bool {
33        matches!(self, TryAcquireError::Closed)
34    }
35
36    /// Returns `true` if the error was caused by insufficient permits.
37    pub fn is_no_permits(&self) -> bool {
38        matches!(self, TryAcquireError::NoPermits)
39    }
40}
41
42impl fmt::Display for TryAcquireError {
43    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
44        match self {
45            TryAcquireError::Closed => write!(fmt, "semaphore closed"),
46            TryAcquireError::NoPermits => write!(fmt, "no permits available"),
47        }
48    }
49}
50
51impl std::error::Error for TryAcquireError {}