Skip to content

Commit

Permalink
[breaking] Implement Iterator for owned ParserIterator (#1587)
Browse files Browse the repository at this point in the history
* Implement Iterator for owned ParserIterator

Also test and fix doctests and examples

---------

Co-authored-by: ambiso <ambiso@invalid>
Co-authored-by: Geoffroy Couprie <contact@geoffroycouprie.com>
  • Loading branch information
3 people authored Oct 21, 2023
1 parent 8c77435 commit c98ffeb
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
1 change: 1 addition & 0 deletions examples/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ fn main() {
);

let res = nom_it
.by_ref()
.map(|(k, v)| (k.to_uppercase(), v))
.collect::<HashMap<_, _>>();

Expand Down
4 changes: 2 additions & 2 deletions src/combinator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -881,7 +881,7 @@ where
/// let data = "abc|defg|hijkl|mnopqr|123";
/// let mut it = iterator(data, terminated(alpha1, tag("|")));
///
/// let parsed = it.map(|v| (v, v.len())).collect::<HashMap<_,_>>();
/// let parsed = it.by_ref().map(|v| (v, v.len())).collect::<HashMap<_,_>>();
/// let res: IResult<_,_> = it.finish();
///
/// assert_eq!(parsed, [("abc", 3usize), ("defg", 4), ("hijkl", 5), ("mnopqr", 6)].iter().cloned().collect());
Expand Down Expand Up @@ -917,7 +917,7 @@ impl<I: Clone, E, F> ParserIterator<I, E, F> {
}
}

impl<'a, Input, Output, Error, F> core::iter::Iterator for &'a mut ParserIterator<Input, Error, F>
impl<Input, Output, Error, F> core::iter::Iterator for ParserIterator<Input, Error, F>
where
F: Parser<Input, Output = Output, Error = Error>,
Input: Clone,
Expand Down
19 changes: 19 additions & 0 deletions tests/issues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,22 @@ fn issue_1617_count_parser_returning_zero_size() {
.expect("parsing should succeed");
assert_eq!(result, ("def", vec![(), (), ()]));
}

#[test]
fn issue_1586_parser_iterator_impl() {
use nom::{
character::complete::{digit1, newline},
combinator::{iterator, opt},
sequence::terminated,
IResult,
};
fn parse_line(i: &str) -> IResult<&str, &str> {
terminated(digit1, opt(newline)).parse(i)
}

fn parse_input(i: &str) -> impl Iterator<Item = i32> + '_ {
iterator(i, parse_line).map(|x| x.parse::<i32>().unwrap())
}

assert_eq!(parse_input("123\n456").collect::<Vec<_>>(), vec![123, 456]);
}

0 comments on commit c98ffeb

Please sign in to comment.