sumtype

Attribute Macro sumtype 

Source
#[sumtype]
Expand description

Enables sumtype!(..) macro in the context.

For each context marked by #[sumtype], sumtype creates a union type of several std::iter::Iterator types. To intern an expression of Iterator into the union type, you can use sumtype!([expr]) syntax. This is an example of returning a unified Iterator:

#[sumtype]
fn return_iter(a: bool) -> impl Iterator<Item = ()> {
    if a {
        sumtype!(std::iter::once(()))
    } else {
        sumtype!(vec![()].into_iter())
    }
}

This function returns std::iter::Once or std::vec::IntoIter depending on the a value. The #[sumtype] system creates an anonymous union type that is also std::iter::Iterator, and wraps each sumtype!(..) expression with the union type. The mechanism is zero-cost when a is fixed at compile time.

You can specify the exact (non-anonymous) type using sumtype!() macro in type context. In this case, you should specify the type using sumtype!([expr], [type]) format like:

#[sumtype]
fn return_iter_explicit(a: bool) -> sumtype!() {
    if a {
        sumtype!(std::iter::once(()), std::iter::Once<()>)
    } else {
        sumtype!(vec![()].into_iter(), std::vec::IntoIter<()>)
    }
}

You may need to use additional generic parameters in [ty]. The following example demonstrates this:

struct S;

#[sumtype]
impl S {
    fn f<'a, T>(t: &'a T, count: usize) -> sumtype!['a, T] {
        if count == 0 {
            sumtype!(std::iter::empty(), for<'a, T: 'a> std::iter::Empty<&'a T>)
        } else {
            sumtype!(
                std::iter::repeat(t).take(count),
                for<'a, T: 'a> std::iter::Take<std::iter::Repeat<&'a T>>
            )
        }
    }
}