1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use crate::ion::Value;
use crate::Row;

pub trait FromRow
where
    Self: Sized,
{
    type Err;

    fn from_str_iter<'a, I>(row: I) -> Result<Self, Self::Err>
    where
        I: Iterator<Item = &'a Value>;
}

pub trait ParseRow
where
    Self: Sized,
{
    type Err;

    fn parse<F: FromRow>(&self) -> Result<F, F::Err>;
}

impl ParseRow for Row {
    type Err = ();

    fn parse<F: FromRow>(&self) -> Result<F, F::Err> {
        F::from_str_iter(self.iter())
    }
}

#[cfg(test)]
mod tests {
    use crate::ion::{FromRow, Value};

    macro_rules! parse_next {
        ($row:expr, $err:expr) => {{
            match $row.next() {
                Some(v) => match v.parse() {
                    Ok(v) => v,
                    Err(_) => return Err($err),
                },
                None => return Err($err),
            }
        }};
    }

    #[derive(Debug, PartialEq)]
    struct Foo {
        foo: u32,
        bar: String,
    }

    impl FromRow for Foo {
        type Err = &'static str;

        fn from_str_iter<'a, I: Iterator<Item = &'a Value>>(mut row: I) -> Result<Self, Self::Err> {
            Ok(Foo {
                foo: parse_next!(row, "foo"),
                bar: parse_next!(row, "bar"),
            })
        }
    }

    #[test]
    fn from_row() {
        let row: Vec<_> = "1|foo"
            .split('|')
            .map(|s| Value::String(s.to_owned()))
            .collect();

        let foo = Foo::from_str_iter(row.iter()).unwrap();

        assert_eq!(
            Foo {
                foo: 1,
                bar: "foo".to_owned(),
            },
            foo
        );
    }
}