Trait async_std::stream::Sum[][src]

pub trait Sum<A = Self>: Sized {
    fn sum<'a, S>(stream: S) -> Pin<Box<dyn Future<Output = Self> + 'a>>
Notable traits for Pin<P>
impl<P> Future for Pin<P> where
    P: DerefMut,
    <P as Deref>::Target: Future
type Output = <<P as Deref>::Target as Future>::Output;

    where
        S: Stream<Item = A> + 'a
; }
This is supported on unstable only.
Expand description

Trait to represent types that can be created by summing up a stream.

This trait is used to implement the sum method on streams. Types which implement the trait can be generated by the sum method. Like FromStream this trait should rarely be called directly and instead interacted with through Stream::sum.

Required methods

Method which takes a stream and generates Self from the elements by “summing up” the items.

Implementations on Foreign Types

Takes each element in the Stream: if it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, the sum of all elements is returned.

Examples

This sums up every integer in a vector, rejecting the sum if a negative element is encountered:

use async_std::prelude::*;
use async_std::stream;

let v = stream::from_iter(vec![1, 2]);
let res: Result<i32, &'static str> = v.map(|x|
    if x < 0 {
        Err("Negative element found")
    } else {
        Ok(x)
    }).sum().await;
assert_eq!(res, Ok(3));

Takes each element in the Iterator: if it is a None, no further elements are taken, and the None is returned. Should no None occur, the sum of all elements is returned.

Examples

This sums up the position of the character ‘a’ in a vector of strings, if a word did not have the character ‘a’ the operation returns None:

use async_std::prelude::*;
use async_std::stream;

let words = stream::from_iter(vec!["have", "a", "great", "day"]);
let total: Option<usize> = words.map(|w| w.find('a')).sum().await;
assert_eq!(total, Some(5));

Implementors