nom/multi/
mod.rs

1//! Combinators applying their child parser multiple times
2
3#[cfg(test)]
4mod tests;
5
6use core::marker::PhantomData;
7
8use crate::bytes::take;
9use crate::error::ErrorKind;
10use crate::error::ParseError;
11use crate::internal::{Err, Needed, Parser};
12use crate::lib::std::num::NonZeroUsize;
13#[cfg(feature = "alloc")]
14use crate::lib::std::vec::Vec;
15use crate::traits::ToUsize;
16use crate::Check;
17use crate::Emit;
18use crate::Input;
19use crate::Mode;
20use crate::NomRange;
21use crate::OutputM;
22use crate::OutputMode;
23
24/// Don't pre-allocate more than 64KiB when calling `Vec::with_capacity`.
25///
26/// Pre-allocating memory is a nice optimization but count fields can't
27/// always be trusted. We should clamp initial capacities to some reasonable
28/// amount. This reduces the risk of a bogus count value triggering a panic
29/// due to an OOM error.
30///
31/// This does not affect correctness. Nom will always read the full number
32/// of elements regardless of the capacity cap.
33#[cfg(feature = "alloc")]
34const MAX_INITIAL_CAPACITY_BYTES: usize = 65536;
35
36/// Repeats the embedded parser, gathering the results in a `Vec`.
37///
38/// This stops on [`Err::Error`] and returns the results that were accumulated. To instead chain an error up, see
39/// [`cut`][crate::combinator::cut].
40///
41/// # Arguments
42/// * `f` The parser to apply.
43///
44/// *Note*: if the parser passed in accepts empty inputs (like `alpha0` or `digit0`), `many0` will
45/// return an error, to prevent going into an infinite loop
46///
47/// ```rust
48/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
49/// use nom::multi::many0;
50/// use nom::bytes::complete::tag;
51///
52/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
53///   many0(tag("abc")).parse(s)
54/// }
55///
56/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
57/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
58/// assert_eq!(parser("123123"), Ok(("123123", vec![])));
59/// assert_eq!(parser(""), Ok(("", vec![])));
60/// ```
61#[cfg(feature = "alloc")]
62#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
63pub fn many0<I, F>(
64  f: F,
65) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = <F as Parser<I>>::Error>
66where
67  I: Clone + Input,
68  F: Parser<I>,
69{
70  Many0 { parser: f }
71}
72
73#[cfg(feature = "alloc")]
74/// Parser implementation for the [many0] combinator
75pub struct Many0<F> {
76  parser: F,
77}
78
79#[cfg(feature = "alloc")]
80impl<I, F> Parser<I> for Many0<F>
81where
82  I: Clone + Input,
83  F: Parser<I>,
84{
85  type Output = crate::lib::std::vec::Vec<<F as Parser<I>>::Output>;
86  type Error = <F as Parser<I>>::Error;
87
88  fn process<OM: OutputMode>(
89    &mut self,
90    mut i: I,
91  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
92    let mut acc = OM::Output::bind(|| crate::lib::std::vec::Vec::with_capacity(4));
93    loop {
94      let len = i.input_len();
95      match self
96        .parser
97        .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
98      {
99        Err(Err::Error(_)) => return Ok((i, acc)),
100        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
101        Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
102        Ok((i1, o)) => {
103          // infinite loop check: the parser must always consume
104          if i1.input_len() == len {
105            return Err(Err::Error(OM::Error::bind(|| {
106              <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::Many0)
107            })));
108          }
109
110          i = i1;
111
112          acc = OM::Output::combine(acc, o, |mut acc, o| {
113            acc.push(o);
114            acc
115          })
116        }
117      }
118    }
119  }
120}
121
122/// Runs the embedded parser, gathering the results in a `Vec`.
123///
124/// This stops on [`Err::Error`] if there is at least one result,  and returns the results that were accumulated. To instead chain an error up,
125/// see [`cut`][crate::combinator::cut].
126///
127/// # Arguments
128/// * `f` The parser to apply.
129///
130/// *Note*: If the parser passed to `many1` accepts empty inputs
131/// (like `alpha0` or `digit0`), `many1` will return an error,
132/// to prevent going into an infinite loop.
133///
134/// ```rust
135/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
136/// use nom::multi::many1;
137/// use nom::bytes::complete::tag;
138///
139/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
140///   many1(tag("abc")).parse(s)
141/// }
142///
143/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
144/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
145/// assert_eq!(parser("123123"), Err(Err::Error(Error::new("123123", ErrorKind::Tag))));
146/// assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Tag))));
147/// ```
148#[cfg(feature = "alloc")]
149#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
150pub fn many1<I, F>(
151  parser: F,
152) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = <F as Parser<I>>::Error>
153where
154  I: Clone + Input,
155  F: Parser<I>,
156{
157  Many1 { parser }
158}
159
160#[cfg(feature = "alloc")]
161/// Parser implementation for the [many1] combinator
162pub struct Many1<F> {
163  parser: F,
164}
165
166#[cfg(feature = "alloc")]
167impl<I, F> Parser<I> for Many1<F>
168where
169  I: Clone + Input,
170  F: Parser<I>,
171{
172  type Output = Vec<<F as Parser<I>>::Output>;
173  type Error = <F as Parser<I>>::Error;
174
175  fn process<OM: OutputMode>(
176    &mut self,
177    mut i: I,
178  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
179    match self
180      .parser
181      .process::<OutputM<OM::Output, Emit, OM::Incomplete>>(i.clone())
182    {
183      Err(Err::Error(err)) => Err(Err::Error(OM::Error::bind(|| {
184        <F as Parser<I>>::Error::append(i, ErrorKind::Many1, err)
185      }))),
186      Err(Err::Failure(e)) => Err(Err::Failure(e)),
187      Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),
188      Ok((i1, o)) => {
189        let mut acc = OM::Output::map(o, |o| {
190          let mut acc = crate::lib::std::vec::Vec::with_capacity(4);
191          acc.push(o);
192          acc
193        });
194
195        i = i1;
196
197        loop {
198          let len = i.input_len();
199          match self
200            .parser
201            .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
202          {
203            Err(Err::Error(_)) => return Ok((i, acc)),
204            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
205            Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
206            Ok((i1, o)) => {
207              // infinite loop check: the parser must always consume
208              if i1.input_len() == len {
209                return Err(Err::Error(OM::Error::bind(|| {
210                  <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::Many0)
211                })));
212              }
213
214              i = i1;
215
216              acc = OM::Output::combine(acc, o, |mut acc, o| {
217                acc.push(o);
218                acc
219              })
220            }
221          }
222        }
223      }
224    }
225  }
226}
227
228/// Applies the parser `f` until the parser `g` produces a result.
229///
230/// Returns a tuple of the results of `f` in a `Vec` and the result of `g`.
231///
232/// `f` keeps going so long as `g` produces [`Err::Error`]. To instead chain an error up, see [`cut`][crate::combinator::cut].
233///
234/// ```rust
235/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
236/// use nom::multi::many_till;
237/// use nom::bytes::complete::tag;
238///
239/// fn parser(s: &str) -> IResult<&str, (Vec<&str>, &str)> {
240///   many_till(tag("abc"), tag("end")).parse(s)
241/// };
242///
243/// assert_eq!(parser("abcabcend"), Ok(("", (vec!["abc", "abc"], "end"))));
244/// assert_eq!(parser("abc123end"), Err(Err::Error(Error::new("123end", ErrorKind::Tag))));
245/// assert_eq!(parser("123123end"), Err(Err::Error(Error::new("123123end", ErrorKind::Tag))));
246/// assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Tag))));
247/// assert_eq!(parser("abcendefg"), Ok(("efg", (vec!["abc"], "end"))));
248/// ```
249#[cfg(feature = "alloc")]
250#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
251pub fn many_till<I, E, F, G>(
252  f: F,
253  g: G,
254) -> impl Parser<I, Output = (Vec<<F as Parser<I>>::Output>, <G as Parser<I>>::Output), Error = E>
255where
256  I: Clone + Input,
257  F: Parser<I, Error = E>,
258  G: Parser<I, Error = E>,
259  E: ParseError<I>,
260{
261  ManyTill {
262    f,
263    g,
264    e: PhantomData,
265  }
266}
267
268#[cfg(feature = "alloc")]
269/// Parser implementation for the [many_till] combinator
270pub struct ManyTill<F, G, E> {
271  f: F,
272  g: G,
273  e: PhantomData<E>,
274}
275
276#[cfg(feature = "alloc")]
277impl<I, F, G, E> Parser<I> for ManyTill<F, G, E>
278where
279  I: Clone + Input,
280  F: Parser<I, Error = E>,
281  G: Parser<I, Error = E>,
282  E: ParseError<I>,
283{
284  type Output = (Vec<<F as Parser<I>>::Output>, <G as Parser<I>>::Output);
285  type Error = E;
286
287  fn process<OM: OutputMode>(
288    &mut self,
289    mut i: I,
290  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
291    let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);
292    loop {
293      let len = i.input_len();
294      match self
295        .g
296        .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
297      {
298        Ok((i1, o)) => return Ok((i1, OM::Output::combine(res, o, |res, o| (res, o)))),
299        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
300        Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),
301        Err(Err::Error(_)) => {
302          match self.f.process::<OM>(i.clone()) {
303            Err(Err::Error(err)) => {
304              return Err(Err::Error(OM::Error::map(err, |err| {
305                E::append(i, ErrorKind::ManyTill, err)
306              })))
307            }
308            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
309            Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
310            Ok((i1, o)) => {
311              // infinite loop check: the parser must always consume
312              if i1.input_len() == len {
313                return Err(Err::Error(OM::Error::bind(|| {
314                  E::from_error_kind(i, ErrorKind::Many0)
315                })));
316              }
317
318              i = i1;
319
320              res = OM::Output::combine(res, o, |mut acc, o| {
321                acc.push(o);
322                acc
323              })
324            }
325          }
326        }
327      }
328    }
329  }
330}
331
332/// Alternates between two parsers to produce a list of elements.
333///
334/// This stops when either parser returns [`Err::Error`]  and returns the results that were accumulated. To instead chain an error up, see
335/// [`cut`][crate::combinator::cut].
336///
337/// # Arguments
338/// * `sep` Parses the separator between list elements.
339/// * `f` Parses the elements of the list.
340///
341/// ```rust
342/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
343/// use nom::multi::separated_list0;
344/// use nom::bytes::complete::tag;
345///
346/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
347///   separated_list0(tag("|"), tag("abc")).parse(s)
348/// }
349///
350/// assert_eq!(parser("abc|abc|abc"), Ok(("", vec!["abc", "abc", "abc"])));
351/// assert_eq!(parser("abc123abc"), Ok(("123abc", vec!["abc"])));
352/// assert_eq!(parser("abc|def"), Ok(("|def", vec!["abc"])));
353/// assert_eq!(parser(""), Ok(("", vec![])));
354/// assert_eq!(parser("def|abc"), Ok(("def|abc", vec![])));
355/// ```
356#[cfg(feature = "alloc")]
357#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
358pub fn separated_list0<I, E, F, G>(
359  sep: G,
360  f: F,
361) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = E>
362where
363  I: Clone + Input,
364  F: Parser<I, Error = E>,
365  G: Parser<I, Error = E>,
366  E: ParseError<I>,
367{
368  SeparatedList0 {
369    parser: f,
370    separator: sep,
371  }
372}
373
374#[cfg(feature = "alloc")]
375/// Parser implementation for the [separated_list0] combinator
376pub struct SeparatedList0<F, G> {
377  parser: F,
378  separator: G,
379}
380
381#[cfg(feature = "alloc")]
382impl<I, E: ParseError<I>, F, G> Parser<I> for SeparatedList0<F, G>
383where
384  I: Clone + Input,
385  F: Parser<I, Error = E>,
386  G: Parser<I, Error = E>,
387{
388  type Output = Vec<<F as Parser<I>>::Output>;
389  type Error = <F as Parser<I>>::Error;
390
391  fn process<OM: OutputMode>(
392    &mut self,
393    mut i: I,
394  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
395    let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);
396
397    match self
398      .parser
399      .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
400    {
401      Err(Err::Error(_)) => return Ok((i, res)),
402      Err(Err::Failure(e)) => return Err(Err::Failure(e)),
403      Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
404      Ok((i1, o)) => {
405        res = OM::Output::combine(res, o, |mut res, o| {
406          res.push(o);
407          res
408        });
409        i = i1;
410      }
411    }
412
413    loop {
414      let len = i.input_len();
415      match self
416        .separator
417        .process::<OutputM<Check, Check, OM::Incomplete>>(i.clone())
418      {
419        Err(Err::Error(_)) => return Ok((i, res)),
420        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
421        Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
422        Ok((i1, _)) => {
423          match self
424            .parser
425            .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i1.clone())
426          {
427            Err(Err::Error(_)) => return Ok((i, res)),
428            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
429            Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
430            Ok((i2, o)) => {
431              // infinite loop check: the parser must always consume
432              if i2.input_len() == len {
433                return Err(Err::Error(OM::Error::bind(|| {
434                  <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::SeparatedList)
435                })));
436              }
437
438              res = OM::Output::combine(res, o, |mut res, o| {
439                res.push(o);
440                res
441              });
442
443              i = i2;
444            }
445          }
446        }
447      }
448    }
449  }
450}
451
452/// Alternates between two parsers to produce a list of elements until [`Err::Error`].
453///
454/// Fails if the element parser does not produce at least one element.
455///
456/// This stops when either parser returns [`Err::Error`]  and returns the results that were accumulated. To instead chain an error up, see
457/// [`cut`][crate::combinator::cut].
458///
459/// # Arguments
460/// * `sep` Parses the separator between list elements.
461/// * `f` Parses the elements of the list.
462/// ```rust
463/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
464/// use nom::multi::separated_list1;
465/// use nom::bytes::complete::tag;
466///
467/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
468///   separated_list1(tag("|"), tag("abc")).parse(s)
469/// }
470///
471/// assert_eq!(parser("abc|abc|abc"), Ok(("", vec!["abc", "abc", "abc"])));
472/// assert_eq!(parser("abc123abc"), Ok(("123abc", vec!["abc"])));
473/// assert_eq!(parser("abc|def"), Ok(("|def", vec!["abc"])));
474/// assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Tag))));
475/// assert_eq!(parser("def|abc"), Err(Err::Error(Error::new("def|abc", ErrorKind::Tag))));
476/// ```
477#[cfg(feature = "alloc")]
478#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
479pub fn separated_list1<I, E, F, G>(
480  separator: G,
481  parser: F,
482) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = E>
483where
484  I: Clone + Input,
485  F: Parser<I, Error = E>,
486  G: Parser<I, Error = E>,
487  E: ParseError<I>,
488{
489  SeparatedList1 { parser, separator }
490}
491
492#[cfg(feature = "alloc")]
493/// Parser implementation for the [separated_list1] combinator
494pub struct SeparatedList1<F, G> {
495  parser: F,
496  separator: G,
497}
498
499#[cfg(feature = "alloc")]
500impl<I, E: ParseError<I>, F, G> Parser<I> for SeparatedList1<F, G>
501where
502  I: Clone + Input,
503  F: Parser<I, Error = E>,
504  G: Parser<I, Error = E>,
505{
506  type Output = Vec<<F as Parser<I>>::Output>;
507  type Error = <F as Parser<I>>::Error;
508
509  fn process<OM: OutputMode>(
510    &mut self,
511    mut i: I,
512  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
513    let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);
514
515    match self.parser.process::<OM>(i.clone()) {
516      Err(e) => return Err(e),
517      Ok((i1, o)) => {
518        res = OM::Output::combine(res, o, |mut res, o| {
519          res.push(o);
520          res
521        });
522        i = i1;
523      }
524    }
525
526    loop {
527      let len = i.input_len();
528      match self
529        .separator
530        .process::<OutputM<Check, Check, OM::Incomplete>>(i.clone())
531      {
532        Err(Err::Error(_)) => return Ok((i, res)),
533        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
534        Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
535        Ok((i1, _)) => {
536          match self
537            .parser
538            .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i1.clone())
539          {
540            Err(Err::Error(_)) => return Ok((i, res)),
541            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
542            Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
543            Ok((i2, o)) => {
544              // infinite loop check: the parser must always consume
545              if i2.input_len() == len {
546                return Err(Err::Error(OM::Error::bind(|| {
547                  <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::SeparatedList)
548                })));
549              }
550
551              res = OM::Output::combine(res, o, |mut res, o| {
552                res.push(o);
553                res
554              });
555              i = i2;
556            }
557          }
558        }
559      }
560    }
561  }
562}
563
564/// Repeats the embedded parser `m..=n` times
565///
566/// This stops before `n` when the parser returns [`Err::Error`]  and returns the results that were accumulated. To instead chain an error up, see
567/// [`cut`][crate::combinator::cut].
568///
569/// # Arguments
570/// * `m` The minimum number of iterations.
571/// * `n` The maximum number of iterations.
572/// * `f` The parser to apply.
573///
574/// *Note*: If the parser passed to `many1` accepts empty inputs
575/// (like `alpha0` or `digit0`), `many1` will return an error,
576/// to prevent going into an infinite loop.
577///
578/// ```rust
579/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
580/// use nom::multi::many_m_n;
581/// use nom::bytes::complete::tag;
582///
583/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
584///   many_m_n(0, 2, tag("abc")).parse(s)
585/// }
586///
587/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
588/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
589/// assert_eq!(parser("123123"), Ok(("123123", vec![])));
590/// assert_eq!(parser(""), Ok(("", vec![])));
591/// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
592/// ```
593#[cfg(feature = "alloc")]
594#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
595pub fn many_m_n<I, E, F>(
596  min: usize,
597  max: usize,
598  parser: F,
599) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = E>
600where
601  I: Clone + Input,
602  F: Parser<I, Error = E>,
603  E: ParseError<I>,
604{
605  ManyMN { parser, min, max }
606}
607
608#[cfg(feature = "alloc")]
609/// Parser implementation for the [many_m_n] combinator
610pub struct ManyMN<F> {
611  parser: F,
612  min: usize,
613  max: usize,
614}
615
616#[cfg(feature = "alloc")]
617impl<I, F> Parser<I> for ManyMN<F>
618where
619  I: Clone + Input,
620  F: Parser<I>,
621{
622  type Output = Vec<<F as Parser<I>>::Output>;
623  type Error = <F as Parser<I>>::Error;
624
625  fn process<OM: OutputMode>(
626    &mut self,
627    mut input: I,
628  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
629    if self.min > self.max {
630      return Err(Err::Failure(<F as Parser<I>>::Error::from_error_kind(
631        input,
632        ErrorKind::ManyMN,
633      )));
634    }
635
636    let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES
637      / crate::lib::std::mem::size_of::<<F as Parser<I>>::Output>().max(1);
638    let mut res = OM::Output::bind(|| {
639      crate::lib::std::vec::Vec::with_capacity(self.min.min(max_initial_capacity))
640    });
641    for count in 0..self.max {
642      let len = input.input_len();
643      match self.parser.process::<OM>(input.clone()) {
644        Ok((tail, value)) => {
645          // infinite loop check: the parser must always consume
646          if tail.input_len() == len {
647            return Err(Err::Error(OM::Error::bind(|| {
648              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::ManyMN)
649            })));
650          }
651
652          res = OM::Output::combine(res, value, |mut res, value| {
653            res.push(value);
654            res
655          });
656          input = tail;
657        }
658        Err(Err::Error(e)) => {
659          if count < self.min {
660            return Err(Err::Error(OM::Error::map(e, |e| {
661              <F as Parser<I>>::Error::append(input, ErrorKind::ManyMN, e)
662            })));
663          } else {
664            return Ok((input, res));
665          }
666        }
667        Err(e) => {
668          return Err(e);
669        }
670      }
671    }
672
673    Ok((input, res))
674  }
675}
676
677/// Repeats the embedded parser, counting the results
678///
679/// This stops on [`Err::Error`]. To instead chain an error up, see
680/// [`cut`][crate::combinator::cut].
681///
682/// # Arguments
683/// * `f` The parser to apply.
684///
685/// *Note*: if the parser passed in accepts empty inputs (like `alpha0` or `digit0`), `many0` will
686/// return an error, to prevent going into an infinite loop
687///
688/// ```rust
689/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
690/// use nom::multi::many0_count;
691/// use nom::bytes::complete::tag;
692///
693/// fn parser(s: &str) -> IResult<&str, usize> {
694///   many0_count(tag("abc")).parse(s)
695/// }
696///
697/// assert_eq!(parser("abcabc"), Ok(("", 2)));
698/// assert_eq!(parser("abc123"), Ok(("123", 1)));
699/// assert_eq!(parser("123123"), Ok(("123123", 0)));
700/// assert_eq!(parser(""), Ok(("", 0)));
701/// ```
702pub fn many0_count<I, E, F>(parser: F) -> impl Parser<I, Output = usize, Error = E>
703where
704  I: Clone + Input,
705  F: Parser<I, Error = E>,
706  E: ParseError<I>,
707{
708  Many0Count { parser }
709}
710
711/// Parser implementation for the [many0_count] combinator
712pub struct Many0Count<F> {
713  parser: F,
714}
715
716impl<I, F> Parser<I> for Many0Count<F>
717where
718  I: Clone + Input,
719  F: Parser<I>,
720{
721  type Output = usize;
722  type Error = <F as Parser<I>>::Error;
723
724  fn process<OM: OutputMode>(
725    &mut self,
726    mut input: I,
727  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
728    let mut count = 0;
729
730    loop {
731      let input_ = input.clone();
732      let len = input.input_len();
733      match self
734        .parser
735        .process::<OutputM<Check, Check, OM::Incomplete>>(input_)
736      {
737        Ok((i, _)) => {
738          // infinite loop check: the parser must always consume
739          if i.input_len() == len {
740            return Err(Err::Error(OM::Error::bind(|| {
741              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many0Count)
742            })));
743          }
744
745          input = i;
746          count += 1;
747        }
748
749        Err(Err::Error(_)) => return Ok((input, OM::Output::bind(|| count))),
750        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
751        Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),
752      }
753    }
754  }
755}
756
757/// Runs the embedded parser, counting the results.
758///
759/// This stops on [`Err::Error`] if there is at least one result. To instead chain an error up,
760/// see [`cut`][crate::combinator::cut].
761///
762/// # Arguments
763/// * `f` The parser to apply.
764///
765/// *Note*: If the parser passed to `many1` accepts empty inputs
766/// (like `alpha0` or `digit0`), `many1` will return an error,
767/// to prevent going into an infinite loop.
768///
769/// ```rust
770/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
771/// use nom::multi::many1_count;
772/// use nom::bytes::complete::tag;
773///
774/// fn parser(s: &str) -> IResult<&str, usize> {
775///   many1_count(tag("abc")).parse(s)
776/// }
777///
778/// assert_eq!(parser("abcabc"), Ok(("", 2)));
779/// assert_eq!(parser("abc123"), Ok(("123", 1)));
780/// assert_eq!(parser("123123"), Err(Err::Error(Error::new("123123", ErrorKind::Many1Count))));
781/// assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Many1Count))));
782/// ```
783pub fn many1_count<I, E, F>(parser: F) -> impl Parser<I, Output = usize, Error = E>
784where
785  I: Clone + Input,
786  F: Parser<I, Error = E>,
787  E: ParseError<I>,
788{
789  Many1Count { parser }
790}
791
792/// Parser implementation for the [many1_count] combinator
793pub struct Many1Count<F> {
794  parser: F,
795}
796
797impl<I, F> Parser<I> for Many1Count<F>
798where
799  I: Clone + Input,
800  F: Parser<I>,
801{
802  type Output = usize;
803  type Error = <F as Parser<I>>::Error;
804
805  fn process<OM: OutputMode>(
806    &mut self,
807    input: I,
808  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
809    let mut count = 0;
810
811    match self
812      .parser
813      .process::<OutputM<Check, Check, OM::Incomplete>>(input.clone())
814    {
815      Err(Err::Error(_)) => Err(Err::Error(OM::Error::bind(move || {
816        <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many1Count)
817      }))),
818      Err(Err::Failure(e)) => Err(Err::Failure(e)),
819      Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),
820      Ok((mut input, _)) => {
821        count += 1;
822
823        loop {
824          let input_ = input.clone();
825          let len = input.input_len();
826          match self
827            .parser
828            .process::<OutputM<Check, Check, OM::Incomplete>>(input_)
829          {
830            Ok((i, _)) => {
831              // infinite loop check: the parser must always consume
832              if i.input_len() == len {
833                return Err(Err::Error(OM::Error::bind(|| {
834                  <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many1Count)
835                })));
836              }
837
838              input = i;
839              count += 1;
840            }
841
842            Err(Err::Error(_)) => return Ok((input, OM::Output::bind(|| count))),
843            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
844            Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),
845          }
846        }
847      }
848    }
849  }
850}
851
852/// Runs the embedded parser `count` times, gathering the results in a `Vec`
853///
854/// # Arguments
855/// * `f` The parser to apply.
856/// * `count` How often to apply the parser.
857/// ```rust
858/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
859/// use nom::multi::count;
860/// use nom::bytes::complete::tag;
861///
862/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
863///   count(tag("abc"), 2).parse(s)
864/// }
865///
866/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
867/// assert_eq!(parser("abc123"), Err(Err::Error(Error::new("123", ErrorKind::Tag))));
868/// assert_eq!(parser("123123"), Err(Err::Error(Error::new("123123", ErrorKind::Tag))));
869/// assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Tag))));
870/// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
871/// ```
872#[cfg(feature = "alloc")]
873#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
874pub fn count<I, F>(
875  parser: F,
876  count: usize,
877) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = <F as Parser<I>>::Error>
878where
879  I: Clone,
880  F: Parser<I>,
881{
882  Count { parser, count }
883}
884
885#[cfg(feature = "alloc")]
886/// Parser implementation for the [count] combinator
887pub struct Count<F> {
888  parser: F,
889  count: usize,
890}
891
892#[cfg(feature = "alloc")]
893impl<I, F> Parser<I> for Count<F>
894where
895  I: Clone,
896  F: Parser<I>,
897{
898  type Output = Vec<<F as Parser<I>>::Output>;
899  type Error = <F as Parser<I>>::Error;
900
901  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
902    let mut input = i.clone();
903    let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES
904      / crate::lib::std::mem::size_of::<<F as Parser<I>>::Output>().max(1);
905    let mut res = OM::Output::bind(|| {
906      crate::lib::std::vec::Vec::with_capacity(self.count.min(max_initial_capacity))
907    });
908
909    for _ in 0..self.count {
910      let input_ = input.clone();
911      match self.parser.process::<OM>(input_) {
912        Ok((i, o)) => {
913          res = OM::Output::combine(res, o, |mut res, o| {
914            res.push(o);
915            res
916          });
917          input = i;
918        }
919        Err(Err::Error(e)) => {
920          return Err(Err::Error(OM::Error::map(e, |e| {
921            <F as Parser<I>>::Error::append(i, ErrorKind::Count, e)
922          })));
923        }
924        Err(e) => {
925          return Err(e);
926        }
927      }
928    }
929
930    Ok((input, res))
931  }
932}
933
934/// Runs the embedded parser repeatedly, filling the given slice with results.
935///
936/// This parser fails if the input runs out before the given slice is full.
937///
938/// # Arguments
939/// * `f` The parser to apply.
940/// * `buf` The slice to fill
941/// ```rust
942/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
943/// use nom::multi::fill;
944/// use nom::bytes::complete::tag;
945///
946/// fn parser(s: &str) -> IResult<&str, [&str; 2]> {
947///   let mut buf = ["", ""];
948///   let (rest, ()) = fill(tag("abc"), &mut buf).parse(s)?;
949///   Ok((rest, buf))
950/// }
951///
952/// assert_eq!(parser("abcabc"), Ok(("", ["abc", "abc"])));
953/// assert_eq!(parser("abc123"), Err(Err::Error(Error::new("123", ErrorKind::Tag))));
954/// assert_eq!(parser("123123"), Err(Err::Error(Error::new("123123", ErrorKind::Tag))));
955/// assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Tag))));
956/// assert_eq!(parser("abcabcabc"), Ok(("abc", ["abc", "abc"])));
957/// ```
958pub fn fill<'a, I, E, F>(
959  parser: F,
960  buf: &'a mut [<F as Parser<I>>::Output],
961) -> impl Parser<I, Output = (), Error = E> + 'a
962where
963  I: Clone,
964  F: Parser<I, Error = E> + 'a,
965  E: ParseError<I>,
966{
967  Fill { parser, buf }
968}
969
970/// Parser implementation for the [fill] combinator
971pub struct Fill<'a, F, O> {
972  parser: F,
973  buf: &'a mut [O],
974}
975
976impl<'a, I, F, O> Parser<I> for Fill<'a, F, O>
977where
978  I: Clone,
979  F: Parser<I, Output = O>,
980{
981  type Output = ();
982  type Error = <F as Parser<I>>::Error;
983
984  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
985    let mut input = i.clone();
986
987    for elem in self.buf.iter_mut() {
988      let input_ = input.clone();
989      match self.parser.process::<OM>(input_) {
990        Ok((i, o)) => {
991          OM::Output::map(o, |o| *elem = o);
992          input = i;
993        }
994        Err(Err::Error(e)) => {
995          return Err(Err::Error(OM::Error::map(e, |e| {
996            <F as Parser<I>>::Error::append(i, ErrorKind::Count, e)
997          })));
998        }
999        Err(e) => {
1000          return Err(e);
1001        }
1002      }
1003    }
1004
1005    Ok((input, OM::Output::bind(|| ())))
1006  }
1007}
1008
1009/// Repeats the embedded parser, calling `g` to gather the results.
1010///
1011/// This stops on [`Err::Error`]. To instead chain an error up, see
1012/// [`cut`][crate::combinator::cut].
1013///
1014/// # Arguments
1015/// * `f` The parser to apply.
1016/// * `init` A function returning the initial value.
1017/// * `g` The function that combines a result of `f` with
1018///       the current accumulator.
1019///
1020/// *Note*: if the parser passed in accepts empty inputs (like `alpha0` or `digit0`), `many0` will
1021/// return an error, to prevent going into an infinite loop
1022///
1023/// ```rust
1024/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
1025/// use nom::multi::fold_many0;
1026/// use nom::bytes::complete::tag;
1027///
1028/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
1029///   fold_many0(
1030///     tag("abc"),
1031///     Vec::new,
1032///     |mut acc: Vec<_>, item| {
1033///       acc.push(item);
1034///       acc
1035///     }
1036///   ).parse(s)
1037/// }
1038///
1039/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
1040/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
1041/// assert_eq!(parser("123123"), Ok(("123123", vec![])));
1042/// assert_eq!(parser(""), Ok(("", vec![])));
1043/// ```
1044pub fn fold_many0<I, E, F, G, H, R>(
1045  parser: F,
1046  init: H,
1047  g: G,
1048) -> impl Parser<I, Output = R, Error = E>
1049where
1050  I: Clone + Input,
1051  F: Parser<I, Error = E>,
1052  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1053  H: FnMut() -> R,
1054  E: ParseError<I>,
1055{
1056  FoldMany0 {
1057    parser,
1058    g,
1059    init,
1060    r: PhantomData,
1061  }
1062}
1063
1064/// Parser implementation for the [fold_many0] combinator
1065pub struct FoldMany0<F, G, Init, R> {
1066  parser: F,
1067  g: G,
1068  init: Init,
1069  r: PhantomData<R>,
1070}
1071
1072impl<I, F, G, Init, R> Parser<I> for FoldMany0<F, G, Init, R>
1073where
1074  I: Clone + Input,
1075  F: Parser<I>,
1076  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1077  Init: FnMut() -> R,
1078{
1079  type Output = R;
1080  type Error = <F as Parser<I>>::Error;
1081
1082  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1083    let mut res = OM::Output::bind(|| (self.init)());
1084    let mut input = i;
1085
1086    loop {
1087      let i_ = input.clone();
1088      let len = input.input_len();
1089      match self.parser.process::<OM>(i_) {
1090        Ok((i, o)) => {
1091          // infinite loop check: the parser must always consume
1092          if i.input_len() == len {
1093            return Err(Err::Error(OM::Error::bind(|| {
1094              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many0)
1095            })));
1096          }
1097
1098          res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));
1099          input = i;
1100        }
1101        Err(Err::Error(_)) => {
1102          return Ok((input, res));
1103        }
1104        Err(e) => {
1105          return Err(e);
1106        }
1107      }
1108    }
1109  }
1110}
1111
1112/// Repeats the embedded parser, calling `g` to gather the results.
1113///
1114/// This stops on [`Err::Error`] if there is at least one result. To instead chain an error up,
1115/// see [`cut`][crate::combinator::cut].
1116///
1117/// # Arguments
1118/// * `f` The parser to apply.
1119/// * `init` A function returning the initial value.
1120/// * `g` The function that combines a result of `f` with
1121///       the current accumulator.
1122///
1123/// *Note*: If the parser passed to `many1` accepts empty inputs
1124/// (like `alpha0` or `digit0`), `many1` will return an error,
1125/// to prevent going into an infinite loop.
1126///
1127/// ```rust
1128/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
1129/// use nom::multi::fold_many1;
1130/// use nom::bytes::complete::tag;
1131///
1132/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
1133///   fold_many1(
1134///     tag("abc"),
1135///     Vec::new,
1136///     |mut acc: Vec<_>, item| {
1137///       acc.push(item);
1138///       acc
1139///     }
1140///   ).parse(s)
1141/// }
1142///
1143/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
1144/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
1145/// assert_eq!(parser("123123"), Err(Err::Error(Error::new("123123", ErrorKind::Many1))));
1146/// assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Many1))));
1147/// ```
1148pub fn fold_many1<I, E, F, G, H, R>(
1149  parser: F,
1150  init: H,
1151  g: G,
1152) -> impl Parser<I, Output = R, Error = E>
1153where
1154  I: Clone + Input,
1155  F: Parser<I, Error = E>,
1156  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1157  H: FnMut() -> R,
1158  E: ParseError<I>,
1159{
1160  FoldMany1 {
1161    parser,
1162    g,
1163    init,
1164    r: PhantomData,
1165  }
1166}
1167
1168/// Parser implementation for the [fold_many1] combinator
1169pub struct FoldMany1<F, G, Init, R> {
1170  parser: F,
1171  g: G,
1172  init: Init,
1173  r: PhantomData<R>,
1174}
1175
1176impl<I, F, G, Init, R> Parser<I> for FoldMany1<F, G, Init, R>
1177where
1178  I: Clone + Input,
1179  F: Parser<I>,
1180  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1181  Init: FnMut() -> R,
1182{
1183  type Output = R;
1184  type Error = <F as Parser<I>>::Error;
1185
1186  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1187    let mut res = OM::Output::bind(|| (self.init)());
1188    let input = i.clone();
1189
1190    match self.parser.process::<OM>(input) {
1191      Err(Err::Error(_)) => Err(Err::Error(OM::Error::bind(|| {
1192        <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::Many1)
1193      }))),
1194      Err(e) => Err(e),
1195      Ok((i1, o1)) => {
1196        res = OM::Output::combine(res, o1, |res, o| (self.g)(res, o));
1197
1198        let mut input = i1;
1199        loop {
1200          let i_ = input.clone();
1201          let len = input.input_len();
1202          match self.parser.process::<OM>(i_) {
1203            Ok((i, o)) => {
1204              // infinite loop check: the parser must always consume
1205              if i.input_len() == len {
1206                return Err(Err::Error(OM::Error::bind(|| {
1207                  <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many1)
1208                })));
1209              }
1210
1211              res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));
1212              input = i;
1213            }
1214            Err(Err::Error(_)) => {
1215              return Ok((input, res));
1216            }
1217            Err(e) => {
1218              return Err(e);
1219            }
1220          }
1221        }
1222      }
1223    }
1224  }
1225}
1226
1227/// Repeats the embedded parser `m..=n` times, calling `g` to gather the results
1228///
1229/// This stops before `n` when the parser returns [`Err::Error`]. To instead chain an error up, see
1230/// [`cut`][crate::combinator::cut].
1231///
1232/// # Arguments
1233/// * `m` The minimum number of iterations.
1234/// * `n` The maximum number of iterations.
1235/// * `f` The parser to apply.
1236/// * `init` A function returning the initial value.
1237/// * `g` The function that combines a result of `f` with
1238///       the current accumulator.
1239///
1240/// *Note*: If the parser passed to `many1` accepts empty inputs
1241/// (like `alpha0` or `digit0`), `many1` will return an error,
1242/// to prevent going into an infinite loop.
1243///
1244/// ```rust
1245/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
1246/// use nom::multi::fold_many_m_n;
1247/// use nom::bytes::complete::tag;
1248///
1249/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
1250///   fold_many_m_n(
1251///     0,
1252///     2,
1253///     tag("abc"),
1254///     Vec::new,
1255///     |mut acc: Vec<_>, item| {
1256///       acc.push(item);
1257///       acc
1258///     }
1259///   ).parse(s)
1260/// }
1261///
1262/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
1263/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
1264/// assert_eq!(parser("123123"), Ok(("123123", vec![])));
1265/// assert_eq!(parser(""), Ok(("", vec![])));
1266/// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
1267/// ```
1268pub fn fold_many_m_n<I, E, F, G, H, R>(
1269  min: usize,
1270  max: usize,
1271  parser: F,
1272  init: H,
1273  g: G,
1274) -> impl Parser<I, Output = R, Error = E>
1275where
1276  I: Clone + Input,
1277  F: Parser<I, Error = E>,
1278  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1279  H: FnMut() -> R,
1280  E: ParseError<I>,
1281{
1282  FoldManyMN {
1283    parser,
1284    g,
1285    init,
1286    min,
1287    max,
1288    r: PhantomData,
1289  }
1290}
1291
1292/// Parser implementation for the [fold_many_m_n] combinator
1293pub struct FoldManyMN<F, G, Init, R> {
1294  parser: F,
1295  g: G,
1296  init: Init,
1297  r: PhantomData<R>,
1298  min: usize,
1299  max: usize,
1300}
1301
1302impl<I, F, G, Init, R> Parser<I> for FoldManyMN<F, G, Init, R>
1303where
1304  I: Clone + Input,
1305  F: Parser<I>,
1306  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1307  Init: FnMut() -> R,
1308{
1309  type Output = R;
1310  type Error = <F as Parser<I>>::Error;
1311
1312  fn process<OM: OutputMode>(
1313    &mut self,
1314    mut input: I,
1315  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1316    if self.min > self.max {
1317      return Err(Err::Error(OM::Error::bind(|| {
1318        <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::ManyMN)
1319      })));
1320    }
1321
1322    let mut res = OM::Output::bind(|| (self.init)());
1323    for count in 0..self.max {
1324      let len = input.input_len();
1325      match self.parser.process::<OM>(input.clone()) {
1326        Ok((tail, value)) => {
1327          // infinite loop check: the parser must always consume
1328          if tail.input_len() == len {
1329            return Err(Err::Error(OM::Error::bind(|| {
1330              <F as Parser<I>>::Error::from_error_kind(tail, ErrorKind::ManyMN)
1331            })));
1332          }
1333
1334          res = OM::Output::combine(res, value, |res, o| (self.g)(res, o));
1335          input = tail;
1336        }
1337        Err(Err::Error(err)) => {
1338          if count < self.min {
1339            return Err(Err::Error(OM::Error::map(err, |err| {
1340              <F as Parser<I>>::Error::append(input, ErrorKind::ManyMN, err)
1341            })));
1342          } else {
1343            break;
1344          }
1345        }
1346        Err(e) => return Err(e),
1347      }
1348    }
1349
1350    Ok((input, res))
1351  }
1352}
1353
1354/// Gets a number from the parser and returns a
1355/// subslice of the input of that size.
1356/// If the parser returns `Incomplete`,
1357/// `length_data` will return an error.
1358/// # Arguments
1359/// * `f` The parser to apply.
1360/// ```rust
1361/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
1362/// use nom::number::complete::be_u16;
1363/// use nom::multi::length_data;
1364/// use nom::bytes::complete::tag;
1365///
1366/// fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> {
1367///   length_data(be_u16).parse(s)
1368/// }
1369///
1370/// assert_eq!(parser(b"\x00\x03abcefg"), Ok((&b"efg"[..], &b"abc"[..])));
1371/// assert_eq!(parser(b"\x00\x03a"), Err(Err::Incomplete(Needed::new(2))));
1372/// ```
1373pub fn length_data<I, E, F>(f: F) -> impl Parser<I, Output = I, Error = E>
1374where
1375  I: Input,
1376  <F as Parser<I>>::Output: ToUsize,
1377  F: Parser<I, Error = E>,
1378  E: ParseError<I>,
1379{
1380  f.flat_map(|size| take(size))
1381}
1382
1383/// Gets a number from the first parser,
1384/// takes a subslice of the input of that size,
1385/// then applies the second parser on that subslice.
1386/// If the second parser returns `Incomplete`,
1387/// `length_value` will return an error.
1388/// # Arguments
1389/// * `f` The parser to apply.
1390/// * `g` The parser to apply on the subslice.
1391/// ```rust
1392/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
1393/// use nom::number::complete::be_u16;
1394/// use nom::multi::length_value;
1395/// use nom::bytes::complete::tag;
1396///
1397/// fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> {
1398///   length_value(be_u16, tag("abc")).parse(s)
1399/// }
1400///
1401/// assert_eq!(parser(b"\x00\x03abcefg"), Ok((&b"efg"[..], &b"abc"[..])));
1402/// assert_eq!(parser(b"\x00\x03123123"), Err(Err::Error(Error::new(&b"123"[..], ErrorKind::Tag))));
1403/// assert_eq!(parser(b"\x00\x03a"), Err(Err::Incomplete(Needed::new(2))));
1404/// ```
1405pub fn length_value<I, E, F, G>(
1406  f: F,
1407  g: G,
1408) -> impl Parser<I, Output = <G as Parser<I>>::Output, Error = E>
1409where
1410  I: Clone + Input,
1411  <F as Parser<I>>::Output: ToUsize,
1412  F: Parser<I, Error = E>,
1413  G: Parser<I, Error = E>,
1414  E: ParseError<I>,
1415{
1416  /*f.flat_map(|size| {
1417    println!("got size: {size}");
1418    take(size)
1419  })
1420  .and_then(g)*/
1421  LengthValue {
1422    length: f,
1423    parser: g,
1424    e: PhantomData,
1425  }
1426}
1427
1428/// Parser implementation for the [length_value] combinator
1429pub struct LengthValue<F, G, E> {
1430  length: F,
1431  parser: G,
1432  e: PhantomData<E>,
1433}
1434
1435impl<I, F, G, E> Parser<I> for LengthValue<F, G, E>
1436where
1437  I: Clone + Input,
1438  F: Parser<I, Error = E>,
1439  G: Parser<I, Error = E>,
1440  <F as Parser<I>>::Output: ToUsize,
1441  E: ParseError<I>,
1442{
1443  type Output = <G as Parser<I>>::Output;
1444  type Error = E;
1445
1446  fn process<OM: OutputMode>(
1447    &mut self,
1448    input: I,
1449  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1450    let (i, length) = self
1451      .length
1452      .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(input)?;
1453
1454    let length: usize = length.to_usize();
1455
1456    if let Some(needed) = length
1457      .checked_sub(i.input_len())
1458      .and_then(NonZeroUsize::new)
1459    {
1460      Err(Err::Incomplete(Needed::Size(needed)))
1461    } else {
1462      let (rest, i) = i.take_split(length);
1463      match self.parser.process::<OM>(i.clone()) {
1464        Err(Err::Incomplete(_)) => Err(Err::Error(OM::Error::bind(|| {
1465          E::from_error_kind(i, ErrorKind::Complete)
1466        }))),
1467        Err(e) => Err(e),
1468        Ok((_, o)) => Ok((rest, o)),
1469      }
1470    }
1471  }
1472}
1473
1474/// Gets a number from the first parser,
1475/// then applies the second parser that many times.
1476/// # Arguments
1477/// * `f` The parser to apply to obtain the count.
1478/// * `g` The parser to apply repeatedly.
1479/// ```rust
1480/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};
1481/// use nom::number::complete::u8;
1482/// use nom::multi::length_count;
1483/// use nom::bytes::complete::tag;
1484/// use nom::combinator::map;
1485///
1486/// fn parser(s: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {
1487///   length_count(map(u8, |i| {
1488///      println!("got number: {}", i);
1489///      i
1490///   }), tag("abc")).parse(s)
1491/// }
1492///
1493/// assert_eq!(parser(&b"\x02abcabcabc"[..]), Ok(((&b"abc"[..], vec![&b"abc"[..], &b"abc"[..]]))));
1494/// assert_eq!(parser(b"\x03123123123"), Err(Err::Error(Error::new(&b"123123123"[..], ErrorKind::Tag))));
1495/// ```
1496#[cfg(feature = "alloc")]
1497pub fn length_count<I, E, F, G>(
1498  f: F,
1499  g: G,
1500) -> impl Parser<I, Output = Vec<<G as Parser<I>>::Output>, Error = E>
1501where
1502  I: Clone,
1503  <F as Parser<I>>::Output: ToUsize,
1504  F: Parser<I, Error = E>,
1505  G: Parser<I, Error = E>,
1506  E: ParseError<I>,
1507{
1508  LengthCount {
1509    length: f,
1510    parser: g,
1511    e: PhantomData,
1512  }
1513}
1514
1515#[cfg(feature = "alloc")]
1516/// Parser implementation for the [length_count] combinator
1517pub struct LengthCount<F, G, E> {
1518  length: F,
1519  parser: G,
1520  e: PhantomData<E>,
1521}
1522
1523#[cfg(feature = "alloc")]
1524impl<I, F, G, E> Parser<I> for LengthCount<F, G, E>
1525where
1526  I: Clone,
1527  F: Parser<I, Error = E>,
1528  G: Parser<I, Error = E>,
1529  <F as Parser<I>>::Output: ToUsize,
1530  E: ParseError<I>,
1531{
1532  type Output = Vec<<G as Parser<I>>::Output>;
1533  type Error = E;
1534
1535  fn process<OM: OutputMode>(
1536    &mut self,
1537    input: I,
1538  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1539    match self
1540      .length
1541      .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(input)
1542    {
1543      Err(e) => Err(e),
1544      Ok((i, count)) => {
1545        let count = count.to_usize();
1546        let mut input = i.clone();
1547        let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES
1548          / crate::lib::std::mem::size_of::<<F as Parser<I>>::Output>().max(1);
1549        let mut res = OM::Output::bind(|| {
1550          crate::lib::std::vec::Vec::with_capacity(count.min(max_initial_capacity))
1551        });
1552
1553        for _ in 0..count {
1554          let input_ = input.clone();
1555          match self.parser.process::<OM>(input_) {
1556            Ok((i, o)) => {
1557              res = OM::Output::combine(res, o, |mut res, o| {
1558                res.push(o);
1559                res
1560              });
1561              input = i;
1562            }
1563            Err(Err::Error(e)) => {
1564              return Err(Err::Error(OM::Error::map(e, |e| {
1565                <F as Parser<I>>::Error::append(i, ErrorKind::Count, e)
1566              })));
1567            }
1568            Err(e) => {
1569              return Err(e);
1570            }
1571          }
1572        }
1573
1574        Ok((input, res))
1575      }
1576    }
1577  }
1578}
1579
1580/// Repeats the embedded parser and collects the results in a type implementing `Extend + Default`.
1581/// Fails if the amount of time the embedded parser is run is not
1582/// within the specified range.
1583/// # Arguments
1584/// * `range` Constrains the number of iterations.
1585///   * A range without an upper bound `a..` is equivalent to a range of `a..=usize::MAX`.
1586///   * A single `usize` value is equivalent to `value..=value`.
1587///   * An empty range is invalid.
1588/// * `parse` The parser to apply.
1589///
1590/// ```rust
1591/// # #[macro_use] extern crate nom;
1592/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
1593/// use nom::multi::many;
1594/// use nom::bytes::complete::tag;
1595///
1596/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
1597///   many(0..=2, tag("abc")).parse(s)
1598/// }
1599///
1600/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
1601/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
1602/// assert_eq!(parser("123123"), Ok(("123123", vec![])));
1603/// assert_eq!(parser(""), Ok(("", vec![])));
1604/// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
1605/// ```
1606///
1607/// This is not limited to `Vec`, other collections like `HashMap`
1608/// can be used:
1609///
1610/// ```rust
1611/// # #[macro_use] extern crate nom;
1612/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
1613/// use nom::multi::many;
1614/// use nom::bytes::complete::{tag, take_while};
1615/// use nom::sequence::{separated_pair, terminated};
1616/// use nom::AsChar;
1617///
1618/// use std::collections::HashMap;
1619///
1620/// fn key_value(s: &str) -> IResult<&str, HashMap<&str, &str>> {
1621///   many(0.., terminated(
1622///     separated_pair(
1623///       take_while(AsChar::is_alpha),
1624///       tag("="),
1625///       take_while(AsChar::is_alpha)
1626///     ),
1627///     tag(";")
1628///   )).parse(s)
1629/// }
1630///
1631/// assert_eq!(
1632///   key_value("a=b;c=d;"),
1633///   Ok(("", HashMap::from([("a", "b"), ("c", "d")])))
1634/// );
1635/// ```
1636///
1637/// If more control is needed on the default value, [fold] can
1638/// be used instead:
1639///
1640/// ```rust
1641/// # #[macro_use] extern crate nom;
1642/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
1643/// use nom::multi::fold;
1644/// use nom::bytes::complete::tag;
1645///
1646///
1647/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
1648///   fold(
1649///     0..=4,
1650///     tag("abc"),
1651///     // preallocates a vector of the max size
1652///     || Vec::with_capacity(4),
1653///     |mut acc: Vec<_>, item| {
1654///       acc.push(item);
1655///       acc
1656///     }
1657///   ).parse(s)
1658/// }
1659///
1660///
1661/// assert_eq!(parser("abcabcabcabc"), Ok(("", vec!["abc", "abc", "abc", "abc"])));
1662/// ```
1663#[cfg(feature = "alloc")]
1664#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
1665pub fn many<I, E, Collection, F, G>(
1666  range: G,
1667  parser: F,
1668) -> impl Parser<I, Output = Collection, Error = E>
1669where
1670  I: Clone + Input,
1671  F: Parser<I, Error = E>,
1672  Collection: Extend<<F as Parser<I>>::Output> + Default,
1673  E: ParseError<I>,
1674  G: NomRange<usize>,
1675{
1676  Many {
1677    parser,
1678    range,
1679    c: PhantomData,
1680  }
1681}
1682
1683/// Parser implementation for the [many] combinator
1684pub struct Many<F, R, Collection> {
1685  parser: F,
1686  range: R,
1687  c: PhantomData<Collection>,
1688}
1689
1690impl<I, F, R, Collection> Parser<I> for Many<F, R, Collection>
1691where
1692  I: Clone + Input,
1693  F: Parser<I>,
1694  Collection: Extend<<F as Parser<I>>::Output> + Default,
1695  R: NomRange<usize>,
1696{
1697  type Output = Collection;
1698  type Error = <F as Parser<I>>::Error;
1699
1700  fn process<OM: OutputMode>(
1701    &mut self,
1702    mut input: I,
1703  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1704    if self.range.is_inverted() {
1705      return Err(Err::Failure(<F as Parser<I>>::Error::from_error_kind(
1706        input,
1707        ErrorKind::Many,
1708      )));
1709    }
1710
1711    let mut res = OM::Output::bind(Collection::default);
1712
1713    for count in self.range.bounded_iter() {
1714      let len = input.input_len();
1715      match self.parser.process::<OM>(input.clone()) {
1716        Ok((tail, value)) => {
1717          // infinite loop check: the parser must always consume
1718          if tail.input_len() == len {
1719            return Err(Err::Error(OM::Error::bind(|| {
1720              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many)
1721            })));
1722          }
1723
1724          res = OM::Output::combine(res, value, |mut res, value| {
1725            res.extend(Some(value));
1726            res
1727          });
1728          input = tail;
1729        }
1730        Err(Err::Error(e)) => {
1731          if !self.range.contains(&count) {
1732            return Err(Err::Error(OM::Error::map(e, |e| {
1733              <F as Parser<I>>::Error::append(input, ErrorKind::Many, e)
1734            })));
1735          } else {
1736            return Ok((input, res));
1737          }
1738        }
1739        Err(e) => {
1740          return Err(e);
1741        }
1742      }
1743    }
1744
1745    Ok((input, res))
1746  }
1747}
1748
1749/// Applies a parser and accumulates the results using a given
1750/// function and initial value.
1751/// Fails if the amount of time the embedded parser is run is not
1752/// within the specified range.
1753///
1754/// # Arguments
1755/// * `range` Constrains the number of iterations.
1756///   * A range without an upper bound `a..` allows the parser to run until it fails.
1757///   * A single `usize` value is equivalent to `value..=value`.
1758///   * An empty range is invalid.
1759/// * `parse` The parser to apply.
1760/// * `init` A function returning the initial value.
1761/// * `fold` The function that combines a result of `f` with
1762///       the current accumulator.
1763/// ```rust
1764/// # #[macro_use] extern crate nom;
1765/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};
1766/// use nom::multi::fold;
1767/// use nom::bytes::complete::tag;
1768///
1769/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
1770///   fold(
1771///     0..=2,
1772///     tag("abc"),
1773///     Vec::new,
1774///     |mut acc: Vec<_>, item| {
1775///       acc.push(item);
1776///       acc
1777///     }
1778///   ).parse(s)
1779/// }
1780///
1781/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
1782/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
1783/// assert_eq!(parser("123123"), Ok(("123123", vec![])));
1784/// assert_eq!(parser(""), Ok(("", vec![])));
1785/// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
1786/// ```
1787pub fn fold<I, E, F, G, H, J, R>(
1788  range: J,
1789  parser: F,
1790  init: H,
1791  fold: G,
1792) -> impl Parser<I, Output = R, Error = E>
1793where
1794  I: Clone + Input,
1795  F: Parser<I, Error = E>,
1796  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1797  H: FnMut() -> R,
1798  E: ParseError<I>,
1799  J: NomRange<usize>,
1800{
1801  Fold {
1802    parser,
1803    init,
1804    fold,
1805    range,
1806  }
1807}
1808
1809/// Parser implementation for the [fold] combinator
1810pub struct Fold<F, G, H, Range> {
1811  parser: F,
1812  init: H,
1813  fold: G,
1814  range: Range,
1815}
1816
1817impl<I, F, G, H, Range, Res> Parser<I> for Fold<F, G, H, Range>
1818where
1819  I: Clone + Input,
1820  F: Parser<I>,
1821  G: FnMut(Res, <F as Parser<I>>::Output) -> Res,
1822  H: FnMut() -> Res,
1823  Range: NomRange<usize>,
1824{
1825  type Output = Res;
1826  type Error = <F as Parser<I>>::Error;
1827
1828  fn process<OM: OutputMode>(
1829    &mut self,
1830    mut input: I,
1831  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1832    if self.range.is_inverted() {
1833      return Err(Err::Failure(<F as Parser<I>>::Error::from_error_kind(
1834        input,
1835        ErrorKind::Fold,
1836      )));
1837    }
1838
1839    let mut acc = OM::Output::bind(|| (self.init)());
1840
1841    for count in self.range.saturating_iter() {
1842      let len = input.input_len();
1843      match self.parser.process::<OM>(input.clone()) {
1844        Ok((tail, value)) => {
1845          // infinite loop check: the parser must always consume
1846          if tail.input_len() == len {
1847            return Err(Err::Error(OM::Error::bind(|| {
1848              <F as Parser<I>>::Error::from_error_kind(tail, ErrorKind::Fold)
1849            })));
1850          }
1851
1852          acc = OM::Output::combine(acc, value, |acc, value| (self.fold)(acc, value));
1853          input = tail;
1854        }
1855        Err(Err::Error(err)) => {
1856          if !self.range.contains(&count) {
1857            return Err(Err::Error(OM::Error::map(err, |err| {
1858              <F as Parser<I>>::Error::append(input, ErrorKind::Fold, err)
1859            })));
1860          } else {
1861            break;
1862          }
1863        }
1864        Err(e) => return Err(e),
1865      }
1866    }
1867
1868    Ok((input, acc))
1869  }
1870}