use futures_core::{ready, Stream};
use std::fmt;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::sync::{AcquireError, OwnedSemaphorePermit, Semaphore};
use super::ReusableBoxFuture;
pub struct PollSemaphore {
semaphore: Arc<Semaphore>,
permit_fut: ReusableBoxFuture<Result<OwnedSemaphorePermit, AcquireError>>,
}
impl PollSemaphore {
pub fn new(semaphore: Arc<Semaphore>) -> Self {
let fut = Arc::clone(&semaphore).acquire_owned();
Self {
semaphore,
permit_fut: ReusableBoxFuture::new(fut),
}
}
pub fn close(&self) {
self.semaphore.close()
}
pub fn clone_inner(&self) -> Arc<Semaphore> {
self.semaphore.clone()
}
pub fn into_inner(self) -> Arc<Semaphore> {
self.semaphore
}
pub fn poll_acquire(&mut self, cx: &mut Context<'_>) -> Poll<Option<OwnedSemaphorePermit>> {
match ready!(self.permit_fut.poll(cx)) {
Ok(permit) => {
let next_fut = Arc::clone(&self.semaphore).acquire_owned();
self.permit_fut.set(next_fut);
Poll::Ready(Some(permit))
}
Err(_closed) => Poll::Ready(None),
}
}
}
impl Stream for PollSemaphore {
type Item = OwnedSemaphorePermit;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<OwnedSemaphorePermit>> {
Pin::into_inner(self).poll_acquire(cx)
}
}
impl Clone for PollSemaphore {
fn clone(&self) -> PollSemaphore {
PollSemaphore::new(self.clone_inner())
}
}
impl fmt::Debug for PollSemaphore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PollSemaphore")
.field("semaphore", &self.semaphore)
.finish()
}
}