Crate zipped

Source
Expand description

Utility for recursively unzipping tuples, Options of tuples and Results of tuples.

§Usage

This crate is quiet straightforward.

§Unzipping (((A, B), C), ...)

If you have a left- or right-recursively zipped tuple, you can use UnzipInto::unzip_into to turn it into a non-recursive tuple. This works for up to 26 tuple elements.

use zipped::UnzipInto;

let (a, b, c) = ((1, 2), 3).unzip_into(); // left-recursive
let (a, b, c) = (1, (2, 3)).unzip_into(); // right-recursive

§Unzipping Option<(((A, B), C), ...)>

If you have an Option that contains a left- or right-recursively zipped tuple, you can also use UnzipInto::unzip_into to turn it into an Option of a non-recursive tuple. This also works for up to 26 tuple elements.

use zipped::UnzipInto;

let zipped = Some(1).zip(Some(2)).zip(Some(3));

match zipped.unzip_into() {
    Some((a, b, c)) => {}
    None => {}
}

While it’s also possible to unzip Options with right-recursively zipped tuples, these don’t occur naturally since Option::zip is left-recursive.

§Unzipping Result<(((A, B), C), ...), E>

If you have a Result that contains a left- or right-recursively zipped tuple, you can also use UnzipInto::unzip_into to turn it into a Result of a non-recursive tuple. This also works for up to 26 tuple elements.

use zipped::UnzipInto;

let zipped = Ok::<_, ()>(1)
    .and_then(|a| Ok((a, 2)))
    .and_then(|ab| Ok((ab, 3)));

match zipped.unzip_into() {
    Ok((a, b, c)) => {}
    Err(_) => {}
}

Again, while it’s also possible to unzip Results with right-recursively zipped tuples, I found that these occur much less often.

§Limitations

  • Type inference. The compiler cannot automatically infer T in UnzipInto<T>. Eventually, you will need to specify the return value’s arity.
  • Maximum arity. UnzipFrom is implemented for tuples of up to 26 elements.
  • Strict. It only works for completely zipped tuples where each tuple contains 2 elements and only the left (or the right) element can be another tuple, i.e. it does not work for ((A, B), C, D).

Traits§

UnzipFrom
Value-to-value conversation analogous to From that consumes an input value of type T and returns an unzipped equivalent of this type.
UnzipInto
Value-to-value conversion analogous to Into that consumes an input value of this type and returns an unzipped equivalent of type T.