#futures #option

futures-option

Extension traits for dealing with optional futures and streams

4 releases

0.2.0 Jan 5, 2020
0.1.2 Aug 20, 2019
0.1.1 Jul 19, 2019
0.1.0 Jul 19, 2019
Download history 1/week @ 2020-10-31 20/week @ 2020-11-14 5/week @ 2020-11-21 4/week @ 2020-11-28 7/week @ 2020-12-05 8/week @ 2020-12-12 20/week @ 2021-01-02 23/week @ 2021-01-09 21/week @ 2021-01-16 1/week @ 2021-01-23 8/week @ 2021-02-06 12/week @ 2021-02-13

94 downloads per month

MIT/Apache

9KB
124 lines

Option Extensions for Futures

Build Status

Extension traits for dealing with optional futures and streams.

Examples

use futures::{future::{self, FusedFuture as _}};
use futures_option::OptionExt as _;

futures::executor::block_on(async {
    let mut f = Some(future::ready::<u32>(1));
    assert!(f.is_some());
    assert_eq!(f.current().await, 1);
    assert!(f.is_none());
    assert!(f.current().is_terminated());
});

This is useful when you want to implement optional branches using the select! macro.

#![recursion_limit="128"]

use futures::{future, stream, StreamExt as _};
use futures_option::OptionExt as _;

futures::executor::block_on(async {
    let mut value = None;
    let mut values = Some(stream::iter(vec![1u32, 2u32, 4u32].into_iter()).fuse());
    let mut parked = None;

    let mut sum = 0;

    loop {
        futures::select! {
            value = value.current() => {
                sum += value;
                std::mem::swap(&mut parked, &mut values);
            }
            v = values.next() => {
                match v {
                    Some(v) => {
                        value = Some(future::ready(v));
                        std::mem::swap(&mut parked, &mut values);
                    },
                    None => break,
                }
            }
        }
    }

    assert_eq!(7, sum);
});

Dependencies

~27KB