Skip to content

Commit

Permalink
avoid panic when counting zero-sized outputs in count() (#1618)
Browse files Browse the repository at this point in the history
* avoid panic when counting zero-sized outputs in count()

* run cargo fmt
  • Loading branch information
Shadow53 authored and Geal committed Jan 15, 2023
1 parent 6be62d3 commit 520d040
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/multi/mod.rs
Expand Up @@ -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 {
Expand Down
11 changes: 11 additions & 0 deletions tests/issues.rs
Expand Up @@ -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![(), (), ()]));
}

0 comments on commit 520d040

Please sign in to comment.