Debian Codegraph @

debian/rust-vendor/winnow/examples/iterator.rs

raw
1 use std::collections::HashMap;
2 use std::iter::Iterator;
3
4 use winnow::ascii::alphanumeric1;
5 use winnow::combinator::iterator;
6 use winnow::combinator::{separated_pair, terminated};
7 use winnow::prelude::*;
8
9 fn main() {
10 let mut data = "abcabcabcabc";
11
12 fn parser<'s>(i: &mut &'s str) -> ModalResult<&'s str> {
13 "abc".parse_next(i)
14 }
15
16 // `from_fn` (available from Rust 1.34) can create an iterator
17 // from a closure
18 let it = std::iter::from_fn(move || parser.parse_next(&mut data).ok());
19
20 for value in it {
21 println!("parser returned: {value}");
22 }
23
24 println!("\n********************\n");
25
26 let mut data = "abcabcabcabc";
27
28 // if `from_fn` is not available, it is possible to fold
29 // over an iterator of functions
30 let res = std::iter::repeat(parser)
31 .take(3)
32 .try_fold(Vec::new(), |mut acc, mut parser| {
33 parser.parse_next(&mut data).map(|o| {
34 acc.push(o);
35 acc
36 })
37 });
38
39 // will print "parser iterator returned: Ok(("abc", ["abc", "abc", "abc"]))"
40 println!("\nparser iterator returned: {res:?}");
41
42 println!("\n********************\n");
43
44 let data = "key1:value1,key2:value2,key3:value3,;";
45
46 // `winnow::combinator::iterator` will return an iterator
47 // producing the parsed values. Compared to the previous
48 // solutions:
49 // - we can work with a normal iterator like `from_fn`
50 // - we can get the remaining input afterwards, like with the `try_fold` trick
51 let mut i = data;
52 let mut winnow_it = iterator(
53 &mut i,
54 terminated(separated_pair(alphanumeric1, ":", alphanumeric1), ","),
55 );
56
57 let res = winnow_it
58 .map(|(k, v)| (k.to_uppercase(), v))
59 .collect::<HashMap<_, _>>();
60
61 let parser_result: Result<_, ()> = winnow_it.finish();
62 parser_result.unwrap();
63
64 // will print "iterator returned {"key1": "value1", "key3": "value3", "key2": "value2"}, remaining input is ';'"
65 println!("iterator returned {res:?}, remaining input is '{i}'");
66 }