Skip to content

Commit

Permalink
add default wrapper for Future and Stream
Browse files Browse the repository at this point in the history
  • Loading branch information
akiradeveloper committed Aug 16, 2021
1 parent c2dbd54 commit d1c7aec
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,7 @@ categories = ["concurrency"]

[dev-dependencies]
pin-project-lite = "0.2.7"
futures = { version = "0.3" }

[dependencies]
futures-core = { version = "0.3" }
62 changes: 62 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
use core::{
fmt::{self, Debug, Formatter},
pin::Pin,
future::Future,
task::{Context, Poll},
};

/// A mutual exclusion primitive that relies on static type information only
Expand Down Expand Up @@ -181,3 +183,63 @@ impl<T> From<T> for SyncWrapper<T> {
Self::new(value)
}
}


pub struct SyncFuture<F> {
inner: SyncWrapper<F>
}
impl <F: Future> SyncFuture<F> {
/// Create a `Future` which is `Sync`.
///
/// # Examples
///
/// ```
/// use sync_wrapper::{SyncWrapper, SyncFuture};
///
/// let fut = async { 1 };
/// let fut = SyncFuture::new(fut);
/// ```
pub fn new(inner: F) -> Self {
Self { inner: SyncWrapper::new(inner) }
}
pub fn into_inner(self) -> SyncWrapper<F> {
self.inner
}
}
impl <F: Future> Future for SyncFuture<F> {
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let inner = unsafe { self.map_unchecked_mut(|x| x.inner.get_mut()) };
inner.poll(cx)
}
}

pub struct SyncStream<S> {
inner: SyncWrapper<S>
}
impl <S: futures_core::Stream> SyncStream<S> {
/// Create a `Stream` which is `Sync`.
///
/// # Examples
///
/// ```
/// use sync_wrapper::SyncStream;
/// use futures::stream;
///
/// let st = stream::iter(vec![1]);
/// let st = SyncStream::new(st);
/// ```
pub fn new(inner: S) -> Self {
Self { inner: SyncWrapper::new(inner) }
}
pub fn into_inner(self) -> SyncWrapper<S> {
self.inner
}
}
impl <S: futures_core::Stream> futures_core::Stream for SyncStream<S> {
type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let inner = unsafe { self.map_unchecked_mut(|x| x.inner.get_mut()) };
inner.poll_next(cx)
}
}

0 comments on commit d1c7aec

Please sign in to comment.