avoid panic when counting zero-sized outputs in count() (#1618)

* avoid panic when counting zero-sized outputs in count()

* run cargo fmt
This commit is contained in:
Michael Bryant 2023-01-15 11:13:12 -08:00 committed by Geoffroy Couprie
parent 6be62d30d7
commit ee7ad17086
2 changed files with 13 additions and 1 deletions

View File

@ -573,7 +573,8 @@ where
{
move |i: I| {
let mut input = i.clone();
let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES / crate::lib::std::mem::size_of::<O>();
let max_initial_capacity =
MAX_INITIAL_CAPACITY_BYTES / crate::lib::std::mem::size_of::<O>().max(1);
let mut res = crate::lib::std::vec::Vec::with_capacity(count.min(max_initial_capacity));
for _ in 0..count {

View File

@ -229,3 +229,14 @@ fn issue_1459_clamp_capacity() {
let mut parser = count::<_, _, (), _>(char('a'), usize::MAX);
assert_eq!(parser("a"), Err(nom::Err::Error(())));
}
#[test]
fn issue_1617_count_parser_returning_zero_size() {
use nom::{bytes::complete::tag, combinator::map, error::Error, multi::count};
// previously, `count()` panicked if the parser had type `O = ()`
let parser = map(tag::<_, _, Error<&str>>("abc"), |_| ());
// shouldn't panic
let result = count(parser, 3)("abcabcabcdef").expect("parsing should succeed");
assert_eq!(result, ("def", vec![(), (), ()]));
}