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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// For types with identical signatures that don't require runtime support,
// we can just arbitrarily pick one to use based on what's enabled.
//
// We'll generally lean towards Tokio's types as those are more featureful
// (including `tokio-console` support) and more widely deployed.

#[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
pub use async_std::sync::{Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard};

#[cfg(feature = "_rt-tokio")]
pub use tokio::sync::{Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard};

pub struct AsyncSemaphore {
    // We use the semaphore from futures-intrusive as the one from async-std
    // is missing the ability to add arbitrary permits, and is not guaranteed to be fair:
    // * https://github.com/smol-rs/async-lock/issues/22
    // * https://github.com/smol-rs/async-lock/issues/23
    //
    // We're on the look-out for a replacement, however, as futures-intrusive is not maintained
    // and there are some soundness concerns (although it turns out any intrusive future is unsound
    // in MIRI due to the necessitated mutable aliasing):
    // https://github.com/launchbadge/sqlx/issues/1668
    #[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
    inner: futures_intrusive::sync::Semaphore,

    #[cfg(feature = "_rt-tokio")]
    inner: tokio::sync::Semaphore,
}

impl AsyncSemaphore {
    #[track_caller]
    pub fn new(fair: bool, permits: usize) -> Self {
        if cfg!(not(any(feature = "_rt-async-std", feature = "_rt-tokio"))) {
            crate::rt::missing_rt((fair, permits));
        }

        AsyncSemaphore {
            #[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
            inner: futures_intrusive::sync::Semaphore::new(fair, permits),
            #[cfg(feature = "_rt-tokio")]
            inner: {
                debug_assert!(fair, "Tokio only has fair permits");
                tokio::sync::Semaphore::new(permits)
            },
        }
    }

    pub fn permits(&self) -> usize {
        #[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
        return self.inner.permits();

        #[cfg(feature = "_rt-tokio")]
        return self.inner.available_permits();

        #[cfg(not(any(feature = "_rt-async-std", feature = "_rt-tokio")))]
        crate::rt::missing_rt(())
    }

    pub async fn acquire(&self, permits: u32) -> AsyncSemaphoreReleaser<'_> {
        #[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
        return AsyncSemaphoreReleaser {
            inner: self.inner.acquire(permits as usize).await,
        };

        #[cfg(feature = "_rt-tokio")]
        return AsyncSemaphoreReleaser {
            inner: self
                .inner
                // Weird quirk: `tokio::sync::Semaphore` mostly uses `usize` for permit counts,
                // but `u32` for this and `try_acquire_many()`.
                .acquire_many(permits)
                .await
                .expect("BUG: we do not expose the `.close()` method"),
        };

        #[cfg(not(any(feature = "_rt-async-std", feature = "_rt-tokio")))]
        crate::rt::missing_rt(permits)
    }

    pub fn try_acquire(&self, permits: u32) -> Option<AsyncSemaphoreReleaser<'_>> {
        #[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
        return Some(AsyncSemaphoreReleaser {
            inner: self.inner.try_acquire(permits as usize)?,
        });

        #[cfg(feature = "_rt-tokio")]
        return Some(AsyncSemaphoreReleaser {
            inner: self.inner.try_acquire_many(permits).ok()?,
        });

        #[cfg(not(any(feature = "_rt-async-std", feature = "_rt-tokio")))]
        crate::rt::missing_rt(permits)
    }

    pub fn release(&self, permits: usize) {
        #[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
        return self.inner.release(permits);

        #[cfg(feature = "_rt-tokio")]
        return self.inner.add_permits(permits);

        #[cfg(not(any(feature = "_rt-async-std", feature = "_rt-tokio")))]
        crate::rt::missing_rt(permits)
    }
}

pub struct AsyncSemaphoreReleaser<'a> {
    // We use the semaphore from futures-intrusive as the one from async-std
    // is missing the ability to add arbitrary permits, and is not guaranteed to be fair:
    // * https://github.com/smol-rs/async-lock/issues/22
    // * https://github.com/smol-rs/async-lock/issues/23
    //
    // We're on the look-out for a replacement, however, as futures-intrusive is not maintained
    // and there are some soundness concerns (although it turns out any intrusive future is unsound
    // in MIRI due to the necessitated mutable aliasing):
    // https://github.com/launchbadge/sqlx/issues/1668
    #[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
    inner: futures_intrusive::sync::SemaphoreReleaser<'a>,

    #[cfg(feature = "_rt-tokio")]
    inner: tokio::sync::SemaphorePermit<'a>,

    #[cfg(not(any(feature = "_rt-async-std", feature = "_rt-tokio")))]
    _phantom: std::marker::PhantomData<&'a ()>,
}

impl AsyncSemaphoreReleaser<'_> {
    pub fn disarm(self) {
        #[cfg(all(feature = "_rt-async-std", not(feature = "_rt-tokio")))]
        {
            let mut this = self;
            this.inner.disarm();
            return;
        }

        #[cfg(feature = "_rt-tokio")]
        {
            self.inner.forget();
            return;
        }

        #[cfg(not(any(feature = "_rt-async-std", feature = "_rt-tokio")))]
        crate::rt::missing_rt(())
    }
}