Coverage Report

Created: 2025-11-16 06:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nom/src/multi/mod.rs
Line
Count
Source
1
//! Combinators applying their child parser multiple times
2
3
#[cfg(test)]
4
mod tests;
5
6
use core::marker::PhantomData;
7
8
use crate::bytes::take;
9
use crate::error::ErrorKind;
10
use crate::error::ParseError;
11
use crate::internal::{Err, Needed, Parser};
12
use crate::lib::std::num::NonZeroUsize;
13
#[cfg(feature = "alloc")]
14
use crate::lib::std::vec::Vec;
15
use crate::traits::ToUsize;
16
use crate::Check;
17
use crate::Emit;
18
use crate::Input;
19
use crate::Mode;
20
use crate::NomRange;
21
use crate::OutputM;
22
use 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")]
34
const 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")))]
63
0
pub fn many0<I, F>(
64
0
  f: F,
65
0
) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = <F as Parser<I>>::Error>
66
0
where
67
0
  I: Clone + Input,
68
0
  F: Parser<I>,
69
{
70
0
  Many0 { parser: f }
71
0
}
72
73
#[cfg(feature = "alloc")]
74
/// Parser implementation for the [many0] combinator
75
pub struct Many0<F> {
76
  parser: F,
77
}
78
79
#[cfg(feature = "alloc")]
80
impl<I, F> Parser<I> for Many0<F>
81
where
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
0
  fn process<OM: OutputMode>(
89
0
    &mut self,
90
0
    mut i: I,
91
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
92
0
    let mut acc = OM::Output::bind(|| crate::lib::std::vec::Vec::with_capacity(4));
93
    loop {
94
0
      let len = i.input_len();
95
0
      match self
96
0
        .parser
97
0
        .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
98
      {
99
0
        Err(Err::Error(_)) => return Ok((i, acc)),
100
0
        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
101
0
        Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
102
0
        Ok((i1, o)) => {
103
          // infinite loop check: the parser must always consume
104
0
          if i1.input_len() == len {
105
0
            return Err(Err::Error(OM::Error::bind(|| {
106
0
              <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::Many0)
107
0
            })));
108
0
          }
109
110
0
          i = i1;
111
112
0
          acc = OM::Output::combine(acc, o, |mut acc, o| {
113
0
            acc.push(o);
114
0
            acc
115
0
          })
116
        }
117
      }
118
    }
119
0
  }
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")))]
150
0
pub fn many1<I, F>(
151
0
  parser: F,
152
0
) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = <F as Parser<I>>::Error>
153
0
where
154
0
  I: Clone + Input,
155
0
  F: Parser<I>,
156
{
157
0
  Many1 { parser }
158
0
}
159
160
#[cfg(feature = "alloc")]
161
/// Parser implementation for the [many1] combinator
162
pub struct Many1<F> {
163
  parser: F,
164
}
165
166
#[cfg(feature = "alloc")]
167
impl<I, F> Parser<I> for Many1<F>
168
where
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
0
  fn process<OM: OutputMode>(
176
0
    &mut self,
177
0
    mut i: I,
178
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
179
0
    match self
180
0
      .parser
181
0
      .process::<OutputM<OM::Output, Emit, OM::Incomplete>>(i.clone())
182
    {
183
0
      Err(Err::Error(err)) => Err(Err::Error(OM::Error::bind(|| {
184
0
        <F as Parser<I>>::Error::append(i, ErrorKind::Many1, err)
185
0
      }))),
186
0
      Err(Err::Failure(e)) => Err(Err::Failure(e)),
187
0
      Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),
188
0
      Ok((i1, o)) => {
189
0
        let mut acc = OM::Output::map(o, |o| {
190
0
          let mut acc = crate::lib::std::vec::Vec::with_capacity(4);
191
0
          acc.push(o);
192
0
          acc
193
0
        });
194
195
0
        i = i1;
196
197
        loop {
198
0
          let len = i.input_len();
199
0
          match self
200
0
            .parser
201
0
            .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
202
          {
203
0
            Err(Err::Error(_)) => return Ok((i, acc)),
204
0
            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
205
0
            Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
206
0
            Ok((i1, o)) => {
207
              // infinite loop check: the parser must always consume
208
0
              if i1.input_len() == len {
209
0
                return Err(Err::Error(OM::Error::bind(|| {
210
0
                  <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::Many0)
211
0
                })));
212
0
              }
213
214
0
              i = i1;
215
216
0
              acc = OM::Output::combine(acc, o, |mut acc, o| {
217
0
                acc.push(o);
218
0
                acc
219
0
              })
220
            }
221
          }
222
        }
223
      }
224
    }
225
0
  }
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")))]
251
0
pub fn many_till<I, E, F, G>(
252
0
  f: F,
253
0
  g: G,
254
0
) -> impl Parser<I, Output = (Vec<<F as Parser<I>>::Output>, <G as Parser<I>>::Output), Error = E>
255
0
where
256
0
  I: Clone + Input,
257
0
  F: Parser<I, Error = E>,
258
0
  G: Parser<I, Error = E>,
259
0
  E: ParseError<I>,
260
{
261
0
  ManyTill {
262
0
    f,
263
0
    g,
264
0
    e: PhantomData,
265
0
  }
266
0
}
267
268
#[cfg(feature = "alloc")]
269
/// Parser implementation for the [many_till] combinator
270
pub struct ManyTill<F, G, E> {
271
  f: F,
272
  g: G,
273
  e: PhantomData<E>,
274
}
275
276
#[cfg(feature = "alloc")]
277
impl<I, F, G, E> Parser<I> for ManyTill<F, G, E>
278
where
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
0
  fn process<OM: OutputMode>(
288
0
    &mut self,
289
0
    mut i: I,
290
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
291
0
    let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);
292
    loop {
293
0
      let len = i.input_len();
294
0
      match self
295
0
        .g
296
0
        .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
297
      {
298
0
        Ok((i1, o)) => return Ok((i1, OM::Output::combine(res, o, |res, o| (res, o)))),
299
0
        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
300
0
        Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),
301
        Err(Err::Error(_)) => {
302
0
          match self.f.process::<OM>(i.clone()) {
303
0
            Err(Err::Error(err)) => {
304
0
              return Err(Err::Error(OM::Error::map(err, |err| {
305
0
                E::append(i, ErrorKind::ManyTill, err)
306
0
              })))
307
            }
308
0
            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
309
0
            Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
310
0
            Ok((i1, o)) => {
311
              // infinite loop check: the parser must always consume
312
0
              if i1.input_len() == len {
313
0
                return Err(Err::Error(OM::Error::bind(|| {
314
0
                  E::from_error_kind(i, ErrorKind::Many0)
315
0
                })));
316
0
              }
317
318
0
              i = i1;
319
320
0
              res = OM::Output::combine(res, o, |mut acc, o| {
321
0
                acc.push(o);
322
0
                acc
323
0
              })
324
            }
325
          }
326
        }
327
      }
328
    }
329
0
  }
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")))]
358
0
pub fn separated_list0<I, E, F, G>(
359
0
  sep: G,
360
0
  f: F,
361
0
) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = E>
362
0
where
363
0
  I: Clone + Input,
364
0
  F: Parser<I, Error = E>,
365
0
  G: Parser<I, Error = E>,
366
0
  E: ParseError<I>,
367
{
368
0
  SeparatedList0 {
369
0
    parser: f,
370
0
    separator: sep,
371
0
  }
372
0
}
373
374
#[cfg(feature = "alloc")]
375
/// Parser implementation for the [separated_list0] combinator
376
pub struct SeparatedList0<F, G> {
377
  parser: F,
378
  separator: G,
379
}
380
381
#[cfg(feature = "alloc")]
382
impl<I, E: ParseError<I>, F, G> Parser<I> for SeparatedList0<F, G>
383
where
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
0
  fn process<OM: OutputMode>(
392
0
    &mut self,
393
0
    mut i: I,
394
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
395
0
    let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);
396
397
0
    match self
398
0
      .parser
399
0
      .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
400
    {
401
0
      Err(Err::Error(_)) => return Ok((i, res)),
402
0
      Err(Err::Failure(e)) => return Err(Err::Failure(e)),
403
0
      Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
404
0
      Ok((i1, o)) => {
405
0
        res = OM::Output::combine(res, o, |mut res, o| {
406
0
          res.push(o);
407
0
          res
408
0
        });
409
0
        i = i1;
410
      }
411
    }
412
413
    loop {
414
0
      let len = i.input_len();
415
0
      match self
416
0
        .separator
417
0
        .process::<OutputM<Check, Check, OM::Incomplete>>(i.clone())
418
      {
419
0
        Err(Err::Error(_)) => return Ok((i, res)),
420
0
        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
421
0
        Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
422
0
        Ok((i1, _)) => {
423
0
          match self
424
0
            .parser
425
0
            .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i1.clone())
426
          {
427
0
            Err(Err::Error(_)) => return Ok((i, res)),
428
0
            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
429
0
            Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
430
0
            Ok((i2, o)) => {
431
              // infinite loop check: the parser must always consume
432
0
              if i2.input_len() == len {
433
0
                return Err(Err::Error(OM::Error::bind(|| {
434
0
                  <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::SeparatedList)
435
0
                })));
436
0
              }
437
438
0
              res = OM::Output::combine(res, o, |mut res, o| {
439
0
                res.push(o);
440
0
                res
441
0
              });
442
443
0
              i = i2;
444
            }
445
          }
446
        }
447
      }
448
    }
449
0
  }
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")))]
479
0
pub fn separated_list1<I, E, F, G>(
480
0
  separator: G,
481
0
  parser: F,
482
0
) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = E>
483
0
where
484
0
  I: Clone + Input,
485
0
  F: Parser<I, Error = E>,
486
0
  G: Parser<I, Error = E>,
487
0
  E: ParseError<I>,
488
{
489
0
  SeparatedList1 { parser, separator }
490
0
}
491
492
#[cfg(feature = "alloc")]
493
/// Parser implementation for the [separated_list1] combinator
494
pub struct SeparatedList1<F, G> {
495
  parser: F,
496
  separator: G,
497
}
498
499
#[cfg(feature = "alloc")]
500
impl<I, E: ParseError<I>, F, G> Parser<I> for SeparatedList1<F, G>
501
where
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
0
  fn process<OM: OutputMode>(
510
0
    &mut self,
511
0
    mut i: I,
512
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
513
0
    let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);
514
515
0
    match self.parser.process::<OM>(i.clone()) {
516
0
      Err(e) => return Err(e),
517
0
      Ok((i1, o)) => {
518
0
        res = OM::Output::combine(res, o, |mut res, o| {
519
0
          res.push(o);
520
0
          res
521
0
        });
522
0
        i = i1;
523
      }
524
    }
525
526
    loop {
527
0
      let len = i.input_len();
528
0
      match self
529
0
        .separator
530
0
        .process::<OutputM<Check, Check, OM::Incomplete>>(i.clone())
531
      {
532
0
        Err(Err::Error(_)) => return Ok((i, res)),
533
0
        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
534
0
        Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
535
0
        Ok((i1, _)) => {
536
0
          match self
537
0
            .parser
538
0
            .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i1.clone())
539
          {
540
0
            Err(Err::Error(_)) => return Ok((i, res)),
541
0
            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
542
0
            Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
543
0
            Ok((i2, o)) => {
544
              // infinite loop check: the parser must always consume
545
0
              if i2.input_len() == len {
546
0
                return Err(Err::Error(OM::Error::bind(|| {
547
0
                  <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::SeparatedList)
548
0
                })));
549
0
              }
550
551
0
              res = OM::Output::combine(res, o, |mut res, o| {
552
0
                res.push(o);
553
0
                res
554
0
              });
555
0
              i = i2;
556
            }
557
          }
558
        }
559
      }
560
    }
561
0
  }
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")))]
595
0
pub fn many_m_n<I, E, F>(
596
0
  min: usize,
597
0
  max: usize,
598
0
  parser: F,
599
0
) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = E>
600
0
where
601
0
  I: Clone + Input,
602
0
  F: Parser<I, Error = E>,
603
0
  E: ParseError<I>,
604
{
605
0
  ManyMN { parser, min, max }
606
0
}
607
608
#[cfg(feature = "alloc")]
609
/// Parser implementation for the [many_m_n] combinator
610
pub struct ManyMN<F> {
611
  parser: F,
612
  min: usize,
613
  max: usize,
614
}
615
616
#[cfg(feature = "alloc")]
617
impl<I, F> Parser<I> for ManyMN<F>
618
where
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
0
  fn process<OM: OutputMode>(
626
0
    &mut self,
627
0
    mut input: I,
628
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
629
0
    if self.min > self.max {
630
0
      return Err(Err::Failure(<F as Parser<I>>::Error::from_error_kind(
631
0
        input,
632
0
        ErrorKind::ManyMN,
633
0
      )));
634
0
    }
635
636
0
    let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES
637
0
      / crate::lib::std::mem::size_of::<<F as Parser<I>>::Output>().max(1);
638
0
    let mut res = OM::Output::bind(|| {
639
0
      crate::lib::std::vec::Vec::with_capacity(self.min.min(max_initial_capacity))
640
0
    });
641
0
    for count in 0..self.max {
642
0
      let len = input.input_len();
643
0
      match self.parser.process::<OM>(input.clone()) {
644
0
        Ok((tail, value)) => {
645
          // infinite loop check: the parser must always consume
646
0
          if tail.input_len() == len {
647
0
            return Err(Err::Error(OM::Error::bind(|| {
648
0
              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::ManyMN)
649
0
            })));
650
0
          }
651
652
0
          res = OM::Output::combine(res, value, |mut res, value| {
653
0
            res.push(value);
654
0
            res
655
0
          });
656
0
          input = tail;
657
        }
658
0
        Err(Err::Error(e)) => {
659
0
          if count < self.min {
660
0
            return Err(Err::Error(OM::Error::map(e, |e| {
661
0
              <F as Parser<I>>::Error::append(input, ErrorKind::ManyMN, e)
662
0
            })));
663
          } else {
664
0
            return Ok((input, res));
665
          }
666
        }
667
0
        Err(e) => {
668
0
          return Err(e);
669
        }
670
      }
671
    }
672
673
0
    Ok((input, res))
674
0
  }
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
/// ```
702
0
pub fn many0_count<I, E, F>(parser: F) -> impl Parser<I, Output = usize, Error = E>
703
0
where
704
0
  I: Clone + Input,
705
0
  F: Parser<I, Error = E>,
706
0
  E: ParseError<I>,
707
{
708
0
  Many0Count { parser }
709
0
}
710
711
/// Parser implementation for the [many0_count] combinator
712
pub struct Many0Count<F> {
713
  parser: F,
714
}
715
716
impl<I, F> Parser<I> for Many0Count<F>
717
where
718
  I: Clone + Input,
719
  F: Parser<I>,
720
{
721
  type Output = usize;
722
  type Error = <F as Parser<I>>::Error;
723
724
0
  fn process<OM: OutputMode>(
725
0
    &mut self,
726
0
    mut input: I,
727
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
728
0
    let mut count = 0;
729
730
    loop {
731
0
      let input_ = input.clone();
732
0
      let len = input.input_len();
733
0
      match self
734
0
        .parser
735
0
        .process::<OutputM<Check, Check, OM::Incomplete>>(input_)
736
      {
737
0
        Ok((i, _)) => {
738
          // infinite loop check: the parser must always consume
739
0
          if i.input_len() == len {
740
0
            return Err(Err::Error(OM::Error::bind(|| {
741
0
              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many0Count)
742
0
            })));
743
0
          }
744
745
0
          input = i;
746
0
          count += 1;
747
        }
748
749
0
        Err(Err::Error(_)) => return Ok((input, OM::Output::bind(|| count))),
750
0
        Err(Err::Failure(e)) => return Err(Err::Failure(e)),
751
0
        Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),
752
      }
753
    }
754
0
  }
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
/// ```
783
0
pub fn many1_count<I, E, F>(parser: F) -> impl Parser<I, Output = usize, Error = E>
784
0
where
785
0
  I: Clone + Input,
786
0
  F: Parser<I, Error = E>,
787
0
  E: ParseError<I>,
788
{
789
0
  Many1Count { parser }
790
0
}
791
792
/// Parser implementation for the [many1_count] combinator
793
pub struct Many1Count<F> {
794
  parser: F,
795
}
796
797
impl<I, F> Parser<I> for Many1Count<F>
798
where
799
  I: Clone + Input,
800
  F: Parser<I>,
801
{
802
  type Output = usize;
803
  type Error = <F as Parser<I>>::Error;
804
805
0
  fn process<OM: OutputMode>(
806
0
    &mut self,
807
0
    input: I,
808
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
809
0
    let mut count = 0;
810
811
0
    match self
812
0
      .parser
813
0
      .process::<OutputM<Check, Check, OM::Incomplete>>(input.clone())
814
    {
815
0
      Err(Err::Error(_)) => Err(Err::Error(OM::Error::bind(move || {
816
0
        <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many1Count)
817
0
      }))),
818
0
      Err(Err::Failure(e)) => Err(Err::Failure(e)),
819
0
      Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),
820
0
      Ok((mut input, _)) => {
821
0
        count += 1;
822
823
        loop {
824
0
          let input_ = input.clone();
825
0
          let len = input.input_len();
826
0
          match self
827
0
            .parser
828
0
            .process::<OutputM<Check, Check, OM::Incomplete>>(input_)
829
          {
830
0
            Ok((i, _)) => {
831
              // infinite loop check: the parser must always consume
832
0
              if i.input_len() == len {
833
0
                return Err(Err::Error(OM::Error::bind(|| {
834
0
                  <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many1Count)
835
0
                })));
836
0
              }
837
838
0
              input = i;
839
0
              count += 1;
840
            }
841
842
0
            Err(Err::Error(_)) => return Ok((input, OM::Output::bind(|| count))),
843
0
            Err(Err::Failure(e)) => return Err(Err::Failure(e)),
844
0
            Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),
845
          }
846
        }
847
      }
848
    }
849
0
  }
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")))]
874
0
pub fn count<I, F>(
875
0
  parser: F,
876
0
  count: usize,
877
0
) -> impl Parser<I, Output = Vec<<F as Parser<I>>::Output>, Error = <F as Parser<I>>::Error>
878
0
where
879
0
  I: Clone,
880
0
  F: Parser<I>,
881
{
882
0
  Count { parser, count }
883
0
}
884
885
#[cfg(feature = "alloc")]
886
/// Parser implementation for the [count] combinator
887
pub struct Count<F> {
888
  parser: F,
889
  count: usize,
890
}
891
892
#[cfg(feature = "alloc")]
893
impl<I, F> Parser<I> for Count<F>
894
where
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
0
  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
902
0
    let mut input = i.clone();
903
0
    let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES
904
0
      / crate::lib::std::mem::size_of::<<F as Parser<I>>::Output>().max(1);
905
0
    let mut res = OM::Output::bind(|| {
906
0
      crate::lib::std::vec::Vec::with_capacity(self.count.min(max_initial_capacity))
907
0
    });
908
909
0
    for _ in 0..self.count {
910
0
      let input_ = input.clone();
911
0
      match self.parser.process::<OM>(input_) {
912
0
        Ok((i, o)) => {
913
0
          res = OM::Output::combine(res, o, |mut res, o| {
914
0
            res.push(o);
915
0
            res
916
0
          });
917
0
          input = i;
918
        }
919
0
        Err(Err::Error(e)) => {
920
0
          return Err(Err::Error(OM::Error::map(e, |e| {
921
0
            <F as Parser<I>>::Error::append(i, ErrorKind::Count, e)
922
0
          })));
923
        }
924
0
        Err(e) => {
925
0
          return Err(e);
926
        }
927
      }
928
    }
929
930
0
    Ok((input, res))
931
0
  }
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
/// ```
958
0
pub fn fill<'a, I, E, F>(
959
0
  parser: F,
960
0
  buf: &'a mut [<F as Parser<I>>::Output],
961
0
) -> impl Parser<I, Output = (), Error = E> + 'a
962
0
where
963
0
  I: Clone,
964
0
  F: Parser<I, Error = E> + 'a,
965
0
  E: ParseError<I>,
966
{
967
0
  Fill { parser, buf }
968
0
}
969
970
/// Parser implementation for the [fill] combinator
971
pub struct Fill<'a, F, O> {
972
  parser: F,
973
  buf: &'a mut [O],
974
}
975
976
impl<'a, I, F, O> Parser<I> for Fill<'a, F, O>
977
where
978
  I: Clone,
979
  F: Parser<I, Output = O>,
980
{
981
  type Output = ();
982
  type Error = <F as Parser<I>>::Error;
983
984
0
  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
985
0
    let mut input = i.clone();
986
987
0
    for elem in self.buf.iter_mut() {
988
0
      let input_ = input.clone();
989
0
      match self.parser.process::<OM>(input_) {
990
0
        Ok((i, o)) => {
991
0
          OM::Output::map(o, |o| *elem = o);
992
0
          input = i;
993
        }
994
0
        Err(Err::Error(e)) => {
995
0
          return Err(Err::Error(OM::Error::map(e, |e| {
996
0
            <F as Parser<I>>::Error::append(i, ErrorKind::Count, e)
997
0
          })));
998
        }
999
0
        Err(e) => {
1000
0
          return Err(e);
1001
        }
1002
      }
1003
    }
1004
1005
0
    Ok((input, OM::Output::bind(|| ())))
1006
0
  }
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
/// ```
1044
659
pub fn fold_many0<I, E, F, G, H, R>(
1045
659
  parser: F,
1046
659
  init: H,
1047
659
  g: G,
1048
659
) -> impl Parser<I, Output = R, Error = E>
1049
659
where
1050
659
  I: Clone + Input,
1051
659
  F: Parser<I, Error = E>,
1052
659
  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1053
659
  H: FnMut() -> R,
1054
659
  E: ParseError<I>,
1055
{
1056
659
  FoldMany0 {
1057
659
    parser,
1058
659
    g,
1059
659
    init,
1060
659
    r: PhantomData,
1061
659
  }
1062
659
}
nom::multi::fold_many0::<&str, nom::error::Error<&str>, nom::branch::Choice<(nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, fuzz_arithmetic::factor>, nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::combinator::Verify<fuzz_arithmetic::factor, fuzz_arithmetic::term::{closure#1}, i64>>)>, fuzz_arithmetic::term::{closure#3}, fuzz_arithmetic::term::{closure#2}, i64>
Line
Count
Source
1044
512
pub fn fold_many0<I, E, F, G, H, R>(
1045
512
  parser: F,
1046
512
  init: H,
1047
512
  g: G,
1048
512
) -> impl Parser<I, Output = R, Error = E>
1049
512
where
1050
512
  I: Clone + Input,
1051
512
  F: Parser<I, Error = E>,
1052
512
  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1053
512
  H: FnMut() -> R,
1054
512
  E: ParseError<I>,
1055
{
1056
512
  FoldMany0 {
1057
512
    parser,
1058
512
    g,
1059
512
    init,
1060
512
    r: PhantomData,
1061
512
  }
1062
512
}
nom::multi::fold_many0::<&str, nom::error::Error<&str>, nom::internal::And<nom::branch::Choice<(nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0})>, fuzz_arithmetic::term>, fuzz_arithmetic::expr::{closure#2}, fuzz_arithmetic::expr::{closure#1}, i64>
Line
Count
Source
1044
147
pub fn fold_many0<I, E, F, G, H, R>(
1045
147
  parser: F,
1046
147
  init: H,
1047
147
  g: G,
1048
147
) -> impl Parser<I, Output = R, Error = E>
1049
147
where
1050
147
  I: Clone + Input,
1051
147
  F: Parser<I, Error = E>,
1052
147
  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1053
147
  H: FnMut() -> R,
1054
147
  E: ParseError<I>,
1055
{
1056
147
  FoldMany0 {
1057
147
    parser,
1058
147
    g,
1059
147
    init,
1060
147
    r: PhantomData,
1061
147
  }
1062
147
}
Unexecuted instantiation: nom::multi::fold_many0::<_, _, _, _, _, _>
1063
1064
/// Parser implementation for the [fold_many0] combinator
1065
pub struct FoldMany0<F, G, Init, R> {
1066
  parser: F,
1067
  g: G,
1068
  init: Init,
1069
  r: PhantomData<R>,
1070
}
1071
1072
impl<I, F, G, Init, R> Parser<I> for FoldMany0<F, G, Init, R>
1073
where
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
659
  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1083
659
    let mut res = OM::Output::bind(|| (self.init)());
<nom::multi::FoldMany0<nom::branch::Choice<(nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, fuzz_arithmetic::factor>, nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::combinator::Verify<fuzz_arithmetic::factor, fuzz_arithmetic::term::{closure#1}, i64>>)>, fuzz_arithmetic::term::{closure#3}, fuzz_arithmetic::term::{closure#2}, i64> as nom::internal::Parser<&str>>::process::<nom::internal::OutputM<nom::internal::Emit, nom::internal::Emit, nom::internal::Streaming>>::{closure#0}
Line
Count
Source
1083
512
    let mut res = OM::Output::bind(|| (self.init)());
<nom::multi::FoldMany0<nom::internal::And<nom::branch::Choice<(nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0})>, fuzz_arithmetic::term>, fuzz_arithmetic::expr::{closure#2}, fuzz_arithmetic::expr::{closure#1}, i64> as nom::internal::Parser<&str>>::process::<nom::internal::OutputM<nom::internal::Emit, nom::internal::Emit, nom::internal::Streaming>>::{closure#0}
Line
Count
Source
1083
147
    let mut res = OM::Output::bind(|| (self.init)());
Unexecuted instantiation: <nom::multi::FoldMany0<_, _, _, _> as nom::internal::Parser<_>>::process::<_>::{closure#0}
1084
659
    let mut input = i;
1085
1086
    loop {
1087
1.12k
      let i_ = input.clone();
1088
1.12k
      let len = input.input_len();
1089
1.12k
      match self.parser.process::<OM>(i_) {
1090
465
        Ok((i, o)) => {
1091
          // infinite loop check: the parser must always consume
1092
465
          if i.input_len() == len {
1093
0
            return Err(Err::Error(OM::Error::bind(|| {
1094
0
              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many0)
1095
0
            })));
Unexecuted instantiation: <nom::multi::FoldMany0<nom::branch::Choice<(nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, fuzz_arithmetic::factor>, nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::combinator::Verify<fuzz_arithmetic::factor, fuzz_arithmetic::term::{closure#1}, i64>>)>, fuzz_arithmetic::term::{closure#3}, fuzz_arithmetic::term::{closure#2}, i64> as nom::internal::Parser<&str>>::process::<nom::internal::OutputM<nom::internal::Emit, nom::internal::Emit, nom::internal::Streaming>>::{closure#1}
Unexecuted instantiation: <nom::multi::FoldMany0<nom::internal::And<nom::branch::Choice<(nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0})>, fuzz_arithmetic::term>, fuzz_arithmetic::expr::{closure#2}, fuzz_arithmetic::expr::{closure#1}, i64> as nom::internal::Parser<&str>>::process::<nom::internal::OutputM<nom::internal::Emit, nom::internal::Emit, nom::internal::Streaming>>::{closure#1}
Unexecuted instantiation: <nom::multi::FoldMany0<_, _, _, _> as nom::internal::Parser<_>>::process::<_>::{closure#1}
1096
465
          }
1097
1098
465
          res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));
<nom::multi::FoldMany0<nom::branch::Choice<(nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, fuzz_arithmetic::factor>, nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::combinator::Verify<fuzz_arithmetic::factor, fuzz_arithmetic::term::{closure#1}, i64>>)>, fuzz_arithmetic::term::{closure#3}, fuzz_arithmetic::term::{closure#2}, i64> as nom::internal::Parser<&str>>::process::<nom::internal::OutputM<nom::internal::Emit, nom::internal::Emit, nom::internal::Streaming>>::{closure#2}
Line
Count
Source
1098
100
          res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));
<nom::multi::FoldMany0<nom::internal::And<nom::branch::Choice<(nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0})>, fuzz_arithmetic::term>, fuzz_arithmetic::expr::{closure#2}, fuzz_arithmetic::expr::{closure#1}, i64> as nom::internal::Parser<&str>>::process::<nom::internal::OutputM<nom::internal::Emit, nom::internal::Emit, nom::internal::Streaming>>::{closure#2}
Line
Count
Source
1098
365
          res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));
Unexecuted instantiation: <nom::multi::FoldMany0<_, _, _, _> as nom::internal::Parser<_>>::process::<_>::{closure#2}
1099
465
          input = i;
1100
        }
1101
        Err(Err::Error(_)) => {
1102
659
          return Ok((input, res));
1103
        }
1104
0
        Err(e) => {
1105
0
          return Err(e);
1106
        }
1107
      }
1108
    }
1109
659
  }
<nom::multi::FoldMany0<nom::branch::Choice<(nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, fuzz_arithmetic::factor>, nom::internal::And<nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::combinator::Verify<fuzz_arithmetic::factor, fuzz_arithmetic::term::{closure#1}, i64>>)>, fuzz_arithmetic::term::{closure#3}, fuzz_arithmetic::term::{closure#2}, i64> as nom::internal::Parser<&str>>::process::<nom::internal::OutputM<nom::internal::Emit, nom::internal::Emit, nom::internal::Streaming>>
Line
Count
Source
1082
512
  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1083
512
    let mut res = OM::Output::bind(|| (self.init)());
1084
512
    let mut input = i;
1085
1086
    loop {
1087
612
      let i_ = input.clone();
1088
612
      let len = input.input_len();
1089
612
      match self.parser.process::<OM>(i_) {
1090
100
        Ok((i, o)) => {
1091
          // infinite loop check: the parser must always consume
1092
100
          if i.input_len() == len {
1093
0
            return Err(Err::Error(OM::Error::bind(|| {
1094
              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many0)
1095
            })));
1096
100
          }
1097
1098
100
          res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));
1099
100
          input = i;
1100
        }
1101
        Err(Err::Error(_)) => {
1102
512
          return Ok((input, res));
1103
        }
1104
0
        Err(e) => {
1105
0
          return Err(e);
1106
        }
1107
      }
1108
    }
1109
512
  }
<nom::multi::FoldMany0<nom::internal::And<nom::branch::Choice<(nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0}, nom::character::complete::char<&str, nom::error::Error<&str>>::{closure#0})>, fuzz_arithmetic::term>, fuzz_arithmetic::expr::{closure#2}, fuzz_arithmetic::expr::{closure#1}, i64> as nom::internal::Parser<&str>>::process::<nom::internal::OutputM<nom::internal::Emit, nom::internal::Emit, nom::internal::Streaming>>
Line
Count
Source
1082
147
  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1083
147
    let mut res = OM::Output::bind(|| (self.init)());
1084
147
    let mut input = i;
1085
1086
    loop {
1087
512
      let i_ = input.clone();
1088
512
      let len = input.input_len();
1089
512
      match self.parser.process::<OM>(i_) {
1090
365
        Ok((i, o)) => {
1091
          // infinite loop check: the parser must always consume
1092
365
          if i.input_len() == len {
1093
0
            return Err(Err::Error(OM::Error::bind(|| {
1094
              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many0)
1095
            })));
1096
365
          }
1097
1098
365
          res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));
1099
365
          input = i;
1100
        }
1101
        Err(Err::Error(_)) => {
1102
147
          return Ok((input, res));
1103
        }
1104
0
        Err(e) => {
1105
0
          return Err(e);
1106
        }
1107
      }
1108
    }
1109
147
  }
Unexecuted instantiation: <nom::multi::FoldMany0<_, _, _, _> as nom::internal::Parser<_>>::process::<_>
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
/// ```
1148
0
pub fn fold_many1<I, E, F, G, H, R>(
1149
0
  parser: F,
1150
0
  init: H,
1151
0
  g: G,
1152
0
) -> impl Parser<I, Output = R, Error = E>
1153
0
where
1154
0
  I: Clone + Input,
1155
0
  F: Parser<I, Error = E>,
1156
0
  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1157
0
  H: FnMut() -> R,
1158
0
  E: ParseError<I>,
1159
{
1160
0
  FoldMany1 {
1161
0
    parser,
1162
0
    g,
1163
0
    init,
1164
0
    r: PhantomData,
1165
0
  }
1166
0
}
1167
1168
/// Parser implementation for the [fold_many1] combinator
1169
pub struct FoldMany1<F, G, Init, R> {
1170
  parser: F,
1171
  g: G,
1172
  init: Init,
1173
  r: PhantomData<R>,
1174
}
1175
1176
impl<I, F, G, Init, R> Parser<I> for FoldMany1<F, G, Init, R>
1177
where
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
0
  fn process<OM: OutputMode>(&mut self, i: I) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1187
0
    let mut res = OM::Output::bind(|| (self.init)());
1188
0
    let input = i.clone();
1189
1190
0
    match self.parser.process::<OM>(input) {
1191
0
      Err(Err::Error(_)) => Err(Err::Error(OM::Error::bind(|| {
1192
0
        <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::Many1)
1193
0
      }))),
1194
0
      Err(e) => Err(e),
1195
0
      Ok((i1, o1)) => {
1196
0
        res = OM::Output::combine(res, o1, |res, o| (self.g)(res, o));
1197
1198
0
        let mut input = i1;
1199
        loop {
1200
0
          let i_ = input.clone();
1201
0
          let len = input.input_len();
1202
0
          match self.parser.process::<OM>(i_) {
1203
0
            Ok((i, o)) => {
1204
              // infinite loop check: the parser must always consume
1205
0
              if i.input_len() == len {
1206
0
                return Err(Err::Error(OM::Error::bind(|| {
1207
0
                  <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many1)
1208
0
                })));
1209
0
              }
1210
1211
0
              res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));
1212
0
              input = i;
1213
            }
1214
            Err(Err::Error(_)) => {
1215
0
              return Ok((input, res));
1216
            }
1217
0
            Err(e) => {
1218
0
              return Err(e);
1219
            }
1220
          }
1221
        }
1222
      }
1223
    }
1224
0
  }
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
/// ```
1268
0
pub fn fold_many_m_n<I, E, F, G, H, R>(
1269
0
  min: usize,
1270
0
  max: usize,
1271
0
  parser: F,
1272
0
  init: H,
1273
0
  g: G,
1274
0
) -> impl Parser<I, Output = R, Error = E>
1275
0
where
1276
0
  I: Clone + Input,
1277
0
  F: Parser<I, Error = E>,
1278
0
  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1279
0
  H: FnMut() -> R,
1280
0
  E: ParseError<I>,
1281
{
1282
0
  FoldManyMN {
1283
0
    parser,
1284
0
    g,
1285
0
    init,
1286
0
    min,
1287
0
    max,
1288
0
    r: PhantomData,
1289
0
  }
1290
0
}
1291
1292
/// Parser implementation for the [fold_many_m_n] combinator
1293
pub 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
1302
impl<I, F, G, Init, R> Parser<I> for FoldManyMN<F, G, Init, R>
1303
where
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
0
  fn process<OM: OutputMode>(
1313
0
    &mut self,
1314
0
    mut input: I,
1315
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1316
0
    if self.min > self.max {
1317
0
      return Err(Err::Error(OM::Error::bind(|| {
1318
0
        <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::ManyMN)
1319
0
      })));
1320
0
    }
1321
1322
0
    let mut res = OM::Output::bind(|| (self.init)());
1323
0
    for count in 0..self.max {
1324
0
      let len = input.input_len();
1325
0
      match self.parser.process::<OM>(input.clone()) {
1326
0
        Ok((tail, value)) => {
1327
          // infinite loop check: the parser must always consume
1328
0
          if tail.input_len() == len {
1329
0
            return Err(Err::Error(OM::Error::bind(|| {
1330
0
              <F as Parser<I>>::Error::from_error_kind(tail, ErrorKind::ManyMN)
1331
0
            })));
1332
0
          }
1333
1334
0
          res = OM::Output::combine(res, value, |res, o| (self.g)(res, o));
1335
0
          input = tail;
1336
        }
1337
0
        Err(Err::Error(err)) => {
1338
0
          if count < self.min {
1339
0
            return Err(Err::Error(OM::Error::map(err, |err| {
1340
0
              <F as Parser<I>>::Error::append(input, ErrorKind::ManyMN, err)
1341
0
            })));
1342
          } else {
1343
0
            break;
1344
          }
1345
        }
1346
0
        Err(e) => return Err(e),
1347
      }
1348
    }
1349
1350
0
    Ok((input, res))
1351
0
  }
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
/// ```
1373
0
pub fn length_data<I, E, F>(f: F) -> impl Parser<I, Output = I, Error = E>
1374
0
where
1375
0
  I: Input,
1376
0
  <F as Parser<I>>::Output: ToUsize,
1377
0
  F: Parser<I, Error = E>,
1378
0
  E: ParseError<I>,
1379
{
1380
0
  f.flat_map(|size| take(size))
1381
0
}
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
/// ```
1405
0
pub fn length_value<I, E, F, G>(
1406
0
  f: F,
1407
0
  g: G,
1408
0
) -> impl Parser<I, Output = <G as Parser<I>>::Output, Error = E>
1409
0
where
1410
0
  I: Clone + Input,
1411
0
  <F as Parser<I>>::Output: ToUsize,
1412
0
  F: Parser<I, Error = E>,
1413
0
  G: Parser<I, Error = E>,
1414
0
  E: ParseError<I>,
1415
{
1416
  /*f.flat_map(|size| {
1417
    println!("got size: {size}");
1418
    take(size)
1419
  })
1420
  .and_then(g)*/
1421
0
  LengthValue {
1422
0
    length: f,
1423
0
    parser: g,
1424
0
    e: PhantomData,
1425
0
  }
1426
0
}
1427
1428
/// Parser implementation for the [length_value] combinator
1429
pub struct LengthValue<F, G, E> {
1430
  length: F,
1431
  parser: G,
1432
  e: PhantomData<E>,
1433
}
1434
1435
impl<I, F, G, E> Parser<I> for LengthValue<F, G, E>
1436
where
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
0
  fn process<OM: OutputMode>(
1447
0
    &mut self,
1448
0
    input: I,
1449
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1450
0
    let (i, length) = self
1451
0
      .length
1452
0
      .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(input)?;
1453
1454
0
    let length: usize = length.to_usize();
1455
1456
0
    if let Some(needed) = length
1457
0
      .checked_sub(i.input_len())
1458
0
      .and_then(NonZeroUsize::new)
1459
    {
1460
0
      Err(Err::Incomplete(Needed::Size(needed)))
1461
    } else {
1462
0
      let (rest, i) = i.take_split(length);
1463
0
      match self.parser.process::<OM>(i.clone()) {
1464
0
        Err(Err::Incomplete(_)) => Err(Err::Error(OM::Error::bind(|| {
1465
0
          E::from_error_kind(i, ErrorKind::Complete)
1466
0
        }))),
1467
0
        Err(e) => Err(e),
1468
0
        Ok((_, o)) => Ok((rest, o)),
1469
      }
1470
    }
1471
0
  }
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")]
1497
0
pub fn length_count<I, E, F, G>(
1498
0
  f: F,
1499
0
  g: G,
1500
0
) -> impl Parser<I, Output = Vec<<G as Parser<I>>::Output>, Error = E>
1501
0
where
1502
0
  I: Clone,
1503
0
  <F as Parser<I>>::Output: ToUsize,
1504
0
  F: Parser<I, Error = E>,
1505
0
  G: Parser<I, Error = E>,
1506
0
  E: ParseError<I>,
1507
{
1508
0
  LengthCount {
1509
0
    length: f,
1510
0
    parser: g,
1511
0
    e: PhantomData,
1512
0
  }
1513
0
}
1514
1515
#[cfg(feature = "alloc")]
1516
/// Parser implementation for the [length_count] combinator
1517
pub struct LengthCount<F, G, E> {
1518
  length: F,
1519
  parser: G,
1520
  e: PhantomData<E>,
1521
}
1522
1523
#[cfg(feature = "alloc")]
1524
impl<I, F, G, E> Parser<I> for LengthCount<F, G, E>
1525
where
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
0
  fn process<OM: OutputMode>(
1536
0
    &mut self,
1537
0
    input: I,
1538
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1539
0
    match self
1540
0
      .length
1541
0
      .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(input)
1542
    {
1543
0
      Err(e) => Err(e),
1544
0
      Ok((i, count)) => {
1545
0
        let count = count.to_usize();
1546
0
        let mut input = i.clone();
1547
0
        let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES
1548
0
          / crate::lib::std::mem::size_of::<<F as Parser<I>>::Output>().max(1);
1549
0
        let mut res = OM::Output::bind(|| {
1550
0
          crate::lib::std::vec::Vec::with_capacity(count.min(max_initial_capacity))
1551
0
        });
1552
1553
0
        for _ in 0..count {
1554
0
          let input_ = input.clone();
1555
0
          match self.parser.process::<OM>(input_) {
1556
0
            Ok((i, o)) => {
1557
0
              res = OM::Output::combine(res, o, |mut res, o| {
1558
0
                res.push(o);
1559
0
                res
1560
0
              });
1561
0
              input = i;
1562
            }
1563
0
            Err(Err::Error(e)) => {
1564
0
              return Err(Err::Error(OM::Error::map(e, |e| {
1565
0
                <F as Parser<I>>::Error::append(i, ErrorKind::Count, e)
1566
0
              })));
1567
            }
1568
0
            Err(e) => {
1569
0
              return Err(e);
1570
            }
1571
          }
1572
        }
1573
1574
0
        Ok((input, res))
1575
      }
1576
    }
1577
0
  }
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")))]
1665
0
pub fn many<I, E, Collection, F, G>(
1666
0
  range: G,
1667
0
  parser: F,
1668
0
) -> impl Parser<I, Output = Collection, Error = E>
1669
0
where
1670
0
  I: Clone + Input,
1671
0
  F: Parser<I, Error = E>,
1672
0
  Collection: Extend<<F as Parser<I>>::Output> + Default,
1673
0
  E: ParseError<I>,
1674
0
  G: NomRange<usize>,
1675
{
1676
0
  Many {
1677
0
    parser,
1678
0
    range,
1679
0
    c: PhantomData,
1680
0
  }
1681
0
}
1682
1683
/// Parser implementation for the [many] combinator
1684
pub struct Many<F, R, Collection> {
1685
  parser: F,
1686
  range: R,
1687
  c: PhantomData<Collection>,
1688
}
1689
1690
impl<I, F, R, Collection> Parser<I> for Many<F, R, Collection>
1691
where
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
0
  fn process<OM: OutputMode>(
1701
0
    &mut self,
1702
0
    mut input: I,
1703
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1704
0
    if self.range.is_inverted() {
1705
0
      return Err(Err::Failure(<F as Parser<I>>::Error::from_error_kind(
1706
0
        input,
1707
0
        ErrorKind::Many,
1708
0
      )));
1709
0
    }
1710
1711
0
    let mut res = OM::Output::bind(Collection::default);
1712
1713
0
    for count in self.range.bounded_iter() {
1714
0
      let len = input.input_len();
1715
0
      match self.parser.process::<OM>(input.clone()) {
1716
0
        Ok((tail, value)) => {
1717
          // infinite loop check: the parser must always consume
1718
0
          if tail.input_len() == len {
1719
0
            return Err(Err::Error(OM::Error::bind(|| {
1720
0
              <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Many)
1721
0
            })));
1722
0
          }
1723
1724
0
          res = OM::Output::combine(res, value, |mut res, value| {
1725
0
            res.extend(Some(value));
1726
0
            res
1727
0
          });
1728
0
          input = tail;
1729
        }
1730
0
        Err(Err::Error(e)) => {
1731
0
          if !self.range.contains(&count) {
1732
0
            return Err(Err::Error(OM::Error::map(e, |e| {
1733
0
              <F as Parser<I>>::Error::append(input, ErrorKind::Many, e)
1734
0
            })));
1735
          } else {
1736
0
            return Ok((input, res));
1737
          }
1738
        }
1739
0
        Err(e) => {
1740
0
          return Err(e);
1741
        }
1742
      }
1743
    }
1744
1745
0
    Ok((input, res))
1746
0
  }
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
/// ```
1787
0
pub fn fold<I, E, F, G, H, J, R>(
1788
0
  range: J,
1789
0
  parser: F,
1790
0
  init: H,
1791
0
  fold: G,
1792
0
) -> impl Parser<I, Output = R, Error = E>
1793
0
where
1794
0
  I: Clone + Input,
1795
0
  F: Parser<I, Error = E>,
1796
0
  G: FnMut(R, <F as Parser<I>>::Output) -> R,
1797
0
  H: FnMut() -> R,
1798
0
  E: ParseError<I>,
1799
0
  J: NomRange<usize>,
1800
{
1801
0
  Fold {
1802
0
    parser,
1803
0
    init,
1804
0
    fold,
1805
0
    range,
1806
0
  }
1807
0
}
1808
1809
/// Parser implementation for the [fold] combinator
1810
pub struct Fold<F, G, H, Range> {
1811
  parser: F,
1812
  init: H,
1813
  fold: G,
1814
  range: Range,
1815
}
1816
1817
impl<I, F, G, H, Range, Res> Parser<I> for Fold<F, G, H, Range>
1818
where
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
0
  fn process<OM: OutputMode>(
1829
0
    &mut self,
1830
0
    mut input: I,
1831
0
  ) -> crate::PResult<OM, I, Self::Output, Self::Error> {
1832
0
    if self.range.is_inverted() {
1833
0
      return Err(Err::Failure(<F as Parser<I>>::Error::from_error_kind(
1834
0
        input,
1835
0
        ErrorKind::Fold,
1836
0
      )));
1837
0
    }
1838
1839
0
    let mut acc = OM::Output::bind(|| (self.init)());
1840
1841
0
    for count in self.range.saturating_iter() {
1842
0
      let len = input.input_len();
1843
0
      match self.parser.process::<OM>(input.clone()) {
1844
0
        Ok((tail, value)) => {
1845
          // infinite loop check: the parser must always consume
1846
0
          if tail.input_len() == len {
1847
0
            return Err(Err::Error(OM::Error::bind(|| {
1848
0
              <F as Parser<I>>::Error::from_error_kind(tail, ErrorKind::Fold)
1849
0
            })));
1850
0
          }
1851
1852
0
          acc = OM::Output::combine(acc, value, |acc, value| (self.fold)(acc, value));
1853
0
          input = tail;
1854
        }
1855
0
        Err(Err::Error(err)) => {
1856
0
          if !self.range.contains(&count) {
1857
0
            return Err(Err::Error(OM::Error::map(err, |err| {
1858
0
              <F as Parser<I>>::Error::append(input, ErrorKind::Fold, err)
1859
0
            })));
1860
          } else {
1861
0
            break;
1862
          }
1863
        }
1864
0
        Err(e) => return Err(e),
1865
      }
1866
    }
1867
1868
0
    Ok((input, acc))
1869
0
  }
1870
}