Skip to content

Commit

Permalink
feat: Add direct conversion for optional future and streams
Browse files Browse the repository at this point in the history
  • Loading branch information
dariusc93 committed Feb 24, 2025
1 parent e43d575 commit c34f952
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/futures/optional.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ impl<F> From<Option<F>> for OptionalFuture<F> {
}
}

impl<F: Future> From<F> for OptionalFuture<F> {
fn from(fut: F) -> Self {
Self {
future: Some(fut),
waker: None,
}
}
}

impl<F> OptionalFuture<F> {
/// Construct a new `OptionalFuture` with an existing `Future`.
pub fn new(future: F) -> Self {
Expand Down Expand Up @@ -149,4 +158,17 @@ mod test {
assert_eq!(val, Poll::Ready(1));
assert!(future.is_none());
}

#[test]
fn convert_future_to_optional_future() {
let fut = futures::future::ready(0);

let mut future = OptionalFuture::from(fut);
assert!(future.is_some());
let waker = futures::task::noop_waker_ref();

let val = Pin::new(&mut future).poll(&mut Context::from_waker(waker));
assert_eq!(val, Poll::Ready(0));
assert!(future.is_none());
}
}
27 changes: 27 additions & 0 deletions src/stream/optional.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ impl<S> From<Option<S>> for OptionalStream<S> {
}
}

impl<S: Stream> From<S> for OptionalStream<S> {
fn from(st: S) -> Self {
Self {
stream: Some(st),
waker: None,
}
}
}

impl<S> OptionalStream<S> {
/// Constructs a new `OptionalStream` with an existing `Stream`.
pub fn new(st: S) -> Self {
Expand Down Expand Up @@ -169,4 +178,22 @@ mod test {
assert_eq!(val, Poll::Ready(None));
assert!(stream.is_none());
}

#[test]
fn convert_stream_to_optional_stream() {
let st = futures::stream::once(async { 0 }).boxed();

let mut stream = OptionalStream::from(st);

assert!(stream.is_some());
let waker = futures::task::noop_waker_ref();

let val = Pin::new(&mut stream).poll_next(&mut Context::from_waker(waker));
assert_eq!(val, Poll::Ready(Some(0)));
assert!(stream.is_some());

let val = Pin::new(&mut stream).poll_next(&mut Context::from_waker(waker));
assert_eq!(val, Poll::Ready(None));
assert!(stream.is_none());
}
}

0 comments on commit c34f952

Please sign in to comment.