Skip to content

Commit

Permalink
Fix clamped capacity to be divided by element size (#1549)
Browse files Browse the repository at this point in the history
* Fix clamped capacity to be divided by element size

- Fixes #1459 (comment)
- Also change `clamp` to `min` so this works on Rust 2018 edition.

* Update src/multi/mod.rs

Co-authored-by: Geoffroy Couprie <geo.couprie@gmail.com>
Co-authored-by: Geoffroy Couprie <contact@geoffroycouprie.com>
  • Loading branch information
3 people committed Dec 28, 2022
1 parent ad63809 commit 400331e
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/multi/mod.rs
Expand Up @@ -20,7 +20,8 @@ use core::num::NonZeroUsize;
///
/// This does not affect correctness. Nom will always read the full number
/// of elements regardless of the capacity cap.
const MAX_INITIAL_CAPACITY: usize = 65536;
#[cfg(feature = "alloc")]
const MAX_INITIAL_CAPACITY_BYTES: usize = 65536;

/// Repeats the embedded parser until it fails
/// and returns the results in a `Vec`.
Expand Down Expand Up @@ -373,7 +374,8 @@ where
return Err(Err::Failure(E::from_error_kind(input, ErrorKind::ManyMN)));
}

let mut res = crate::lib::std::vec::Vec::with_capacity(min.clamp(0, MAX_INITIAL_CAPACITY));
let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES / crate::lib::std::mem::size_of::<O>();
let mut res = crate::lib::std::vec::Vec::with_capacity(min.min(max_initial_capacity));
for count in 0..max {
let len = input.input_len();
match parse.parse(input.clone()) {
Expand Down Expand Up @@ -540,7 +542,8 @@ where
{
move |i: I| {
let mut input = i.clone();
let mut res = crate::lib::std::vec::Vec::with_capacity(count.clamp(0, MAX_INITIAL_CAPACITY));
let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES / crate::lib::std::mem::size_of::<O>();
let mut res = crate::lib::std::vec::Vec::with_capacity(count.min(max_initial_capacity));

for _ in 0..count {
let input_ = input.clone();
Expand Down

0 comments on commit 400331e

Please sign in to comment.