1 | #[cfg (not(feature = "tokio" ))] |
2 | pub(crate) use async_lock::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; |
3 | #[cfg (feature = "tokio" )] |
4 | pub(crate) use tokio::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; |
5 | |
6 | /// An abstraction over async semaphore API. |
7 | #[cfg (not(feature = "tokio" ))] |
8 | pub(crate) struct Semaphore(async_lock::Semaphore); |
9 | #[cfg (feature = "tokio" )] |
10 | pub(crate) struct Semaphore(tokio::sync::Semaphore); |
11 | |
12 | impl Semaphore { |
13 | pub const fn new(permits: usize) -> Self { |
14 | #[cfg (not(feature = "tokio" ))] |
15 | let semaphore: Semaphore = async_lock::Semaphore::new(permits); |
16 | #[cfg (feature = "tokio" )] |
17 | let semaphore = tokio::sync::Semaphore::const_new(permits); |
18 | |
19 | Self(semaphore) |
20 | } |
21 | |
22 | pub async fn acquire(&self) -> SemaphorePermit<'_> { |
23 | #[cfg (not(feature = "tokio" ))] |
24 | { |
25 | self.0.acquire().await |
26 | } |
27 | #[cfg (feature = "tokio" )] |
28 | { |
29 | // SAFETY: Since we never explicitly close the sempaphore, `acquire` can't fail. |
30 | self.0.acquire().await.unwrap() |
31 | } |
32 | } |
33 | } |
34 | |
35 | #[cfg (not(feature = "tokio" ))] |
36 | pub(crate) type SemaphorePermit<'a> = async_lock::SemaphoreGuard<'a>; |
37 | #[cfg (feature = "tokio" )] |
38 | pub(crate) type SemaphorePermit<'a> = tokio::sync::SemaphorePermit<'a>; |
39 | |