zbus/abstractions/
async_lock.rs

1#[cfg(not(feature = "tokio"))]
2pub(crate) use async_lock::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
3#[cfg(feature = "tokio")]
4pub(crate) use tokio::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
5
6/// An abstraction over async semaphore API.
7#[cfg(not(feature = "tokio"))]
8pub(crate) struct Semaphore(async_lock::Semaphore);
9#[cfg(feature = "tokio")]
10pub(crate) struct Semaphore(tokio::sync::Semaphore);
11
12impl Semaphore {
13    pub const fn new(permits: usize) -> Self {
14        #[cfg(not(feature = "tokio"))]
15        let 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"))]
36pub(crate) type SemaphorePermit<'a> = async_lock::SemaphoreGuard<'a>;
37#[cfg(feature = "tokio")]
38pub(crate) type SemaphorePermit<'a> = tokio::sync::SemaphorePermit<'a>;