product_os_semaphore/
raw.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use std::prelude::v1::*;

use core::{
    marker::PhantomData,
    sync::atomic::{AtomicUsize, Ordering},
};

#[cfg(not(feature = "nightly"))]
#[doc(hidden)]
type PhantomUnsend = core::marker::PhantomData<*mut ()>; // Pointers are never send

/// A counter that has a maximum value
pub struct Semaphore {
    count: AtomicUsize,
    pub max: usize,
}

/// A guard for a Semaphore
/// Increments the count on creation
/// Decrements it on Drop
#[must_use]
pub struct SemaphoreGuard<'guard> {
    semaphore: &'guard Semaphore,
    #[cfg(not(feature = "nightly"))]
    _unsend: PhantomUnsend,
}

impl<'guard> Drop for SemaphoreGuard<'guard> {
    fn drop(&mut self) {
        self.semaphore.count.fetch_sub(1, Ordering::SeqCst);
    }
}

impl<'guard> SemaphoreGuard<'guard> {
    fn new(semaphore: &'guard Semaphore) -> Self {
        semaphore.count.fetch_add(1, Ordering::SeqCst);
        SemaphoreGuard {
            semaphore,
            #[cfg(not(feature = "nightly"))]
            _unsend: PhantomData,
        }
    }
}

#[cfg(any(feature = "nightly", doc))]
impl<'guard> !Send for SemaphoreGuard<'guard> {}

unsafe impl<'guard> Sync for SemaphoreGuard<'guard> {}

impl Semaphore {
    #[must_use]
    pub fn count(&self, ordering: Ordering) -> usize {
        self.count.load(ordering)
    }

    #[must_use]
    pub fn new(max: usize) -> Self {
        Semaphore {
            max,
            count: AtomicUsize::new(0),
        }
    }

    #[must_use]
    pub fn at_max(&self, ordering: Ordering) -> bool {
        self.count.load(ordering) >= self.max
    }

    /// Try to increment the count and return a Guard
    ///
    /// Never blocks
    /// # Errors
    /// Will error if the count is at max already

    pub fn try_get(&self) -> Result<SemaphoreGuard, crate::SemaphoreError> {
        if self.at_max(Ordering::SeqCst) {
            Err(crate::SemaphoreError::AtMaxCount)
        } else {
            Ok(SemaphoreGuard::new(self))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_maximum_count_works() {
        let semaphore = Semaphore::new(4);

        let (g1, g2, g3, g4) = (
            semaphore.try_get(),
            semaphore.try_get(),
            semaphore.try_get(),
            semaphore.try_get(),
        );

        assert_eq!(
            (g1.is_ok(), g2.is_ok(), g3.is_ok(), g4.is_ok()),
            (true, true, true, true)
        );

        let g5 = semaphore.try_get();

        assert!(g5.is_err());

        drop(g1);

        let g6 = semaphore.try_get();

        assert!(g6.is_ok());
    }
}