1use self::Needed::*;
4use crate::error::{self, ErrorKind, FromExternalError, ParseError};
5use crate::lib::std::fmt;
6use core::marker::PhantomData;
7use core::num::NonZeroUsize;
8
9pub type IResult<I, O, E = error::Error<I>> = Result<(I, O), Err<E>>;
20
21pub trait Finish<I, O, E> {
23 fn finish(self) -> Result<(I, O), E>;
34}
35
36impl<I, O, E> Finish<I, O, E> for IResult<I, O, E> {
37 fn finish(self) -> Result<(I, O), E> {
38 match self {
39 Ok(res) => Ok(res),
40 Err(Err::Error(e)) | Err(Err::Failure(e)) => Err(e),
41 Err(Err::Incomplete(_)) => {
42 panic!("Cannot call `finish()` on `Err(Err::Incomplete(_))`: this result means that the parser does not have enough data to decide, you should gather more data and try to reapply the parser instead")
43 }
44 }
45 }
46}
47
48#[derive(Debug, PartialEq, Eq, Clone, Copy)]
50pub enum Needed {
51 Unknown,
53 Size(NonZeroUsize),
55}
56
57impl Needed {
58 pub fn new(s: usize) -> Self {
60 match NonZeroUsize::new(s) {
61 Some(sz) => Needed::Size(sz),
62 None => Needed::Unknown,
63 }
64 }
65
66 pub fn is_known(&self) -> bool {
68 *self != Unknown
69 }
70
71 #[inline]
73 pub fn map<F: Fn(NonZeroUsize) -> usize>(self, f: F) -> Needed {
74 match self {
75 Unknown => Unknown,
76 Size(n) => Needed::new(f(n)),
77 }
78 }
79}
80
81#[derive(Debug, Clone, PartialEq)]
101pub enum Err<Failure, Error = Failure> {
102 Incomplete(Needed),
104 Error(Error),
106 Failure(Failure),
110}
111
112impl<E> Err<E> {
113 pub fn is_incomplete(&self) -> bool {
115 matches!(self, Err::Incomplete(..))
116 }
117
118 pub fn map<E2, F>(self, f: F) -> Err<E2>
120 where
121 F: FnOnce(E) -> E2,
122 {
123 match self {
124 Err::Incomplete(n) => Err::Incomplete(n),
125 Err::Failure(t) => Err::Failure(f(t)),
126 Err::Error(t) => Err::Error(f(t)),
127 }
128 }
129
130 pub fn convert<F>(e: Err<F>) -> Self
132 where
133 E: From<F>,
134 {
135 e.map(crate::lib::std::convert::Into::into)
136 }
137}
138
139impl<T> Err<(T, ErrorKind)> {
140 pub fn map_input<U, F>(self, f: F) -> Err<(U, ErrorKind)>
142 where
143 F: FnOnce(T) -> U,
144 {
145 match self {
146 Err::Incomplete(n) => Err::Incomplete(n),
147 Err::Failure((input, k)) => Err::Failure((f(input), k)),
148 Err::Error((input, k)) => Err::Error((f(input), k)),
149 }
150 }
151}
152
153impl<T> Err<error::Error<T>> {
154 pub fn map_input<U, F>(self, f: F) -> Err<error::Error<U>>
156 where
157 F: FnOnce(T) -> U,
158 {
159 match self {
160 Err::Incomplete(n) => Err::Incomplete(n),
161 Err::Failure(error::Error { input, code }) => Err::Failure(error::Error {
162 input: f(input),
163 code,
164 }),
165 Err::Error(error::Error { input, code }) => Err::Error(error::Error {
166 input: f(input),
167 code,
168 }),
169 }
170 }
171}
172
173#[cfg(feature = "alloc")]
174use crate::lib::std::{borrow::ToOwned, string::String, vec::Vec};
175#[cfg(feature = "alloc")]
176impl Err<(&[u8], ErrorKind)> {
177 #[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
179 pub fn to_owned(self) -> Err<(Vec<u8>, ErrorKind)> {
180 self.map_input(ToOwned::to_owned)
181 }
182}
183
184#[cfg(feature = "alloc")]
185impl Err<(&str, ErrorKind)> {
186 #[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
188 pub fn to_owned(self) -> Err<(String, ErrorKind)> {
189 self.map_input(ToOwned::to_owned)
190 }
191}
192
193#[cfg(feature = "alloc")]
194impl Err<error::Error<&[u8]>> {
195 #[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
197 pub fn to_owned(self) -> Err<error::Error<Vec<u8>>> {
198 self.map_input(ToOwned::to_owned)
199 }
200}
201
202#[cfg(feature = "alloc")]
203impl Err<error::Error<&str>> {
204 #[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
206 pub fn to_owned(self) -> Err<error::Error<String>> {
207 self.map_input(ToOwned::to_owned)
208 }
209}
210
211impl<E: Eq> Eq for Err<E> {}
212
213impl<E> fmt::Display for Err<E>
214where
215 E: fmt::Debug,
216{
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 match self {
219 Err::Incomplete(Needed::Size(u)) => write!(f, "Parsing requires {} bytes/chars", u),
220 Err::Incomplete(Needed::Unknown) => write!(f, "Parsing requires more data"),
221 Err::Failure(c) => write!(f, "Parsing Failure: {:?}", c),
222 Err::Error(c) => write!(f, "Parsing Error: {:?}", c),
223 }
224 }
225}
226
227#[cfg(feature = "std")]
228use std::error::Error;
229
230#[cfg(feature = "std")]
231impl<E> Error for Err<E>
232where
233 E: fmt::Debug,
234{
235 fn source(&self) -> Option<&(dyn Error + 'static)> {
236 None }
238}
239
240pub trait Mode {
249 type Output<T>;
251
252 fn bind<T, F: FnOnce() -> T>(f: F) -> Self::Output<T>;
254
255 fn map<T, U, F: FnOnce(T) -> U>(x: Self::Output<T>, f: F) -> Self::Output<U>;
257
258 fn combine<T, U, V, F: FnOnce(T, U) -> V>(
260 x: Self::Output<T>,
261 y: Self::Output<U>,
262 f: F,
263 ) -> Self::Output<V>;
264}
265
266pub struct Emit;
268impl Mode for Emit {
269 type Output<T> = T;
270
271 #[inline(always)]
272 fn bind<T, F: FnOnce() -> T>(f: F) -> Self::Output<T> {
273 f()
274 }
275
276 #[inline(always)]
277 fn map<T, U, F: FnOnce(T) -> U>(x: Self::Output<T>, f: F) -> Self::Output<U> {
278 f(x)
279 }
280
281 #[inline(always)]
282 fn combine<T, U, V, F: FnOnce(T, U) -> V>(
283 x: Self::Output<T>,
284 y: Self::Output<U>,
285 f: F,
286 ) -> Self::Output<V> {
287 f(x, y)
288 }
289}
290
291pub struct Check;
298impl Mode for Check {
299 type Output<T> = ();
300
301 #[inline(always)]
302 fn bind<T, F: FnOnce() -> T>(_: F) -> Self::Output<T> {}
303
304 #[inline(always)]
305 fn map<T, U, F: FnOnce(T) -> U>(_: Self::Output<T>, _: F) -> Self::Output<U> {}
306
307 #[inline(always)]
308 fn combine<T, U, V, F: FnOnce(T, U) -> V>(
309 _: Self::Output<T>,
310 _: Self::Output<U>,
311 _: F,
312 ) -> Self::Output<V> {
313 }
314}
315
316pub type PResult<OM, I, O, E> = Result<
324 (I, <<OM as OutputMode>::Output as Mode>::Output<O>),
325 Err<E, <<OM as OutputMode>::Error as Mode>::Output<E>>,
326>;
327
328pub trait OutputMode {
333 type Output: Mode;
338 type Error: Mode;
343 type Incomplete: IsStreaming;
349}
350
351pub trait IsStreaming {
353 fn incomplete<E, F: FnOnce() -> E>(needed: Needed, err_f: F) -> Err<E>;
357 fn is_streaming() -> bool;
359}
360
361pub struct Streaming;
363
364impl IsStreaming for Streaming {
365 fn incomplete<E, F: FnOnce() -> E>(needed: Needed, _err_f: F) -> Err<E> {
366 Err::Incomplete(needed)
367 }
368
369 #[inline]
370 fn is_streaming() -> bool {
371 true
372 }
373}
374
375pub struct Complete;
377
378impl IsStreaming for Complete {
379 fn incomplete<E, F: FnOnce() -> E>(_needed: Needed, err_f: F) -> Err<E> {
380 Err::Error(err_f())
381 }
382
383 #[inline]
384 fn is_streaming() -> bool {
385 false
386 }
387}
388
389pub struct OutputM<M: Mode, EM: Mode, S: IsStreaming> {
392 m: PhantomData<M>,
393 em: PhantomData<EM>,
394 s: PhantomData<S>,
395}
396
397impl<M: Mode, EM: Mode, S: IsStreaming> OutputMode for OutputM<M, EM, S> {
398 type Output = M;
399 type Error = EM;
400 type Incomplete = S;
401}
402pub trait Parser<Input> {
404 type Output;
406 type Error: ParseError<Input>;
408
409 #[inline]
412 fn parse(&mut self, input: Input) -> IResult<Input, Self::Output, Self::Error> {
413 self.process::<OutputM<Emit, Emit, Streaming>>(input)
414 }
415
416 #[inline]
419 fn parse_complete(&mut self, input: Input) -> IResult<Input, Self::Output, Self::Error> {
420 self.process::<OutputM<Emit, Emit, Complete>>(input)
421 }
422
423 fn process<OM: OutputMode>(
426 &mut self,
427 input: Input,
428 ) -> PResult<OM, Input, Self::Output, Self::Error>;
429
430 fn map<G, O2>(self, g: G) -> Map<Self, G>
432 where
433 G: FnMut(Self::Output) -> O2,
434 Self: core::marker::Sized,
435 {
436 Map { f: self, g }
437 }
438
439 fn map_res<G, O2, E2>(self, g: G) -> MapRes<Self, G>
441 where
442 G: FnMut(Self::Output) -> Result<O2, E2>,
443 Self::Error: FromExternalError<Input, E2>,
444 Self: core::marker::Sized,
445 {
446 MapRes { f: self, g }
447 }
448
449 fn map_opt<G, O2>(self, g: G) -> MapOpt<Self, G>
451 where
452 G: FnMut(Self::Output) -> Option<O2>,
453 Self: core::marker::Sized,
454 {
455 MapOpt { f: self, g }
456 }
457
458 fn flat_map<G, H>(self, g: G) -> FlatMap<Self, G>
460 where
461 G: FnMut(Self::Output) -> H,
462 H: Parser<Input, Error = Self::Error>,
463 Self: core::marker::Sized,
464 {
465 FlatMap { f: self, g }
466 }
467
468 fn and_then<G>(self, g: G) -> AndThen<Self, G>
470 where
471 G: Parser<Self::Output, Error = Self::Error>,
472 Self: core::marker::Sized,
473 {
474 AndThen { f: self, g }
475 }
476
477 fn and<G, O2>(self, g: G) -> And<Self, G>
479 where
480 G: Parser<Input, Output = O2, Error = Self::Error>,
481 Self: core::marker::Sized,
482 {
483 And { f: self, g }
484 }
485
486 fn or<G>(self, g: G) -> Or<Self, G>
488 where
489 G: Parser<Input, Output = Self::Output, Error = Self::Error>,
490 Self: core::marker::Sized,
491 {
492 Or { f: self, g }
493 }
494
495 fn into<O2: From<Self::Output>, E2: From<Self::Error>>(self) -> Into<Self, O2, E2>
498 where
499 Self: core::marker::Sized,
500 {
501 Into {
502 f: self,
503 phantom_out2: core::marker::PhantomData,
504 phantom_err2: core::marker::PhantomData,
505 }
506 }
507}
508
509impl<I, O, E: ParseError<I>, F> Parser<I> for F
510where
511 F: FnMut(I) -> IResult<I, O, E>,
512{
513 type Output = O;
514 type Error = E;
515
516 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
517 let (i, o) = self(i).map_err(|e| match e {
518 Err::Incomplete(i) => Err::Incomplete(i),
519 Err::Error(e) => Err::Error(OM::Error::bind(|| e)),
520 Err::Failure(e) => Err::Failure(e),
521 })?;
522 Ok((i, OM::Output::bind(|| o)))
523 }
524}
525
526macro_rules! impl_parser_for_tuple {
527 ($($parser:ident $output:ident),+) => (
528 #[allow(non_snake_case)]
529 impl<I, $($output),+, E: ParseError<I>, $($parser),+> Parser<I> for ($($parser),+,)
530 where
531 $($parser: Parser<I, Output = $output, Error = E>),+
532 {
533 type Output = ($($output),+,);
534 type Error = E;
535
536 #[inline(always)]
537 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
538 let ($(ref mut $parser),+,) = *self;
539
540 $(let(i, $output) = $parser.process::<OutputM<Emit, OM::Error, OM::Incomplete>>(i)?;)+
542
543 Ok((i, OM::Output::bind(|| ($($output),+,))))
545 }
546 }
547 )
548}
549
550macro_rules! impl_parser_for_tuples {
551 ($parser1:ident $output1:ident, $($parser:ident $output:ident),+) => {
552 impl_parser_for_tuples!(__impl $parser1 $output1; $($parser $output),+);
553 };
554 (__impl $($parser:ident $output:ident),+; $parser1:ident $output1:ident $(,$parser2:ident $output2:ident)*) => {
555 impl_parser_for_tuple!($($parser $output),+);
556 impl_parser_for_tuples!(__impl $($parser $output),+, $parser1 $output1; $($parser2 $output2),*);
557 };
558 (__impl $($parser:ident $output:ident),+;) => {
559 impl_parser_for_tuple!($($parser $output),+);
560 }
561}
562
563impl_parser_for_tuples!(P1 O1, P2 O2, P3 O3, P4 O4, P5 O5, P6 O6, P7 O7, P8 O8, P9 O9, P10 O10, P11 O11, P12 O12, P13 O13, P14 O14, P15 O15, P16 O16, P17 O17, P18 O18, P19 O19, P20 O20, P21 O21);
564
565pub struct Map<F, G> {
581 f: F,
582 g: G,
583}
584
585impl<I, O2, E: ParseError<I>, F: Parser<I, Error = E>, G: FnMut(<F as Parser<I>>::Output) -> O2>
586 Parser<I> for Map<F, G>
587{
588 type Output = O2;
589 type Error = E;
590
591 #[inline(always)]
592 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
593 match self.f.process::<OM>(i) {
594 Err(e) => Err(e),
595 Ok((i, o)) => Ok((i, OM::Output::map(o, |o| (self.g)(o)))),
596 }
597 }
598}
599
600pub struct MapRes<F, G> {
602 f: F,
603 g: G,
604}
605
606impl<I, O2, E2, F, G> Parser<I> for MapRes<F, G>
607where
608 I: Clone,
609 <F as Parser<I>>::Error: FromExternalError<I, E2>,
610 F: Parser<I>,
611 G: FnMut(<F as Parser<I>>::Output) -> Result<O2, E2>,
612{
613 type Output = O2;
614 type Error = <F as Parser<I>>::Error;
615
616 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
617 let (input, o1) = self
618 .f
619 .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(i.clone())?;
620
621 match (self.g)(o1) {
622 Ok(o2) => Ok((input, OM::Output::bind(|| o2))),
623 Err(e) => Err(Err::Error(OM::Error::bind(|| {
624 <F as Parser<I>>::Error::from_external_error(i, ErrorKind::MapRes, e)
625 }))),
626 }
627 }
628}
629
630pub struct MapOpt<F, G> {
632 f: F,
633 g: G,
634}
635
636impl<I, O2, F, G> Parser<I> for MapOpt<F, G>
637where
638 I: Clone,
639 F: Parser<I>,
640 G: FnMut(<F as Parser<I>>::Output) -> Option<O2>,
641{
642 type Output = O2;
643 type Error = <F as Parser<I>>::Error;
644
645 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
646 let (input, o1) = self
647 .f
648 .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(i.clone())?;
649
650 match (self.g)(o1) {
651 Some(o2) => Ok((input, OM::Output::bind(|| o2))),
652 None => Err(Err::Error(OM::Error::bind(|| {
653 <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::MapOpt)
654 }))),
655 }
656 }
657}
658
659pub struct FlatMap<F, G> {
661 f: F,
662 g: G,
663}
664
665impl<
666 I,
667 E: ParseError<I>,
668 F: Parser<I, Error = E>,
669 G: FnMut(<F as Parser<I>>::Output) -> H,
670 H: Parser<I, Error = E>,
671 > Parser<I> for FlatMap<F, G>
672{
673 type Output = <H as Parser<I>>::Output;
674 type Error = E;
675
676 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
677 let (input, o1) = self
678 .f
679 .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(i)?;
680
681 (self.g)(o1).process::<OM>(input)
682 }
683}
684
685pub struct AndThen<F, G> {
687 f: F,
688 g: G,
689}
690
691impl<I, F: Parser<I>, G: Parser<<F as Parser<I>>::Output, Error = <F as Parser<I>>::Error>>
692 Parser<I> for AndThen<F, G>
693{
694 type Output = <G as Parser<<F as Parser<I>>::Output>>::Output;
695 type Error = <F as Parser<I>>::Error;
696
697 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
698 let (input, o1) = self
699 .f
700 .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(i)?;
701
702 let (_, o2) = self.g.process::<OM>(o1)?;
703 Ok((input, o2))
704 }
705}
706
707pub struct And<F, G> {
709 f: F,
710 g: G,
711}
712
713impl<I, E: ParseError<I>, F: Parser<I, Error = E>, G: Parser<I, Error = E>> Parser<I>
714 for And<F, G>
715{
716 type Output = (<F as Parser<I>>::Output, <G as Parser<I>>::Output);
717 type Error = E;
718
719 #[inline(always)]
720 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
721 let (i, o1) = self.f.process::<OM>(i)?;
722 let (i, o2) = self.g.process::<OM>(i)?;
723
724 Ok((i, OM::Output::combine(o1, o2, |o1, o2| (o1, o2))))
725 }
726}
727
728pub struct Or<F, G> {
730 f: F,
731 g: G,
732}
733
734impl<
735 I: Clone,
736 O,
737 E: ParseError<I>,
738 F: Parser<I, Output = O, Error = E>,
739 G: Parser<I, Output = O, Error = E>,
740 > Parser<I> for Or<F, G>
741{
742 type Output = <F as Parser<I>>::Output;
743 type Error = <F as Parser<I>>::Error;
744
745 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
746 match self.f.process::<OM>(i.clone()) {
747 Err(Err::Error(e1)) => match self.g.process::<OM>(i) {
748 Err(Err::Error(e2)) => Err(Err::Error(OM::Error::combine(e1, e2, |e1, e2| e1.or(e2)))),
749 res => res,
750 },
751 res => res,
752 }
753 }
754}
755
756pub struct Into<F, O2, E2> {
758 f: F,
759 phantom_out2: core::marker::PhantomData<O2>,
760 phantom_err2: core::marker::PhantomData<E2>,
761}
762
763impl<
764 I,
765 O2: From<<F as Parser<I>>::Output>,
766 E2: crate::error::ParseError<I> + From<<F as Parser<I>>::Error>,
767 F: Parser<I>,
768 > Parser<I> for Into<F, O2, E2>
769{
770 type Output = O2;
771 type Error = E2;
772
773 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
774 match self.f.process::<OM>(i) {
775 Ok((i, o)) => Ok((i, OM::Output::map(o, |o| o.into()))),
776 Err(Err::Error(e)) => Err(Err::Error(OM::Error::map(e, |e| e.into()))),
777 Err(Err::Failure(e)) => Err(Err::Failure(e.into())),
778 Err(Err::Incomplete(e)) => Err(Err::Incomplete(e)),
779 }
780 }
781}
782
783pub(crate) enum Either<F, G> {
785 Left(F),
786 Right(G),
787}
788
789impl<
790 I,
791 F: Parser<I>,
792 G: Parser<I, Output = <F as Parser<I>>::Output, Error = <F as Parser<I>>::Error>,
793 > Parser<I> for Either<F, G>
794{
795 type Output = <F as Parser<I>>::Output;
796 type Error = <F as Parser<I>>::Error;
797
798 #[inline]
799 fn process<OM: OutputMode>(&mut self, i: I) -> PResult<OM, I, Self::Output, Self::Error> {
800 match self {
801 Either::Left(f) => f.process::<OM>(i),
802 Either::Right(g) => g.process::<OM>(i),
803 }
804 }
805}
806
807#[cfg(test)]
808mod tests {
809 use super::*;
810 use crate::error::ErrorKind;
811
812 use crate::bytes::streaming::{tag, take};
813 use crate::number::streaming::be_u16;
814 use crate::sequence::terminated;
815
816 #[doc(hidden)]
817 #[macro_export]
818 macro_rules! assert_size (
819 ($t:ty, $sz:expr) => (
820 assert_eq!($crate::lib::std::mem::size_of::<$t>(), $sz);
821 );
822 );
823
824 #[test]
825 #[cfg(target_pointer_width = "64")]
826 fn size_test() {
827 assert_size!(IResult<&[u8], &[u8], (&[u8], u32)>, 40);
828 assert_size!(Needed, 8);
832 assert_size!(Err<u32>, 16);
833 assert_size!(ErrorKind, 1);
834 }
835
836 #[test]
837 fn err_map_test() {
838 let e = Err::Error(1);
839 assert_eq!(e.map(|v| v + 1), Err::Error(2));
840 }
841
842 #[test]
843 fn native_tuple_test() {
844 fn tuple_3(i: &[u8]) -> IResult<&[u8], (u16, &[u8])> {
845 terminated((be_u16, take(3u8)), tag("fg")).parse(i)
846 }
847
848 assert_eq!(
849 tuple_3(&b"abcdefgh"[..]),
850 Ok((&b"h"[..], (0x6162u16, &b"cde"[..])))
851 );
852 assert_eq!(tuple_3(&b"abcd"[..]), Err(Err::Incomplete(Needed::new(1))));
853 assert_eq!(tuple_3(&b"abcde"[..]), Err(Err::Incomplete(Needed::new(2))));
854 assert_eq!(
855 tuple_3(&b"abcdejk"[..]),
856 Err(Err::Error(error_position!(&b"jk"[..], ErrorKind::Tag)))
857 );
858 }
859}