1 unstable release

0.1.0 Feb 1, 2020

#112 in #combinator

Download history 16/week @ 2024-03-11 17/week @ 2024-03-18 35/week @ 2024-03-25 60/week @ 2024-04-01 36/week @ 2024-04-08 90/week @ 2024-04-15 47/week @ 2024-04-22 16/week @ 2024-04-29 28/week @ 2024-05-06 38/week @ 2024-05-13 13/week @ 2024-05-20 8/week @ 2024-05-27 23/week @ 2024-06-03 86/week @ 2024-06-10 17/week @ 2024-06-17 21/week @ 2024-06-24

147 downloads per month
Used in struple

MIT/Apache

5KB
73 lines

Struple

Derive a trait for tuple <-> struct conversion for your own struct.

Basic example

use struple::Struple

#[derive(Struple)]
struct Foo(String, u64, f32);

fn main() {
    let string = "hello";
    let int = 3u64;
    let float = 0.5f32;

    let foo = Foo::from_tuple((string, int, float));
    let (string, int, float) = foo.into_tuple(); 
}

Use cases

The main reason as to why I made this crate is because of nom and it's tuple parser combinator. This combinator allows easy chaining of serveral parsers in sequence but has the downside that you gotta destructure the tuple manually to put the data into the corresponding struct. This is cumbersome and bloats the code(at least in my opinion). With this one can just derive a tuple constructor for the struct and pass that constructor to the map function to map the tuple to the struct. It even allows to create a new combinator just for this:

pub fn struple<I, O1, O2, E, List>(l: List) -> impl Fn(I) -> nom::IResult<I, O2, E>
where
    I: Clone,
    O1: struple::GenericTuple,
    O2: struple::Struple<Tuple = O1>,
    E: nom::error::ParseError<I>,
    List: nom::sequence::Tuple<I, O1, E>,
{
    map(tuple(l), struple::Struple::from_tuple)
}

struct Vector3 {
    x: f32,
    y: f32,
    z: f32
}
// with struple
let (i, vec): (_, Vector3) = struple((le_f32, le_f32, le_f32))?;
// without struple
let (i, vec) = map(
    tuple((le_f32, le_f32, le_f32)),
    |(x, y, z)| Vector3 { x, y, z}
)?;

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~1.5MB
~35K SLoC