Debian Codegraph @

.cargo/vendor/nom/src/internal.rs

raw
1 //! Basic types to build the parsers
2
3 use self::Needed::*;
4 use crate::error::{self, ErrorKind, FromExternalError, ParseError};
5 use crate::lib::std::fmt;
6 use core::marker::PhantomData;
7 use core::num::NonZeroUsize;
8
9 /// Holds the result of parsing functions
10 ///
11 /// It depends on the input type `I`, the output type `O`, and the error type `E`
12 /// (by default `(I, nom::ErrorKind)`)
13 ///
14 /// The `Ok` side is a pair containing the remainder of the input (the part of the data that
15 /// was not parsed) and the produced value. The `Err` side contains an instance of `nom::Err`.
16 ///
17 /// Outside of the parsing code, you can use the [Finish::finish] method to convert
18 /// it to a more common result type
19 pub type IResult<I, O, E = error::Error<I>> = Result<(I, O), Err<E>>;
20
21 /// Helper trait to convert a parser's result to a more manageable type
22 pub trait Finish<I, O, E> {
23 /// converts the parser's result to a type that is more consumable by error
24 /// management libraries. It keeps the same `Ok` branch, and merges `Err::Error`
25 /// and `Err::Failure` into the `Err` side.
26 ///
27 /// *warning*: if the result is `Err(Err::Incomplete(_))`, this method will panic.
28 /// - "complete" parsers: It will not be an issue, `Incomplete` is never used
29 /// - "streaming" parsers: `Incomplete` will be returned if there's not enough data
30 /// for the parser to decide, and you should gather more data before parsing again.
31 /// Once the parser returns either `Ok(_)`, `Err(Err::Error(_))` or `Err(Err::Failure(_))`,
32 /// you can get out of the parsing loop and call `finish()` on the parser's result
33 fn finish(self) -> Result<(I, O), E>;
34 }
35
36 impl<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 /// Contains information on needed data if a parser returned `Incomplete`
49 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
50 pub enum Needed {
51 /// Needs more data, but we do not know how much
52 Unknown,
53 /// Contains the required data size in bytes
54 Size(NonZeroUsize),
55 }
56
57 impl Needed {
58 /// Creates `Needed` instance, returns `Needed::Unknown` if the argument is zero
59 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 /// Indicates if we know how many bytes we need
67 pub fn is_known(&self) -> bool {
68 *self != Unknown
69 }
70
71 /// Maps a `Needed` to `Needed` by applying a function to a contained `Size` value.
72 #[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 /// The `Err` enum indicates the parser was not successful
82 ///
83 /// It has three cases:
84 ///
85 /// * `Incomplete` indicates that more data is needed to decide. The `Needed` enum
86 /// can contain how many additional bytes are necessary. If you are sure your parser
87 /// is working on full data, you can wrap your parser with the `complete` combinator
88 /// to transform that case in `Error`
89 /// * `Error` means some parser did not succeed, but another one might (as an example,
90 /// when testing different branches of an `alt` combinator)
91 /// * `Failure` indicates an unrecoverable error. For example, when a prefix has been
92 /// recognised and the next parser has been confirmed, if that parser fails, then the
93 /// entire process fails; there are no more parsers to try.
94 ///
95 /// Distinguishing `Failure` this from `Error` is only relevant inside the parser's code. For
96 /// external consumers, both mean that parsing failed.
97 ///
98 /// See also: [`Finish`].
99 ///
100 #[derive(Debug, Clone, PartialEq)]
101 pub enum Err<Failure, Error = Failure> {
102 /// There was not enough data
103 Incomplete(Needed),
104 /// The parser had an error (recoverable)
105 Error(Error),
106 /// The parser had an unrecoverable error: we got to the right
107 /// branch and we know other branches won't work, so backtrack
108 /// as fast as possible
109 Failure(Failure),
110 }
111
112 impl<E> Err<E> {
113 /// Tests if the result is Incomplete
114 pub fn is_incomplete(&self) -> bool {
115 matches!(self, Err::Incomplete(..))
116 }
117
118 /// Applies the given function to the inner error
119 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 /// Automatically converts between errors if the underlying type supports it
131 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
139 impl<T> Err<(T, ErrorKind)> {
140 /// Maps `Err<(T, ErrorKind)>` to `Err<(U, ErrorKind)>` with the given `F: T -> U`
141 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
153 impl<T> Err<error::Error<T>> {
154 /// Maps `Err<error::Error<T>>` to `Err<error::Error<U>>` with the given `F: T -> U`
155 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")]
174 use crate::lib::std::{borrow::ToOwned, string::String, vec::Vec};
175 #[cfg(feature = "alloc")]
176 impl Err<(&[u8], ErrorKind)> {
177 /// Obtaining ownership
178 #[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")]
185 impl Err<(&str, ErrorKind)> {
186 /// Obtaining ownership
187 #[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")]
194 impl Err<error::Error<&[u8]>> {
195 /// Obtaining ownership
196 #[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")]
203 impl Err<error::Error<&str>> {
204 /// Obtaining ownership
205 #[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
211 impl<E: Eq> Eq for Err<E> {}
212
213 impl<E> fmt::Display for Err<E>
214 where
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")]
228 use std::error::Error;
229
230 #[cfg(feature = "std")]
231 impl<E> Error for Err<E>
232 where
233 E: fmt::Debug,
234 {
235 fn source(&self) -> Option<&(dyn Error + 'static)> {
236 None // no underlying error
237 }
238 }
239
240 /// Parser mode: influences how combinators build values
241 ///
242 /// the [Parser] trait is generic over types implementing [Mode]. Its method are
243 /// called to produce and manipulate output values or errors.
244 ///
245 /// The main implementations of this trait are:
246 /// * [Emit]: produce a value
247 /// * [Check]: apply the parser but do not generate a value
248 pub trait Mode {
249 /// The output type that may be generated
250 type Output<T>;
251
252 /// Produces a value
253 fn bind<T, F: FnOnce() -> T>(f: F) -> Self::Output<T>;
254
255 /// Applies a function over the produced value
256 fn map<T, U, F: FnOnce(T) -> U>(x: Self::Output<T>, f: F) -> Self::Output<U>;
257
258 /// Combines two values generated by previous parsers
259 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
266 /// Produces a value. This is the default behaviour for parsers
267 pub struct Emit;
268 impl 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
291 /// Applies the parser, but do not a produce a value
292 ///
293 /// This has the effect of greatly reducing the amount of code generated and the
294 /// parser memory usage. Some combinators check for an error in a child parser but
295 /// discard the error, and for those, using [Check] makes sure the error is not
296 /// even generated, only the fact that an error happened remains
297 pub struct Check;
298 impl 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
316 /// Parser result type
317 ///
318 /// * `Ok` branch: a tuple of the remaining input data, and the output value.
319 /// The output value is of the `O` type if the output mode was [Emit], and `()`
320 /// if the mode was [Check]
321 /// * `Err` branch: an error of the `E` type if the erroor mode was [Emit], and `()`
322 /// if the mode was [Check]
323 pub 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
328 /// Trait Defining the parser's execution
329 ///
330 /// The same parser implementation can vary in behaviour according to the chosen
331 /// output mode
332 pub trait OutputMode {
333 /// Defines the [Mode] for the output type. [Emit] will generate the value, [Check] will
334 /// apply the parser but will only generate `()` if successful. This can be used when
335 /// verifying that the input data conforms to the format without having to generate any
336 /// output data
337 type Output: Mode;
338 /// Defines the [Mode] for the output type. [Emit] will generate the value, [Check] will
339 /// apply the parser but will only generate `()` if an error happened. [Emit] should be
340 /// used when we want to handle the error and extract useful information from it. [Check]
341 /// is used when we just want to know if parsing failed and reject the data quickly.
342 type Error: Mode;
343 /// Indicates whether the input data is "complete", ie we already have the entire data in the
344 /// buffer, or if it is "streaming", where more data can be added later in the buffer. In
345 /// streaming mode, the parser will understand that a failure may mean that we are missing
346 /// data, and will return a specific error branch, [Err::Incomplete] to signal it. In complete
347 /// mode, the parser will generate a normal error
348 type Incomplete: IsStreaming;
349 }
350
351 /// Specifies the behaviour when a parser encounters an error that could be due to partial ata
352 pub trait IsStreaming {
353 /// called by parsers on partial data errors
354 /// * `needed` can hold the amount of additional data the parser would need to decide
355 /// * `err_f`: produces the error when in "complete" mode
356 fn incomplete<E, F: FnOnce() -> E>(needed: Needed, err_f: F) -> Err<E>;
357 /// Indicates whether the data is in streaming mode or not
358 fn is_streaming() -> bool;
359 }
360
361 /// Indicates that the input data is streaming: more data may be available later
362 pub struct Streaming;
363
364 impl 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
375 /// Indicates that the input data is complete: no more data may be added later
376 pub struct Complete;
377
378 impl 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
389 /// Holds the parser execution modifiers: output [Mode], error [Mode] and
390 /// streaming behaviour for input data
391 pub struct OutputM<M: Mode, EM: Mode, S: IsStreaming> {
392 m: PhantomData<M>,
393 em: PhantomData<EM>,
394 s: PhantomData<S>,
395 }
396
397 impl<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 }
402 /// All nom parsers implement this trait
403 pub trait Parser<Input> {
404 /// Type of the produced value
405 type Output;
406 /// Error type of this parser
407 type Error: ParseError<Input>;
408
409 /// A parser takes in input type, and returns a `Result` containing
410 /// either the remaining input and the output value, or an error
411 #[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 /// A parser takes in input type, and returns a `Result` containing
417 /// either the remaining input and the output value, or an error
418 #[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 /// A parser takes in input type, and returns a `Result` containing
424 /// either the remaining input and the output value, or an error
425 fn process<OM: OutputMode>(
426 &mut self,
427 input: Input,
428 ) -> PResult<OM, Input, Self::Output, Self::Error>;
429
430 /// Maps a function over the result of a parser
431 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 /// Applies a function returning a `Result` over the result of a parser.
440 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 /// Applies a function returning an `Option` over the result of a parser.
450 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 /// Creates a second parser from the output of the first one, then apply over the rest of the input
459 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 /// Applies a second parser over the output of the first one
469 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 /// Applies a second parser after the first one, return their results as a tuple
478 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 /// Applies a second parser over the input if the first one failed
487 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 /// automatically converts the parser's output and error values to another type, as long as they
496 /// implement the `From` trait
497 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
509 impl<I, O, E: ParseError<I>, F> Parser<I> for F
510 where
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
526 macro_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 // FIXME: is there a way to avoid producing the output values?
541 $(let(i, $output) = $parser.process::<OutputM<Emit, OM::Error, OM::Incomplete>>(i)?;)+
542
543 // ???
544 Ok((i, OM::Output::bind(|| ($($output),+,))))
545 }
546 }
547 )
548 }
549
550 macro_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
563 impl_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
565 /*
566 #[cfg(feature = "alloc")]
567 use alloc::boxed::Box;
568
569 #[cfg(feature = "alloc")]
570 impl<I, O, E: ParseError<I>> Parser<I> for Box<dyn Parser<I, Output = O, Error = E>> {
571 type Output = O;
572 type Error = E;
573
574 fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> {
575 (**self).process(input)
576 }
577 }
578 */
579 /// Implementation of `Parser::map`
580 pub struct Map<F, G> {
581 f: F,
582 g: G,
583 }
584
585 impl<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
600 /// Implementation of `Parser::map_res`
601 pub struct MapRes<F, G> {
602 f: F,
603 g: G,
604 }
605
606 impl<I, O2, E2, F, G> Parser<I> for MapRes<F, G>
607 where
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
630 /// Implementation of `Parser::map_opt`
631 pub struct MapOpt<F, G> {
632 f: F,
633 g: G,
634 }
635
636 impl<I, O2, F, G> Parser<I> for MapOpt<F, G>
637 where
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
659 /// Implementation of `Parser::flat_map`
660 pub struct FlatMap<F, G> {
661 f: F,
662 g: G,
663 }
664
665 impl<
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
685 /// Implementation of `Parser::and_then`
686 pub struct AndThen<F, G> {
687 f: F,
688 g: G,
689 }
690
691 impl<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
707 /// Implementation of `Parser::and`
708 pub struct And<F, G> {
709 f: F,
710 g: G,
711 }
712
713 impl<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
728 /// Implementation of `Parser::or`
729 pub struct Or<F, G> {
730 f: F,
731 g: G,
732 }
733
734 impl<
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
756 /// Implementation of `Parser::into`
757 pub struct Into<F, O2, E2> {
758 f: F,
759 phantom_out2: core::marker::PhantomData<O2>,
760 phantom_err2: core::marker::PhantomData<E2>,
761 }
762
763 impl<
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
783 /// Alternate between two Parser implementations with the same result type.
784 pub(crate) enum Either<F, G> {
785 Left(F),
786 Right(G),
787 }
788
789 impl<
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)]
808 mod 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 //FIXME: since rust 1.65, this is now 32 bytes, likely thanks to https://github.com/rust-lang/rust/pull/94075
829 // deactivating that test for now because it'll have different values depending on the rust version
830 // assert_size!(IResult<&str, &str, u32>, 40);
831 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 }