1#[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#[cfg(feature = "alloc")]
34const MAX_INITIAL_CAPACITY_BYTES: usize = 65536;
35
36#[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")]
74pub 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          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#[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")]
161pub 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              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#[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")]
269pub 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              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#[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")]
375pub 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              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#[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")]
493pub 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              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#[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")]
609pub 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          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
677pub 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
711pub 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          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
757pub 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
792pub 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              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#[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")]
886pub 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
934pub 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
970pub 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
1009pub 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
1064pub 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          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
1112pub 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
1168pub 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              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
1227pub 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
1292pub 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          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
1354pub 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
1383pub 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  LengthValue {
1422    length: f,
1423    parser: g,
1424    e: PhantomData,
1425  }
1426}
1427
1428pub 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#[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")]
1516pub 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#[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
1683pub 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          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
1749pub 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
1809pub 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          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}