nom8/combinator/
mod.rs

1//! # List of parsers and combinators
2//!
3//! **Note**: this list is meant to provide a nicer way to find a nom parser than reading through the documentation on docs.rs. Function combinators are organized in module so they are a bit easier to find.
4//!
5//! Links present in this document will nearly always point to `complete` version of the parser. Most of the parsers also have a `streaming` version.
6//!
7//! ## Basic elements
8//!
9//! Those are used to recognize the lowest level elements of your grammar, like, "here is a dot", or "here is an big endian integer".
10//!
11//! | combinator | usage | input | output | comment |
12//! |---|---|---|---|---|
13//! | [one_of][crate::bytes::one_of] | `one_of("abc")` |  `"abc"` | `Ok(("bc", 'a'))` |Matches one of the provided characters (works with non ASCII characters too)|
14//! | [none_of][crate::bytes::none_of] | `none_of("abc")` |  `"xyab"` | `Ok(("yab", 'x'))` |Matches anything but the provided characters|
15//! | [tag][crate::bytes::tag] | `tag("hello")` |  `"hello world"` | `Ok((" world", "hello"))` |Recognizes a specific suite of characters or bytes|
16//! | [tag_no_case][crate::bytes::tag_no_case] | `tag_no_case("hello")` |  `"HeLLo World"` | `Ok((" World", "HeLLo"))` |Case insensitive comparison. Note that case insensitive comparison is not well defined for unicode, and that you might have bad surprises|
17//! | [take][crate::bytes::take] | `take(4)` |  `"hello"` | `Ok(("o", "hell"))` |Takes a specific number of bytes or characters|
18//! | [take_while][crate::bytes::take_while] | `take_while(is_alphabetic)` |  `"abc123"` | `Ok(("123", "abc"))` |Returns the longest list of bytes for which the provided pattern matches. `take_while1` does the same, but must return at least one character|
19//! | [take_till][crate::bytes::take_till] | `take_till(is_alphabetic)` |  `"123abc"` | `Ok(("abc", "123"))` |Returns the longest list of bytes or characters until the provided pattern matches. `take_till1` does the same, but must return at least one character. This is the reverse behaviour from `take_while`: `take_till(f)` is equivalent to `take_while(\|c\| !f(c))`|
20//! | [take_until][crate::bytes::take_until] | `take_until("world")` |  `"Hello world"` | `Ok(("world", "Hello "))` |Returns the longest list of bytes or characters until the provided tag is found. `take_until1` does the same, but must return at least one character|
21//!
22//! ## Choice combinators
23//!
24//! | combinator | usage | input | output | comment |
25//! |---|---|---|---|---|
26//! | [alt][crate::branch::alt] | `alt((tag("ab"), tag("cd")))` |  `"cdef"` | `Ok(("ef", "cd"))` |Try a list of parsers and return the result of the first successful one|
27//! | [permutation][crate::branch::permutation] | `permutation(tag("ab"), tag("cd"), tag("12"))` | `"cd12abc"` | `Ok(("c", ("ab", "cd", "12"))` |Succeeds when all its child parser have succeeded, whatever the order|
28//!
29//! ## Sequence combinators
30//!
31//! | combinator | usage | input | output | comment |
32//! |---|---|---|---|---|
33//! | [delimited][crate::sequence::delimited] | `delimited(char('('), take(2), char(')'))` | `"(ab)cd"` | `Ok(("cd", "ab"))` ||
34//! | [preceded][crate::sequence::preceded] | `preceded(tag("ab"), tag("XY"))` | `"abXYZ"` | `Ok(("Z", "XY"))` ||
35//! | [terminated][crate::sequence::terminated] | `terminated(tag("ab"), tag("XY"))` | `"abXYZ"` | `Ok(("Z", "ab"))` ||
36//! | [pair][crate::sequence::pair] | `pair(tag("ab"), tag("XY"))` | `"abXYZ"` | `Ok(("Z", ("ab", "XY")))` ||
37//! | [separated_pair][crate::sequence::separated_pair] | `separated_pair(tag("hello"), char(','), tag("world"))` | `"hello,world!"` | `Ok(("!", ("hello", "world")))` ||
38//! | [`(...)` (tuples)][crate::Parser] | `(tag("ab"), tag("XY"), take(1))` | `"abXYZ!"` | `Ok(("!", ("ab", "XY", "Z")))` |Chains parsers and assemble the sub results in a tuple. You can use as many child parsers as you can put elements in a tuple|
39//!
40//! ## Applying a parser multiple times
41//!
42//! | combinator | usage | input | output | comment |
43//! |---|---|---|---|---|
44//! | [count][crate::multi::count] | `count(take(2), 3)` | `"abcdefgh"` | `Ok(("gh", vec!["ab", "cd", "ef"]))` |Applies the child parser a specified number of times|
45//! | [many0][crate::multi::many0] | `many0(tag("ab"))` |  `"abababc"` | `Ok(("c", vec!["ab", "ab", "ab"]))` |Applies the parser 0 or more times and returns the list of results in a Vec. `many1` does the same operation but must return at least one element|
46//! | [many_m_n][crate::multi::many_m_n] | `many_m_n(1, 3, tag("ab"))` | `"ababc"` | `Ok(("c", vec!["ab", "ab"]))` |Applies the parser between m and n times (n included) and returns the list of results in a Vec|
47//! | [many_till][crate::multi::many_till] | `many_till(tag( "ab" ), tag( "ef" ))` | `"ababefg"` | `Ok(("g", (vec!["ab", "ab"], "ef")))` |Applies the first parser until the second applies. Returns a tuple containing the list of results from the first in a Vec and the result of the second|
48//! | [separated_list0][crate::multi::separated_list0] | `separated_list0(tag(","), tag("ab"))` | `"ab,ab,ab."` | `Ok((".", vec!["ab", "ab", "ab"]))` |`separated_list1` works like `separated_list0` but must returns at least one element|
49//! | [fold_many0][crate::multi::fold_many0] | `fold_many0(be_u8, \|\| 0, \|acc, item\| acc + item)` | `[1, 2, 3]` | `Ok(([], 6))` |Applies the parser 0 or more times and folds the list of return values. The `fold_many1` version must apply the child parser at least one time|
50//! | [fold_many_m_n][crate::multi::fold_many_m_n] | `fold_many_m_n(1, 2, be_u8, \|\| 0, \|acc, item\| acc + item)` | `[1, 2, 3]` | `Ok(([3], 3))` |Applies the parser between m and n times (n included) and folds the list of return value|
51//! | [length_count][crate::multi::length_count] | `length_count(number, tag("ab"))` | `"2ababab"` | `Ok(("ab", vec!["ab", "ab"]))` |Gets a number from the first parser, then applies the second parser that many times|
52//!
53//! ## Integers
54//!
55//! Parsing integers from binary formats can be done in two ways: With parser functions, or combinators with configurable endianness.
56//!
57//! The following parsers could be found on [docs.rs number section][number/complete/index].
58//!
59//! - **configurable endianness:** [`i16`][crate::number::i16], [`i32`][crate::number::i32], [`i64`][crate::number::i64], [`u16`][crate::number::u16], [`u32`][crate::number::u32], [`u64`][crate::number::u64] are combinators that take as argument a [`nom8::number::Endianness`][number/enum.Endianness], like this: `i16(endianness)`. If the parameter is `nom8::number::Endianness::Big`, parse a big endian `i16` integer, otherwise a little endian `i16` integer.
60//! - **fixed endianness**: The functions are prefixed by `be_` for big endian numbers, and by `le_` for little endian numbers, and the suffix is the type they parse to. As an example, `be_u32` parses a big endian unsigned integer stored in 32 bits.
61//!   - [`be_f32`][crate::number::be_f32], [`be_f64`][crate::number::be_f64]: Big endian floating point numbers
62//!   - [`le_f32`][crate::number::le_f32], [`le_f64`][crate::number::le_f64]: Little endian floating point numbers
63//!   - [`be_i8`][crate::number::be_i8], [`be_i16`][crate::number::be_i16], [`be_i24`][crate::number::be_i24], [`be_i32`][crate::number::be_i32], [`be_i64`][crate::number::be_i64], [`be_i128`][crate::number::be_i128]: Big endian signed integers
64//!   - [`be_u8`][crate::number::be_u8], [`be_u16`][crate::number::be_u16], [`be_u24`][crate::number::be_u24], [`be_u32`][crate::number::be_u32], [`be_u64`][crate::number::be_u64], [`be_u128`][crate::number::be_u128]: Big endian unsigned integers
65//!   - [`le_i8`][crate::number::le_i8], [`le_i16`][crate::number::le_i16], [`le_i24`][crate::number::le_i24], [`le_i32`][crate::number::le_i32], [`le_i64`][crate::number::le_i64], [`le_i128`][crate::number::le_i128]: Little endian signed integers
66//!   - [`le_u8`][crate::number::le_u8], [`le_u16`][crate::number::le_u16], [`le_u24`][crate::number::le_u24], [`le_u32`][crate::number::le_u32], [`le_u64`][crate::number::le_u64], [`le_u128`][crate::number::le_u128]: Little endian unsigned integers
67//!
68//! ## Streaming related
69//!
70//! - [`eof`][eof]: Returns its input if it is at the end of input data
71//! - [`Parser::complete`][Parser::complete()]: Replaces an `Incomplete` returned by the child parser with an `Error`
72//!
73//! ## Modifiers
74//!
75//! - [`cond`][cond]: Conditional combinator. Wraps another parser and calls it if the condition is met
76//! - [`Parser::flat_map`][crate::Parser::flat_map]: method to map a new parser from the output of the first parser, then apply that parser over the rest of the input
77//! - [`Parser::value`][crate::Parser::value]: method to replace the result of a parser
78//! - [`Parser::map`][crate::Parser::map]: method to map a function on the result of a parser
79//! - [`Parser::and_then`][crate::Parser::and_then]: Applies a second parser over the output of the first one
80//! - [`Parser::map_opt`][Parser::map_opt]: Maps a function returning an `Option` on the output of a parser
81//! - [`Parser::map_res`][Parser::map_res]: Maps a function returning a `Result` on the output of a parser
82//! - [`not`][not]: Returns a result only if the embedded parser returns `Error` or `Incomplete`. Does not consume the input
83//! - [`opt`][opt]: Make the underlying parser optional
84//! - [`peek`][peek]: Returns a result without consuming the input
85//! - [`Parser::recognize`][Parser::recognize]: If the child parser was successful, return the consumed input as the produced value
86//! - [`Parser::with_recognized`][Parser::with_recognized]: If the child parser was successful, return a tuple of the consumed input and the produced output.
87//! - [`Parser::span`][Parser::span]: If the child parser was successful, return the location of the consumed input as the produced value
88//! - [`Parser::with_span`][Parser::with_span]: If the child parser was successful, return a tuple of the location of the consumed input and the produced output.
89//! - [`Parser::verify`]: Returns the result of the child parser if it satisfies a verification function
90//!
91//! ## Error management and debugging
92//!
93//! - [`Parser::context`]: Add context to the error if the parser fails
94//! - [`Parser::dbg_err`]: Prints a message and the input if the parser fails
95//!
96//! ## Text parsing
97//!
98//! - [`escaped`][crate::bytes::escaped]: Matches a byte string with escaped characters
99//! - [`escaped_transform`][crate::bytes::escaped_transform]: Matches a byte string with escaped characters, and returns a new string with the escaped characters replaced
100//!
101//! ## Binary format parsing
102//!
103//! - [`length_data`][crate::multi::length_data]: Gets a number from the first parser, then takes a subslice of the input of that size, and returns that subslice
104//! - [`length_value`][crate::multi::length_value]: Gets a number from the first parser, takes a subslice of the input of that size, then applies the second parser on that subslice. If the second parser returns `Incomplete`, `length_value` will return an error
105//!
106//! ## Bit stream parsing
107//!
108//! - [`bits`][crate::bits::bits]: Transforms the current input type (byte slice `&[u8]`) to a bit stream on which bit specific parsers and more general combinators can be applied
109//! - [`bytes`][crate::bits/::bytes]: Transforms its bits stream input back into a byte slice for the underlying parser
110//!
111//! ## Remaining combinators
112//!
113//! - [`success`][success]: Returns a value without consuming any input, always succeeds
114//! - [`fail`][fail]: Inversion of `success`. Always fails.
115//! - [`Parser::by_ref`]: Allow moving `&mut impl Parser` into other parsers
116//!
117//! ## Character test functions
118//!
119//! Use these functions with a combinator like `take_while`:
120//!
121//! - [`AsChar::is_alpha`][crate::input::AsChar::is_alpha]: Tests if byte is ASCII alphabetic: `[A-Za-z]`
122//! - [`AsChar::is_alphanum`][crate::input::AsChar::is_alphanum]: Tests if byte is ASCII alphanumeric: `[A-Za-z0-9]`
123//! - [`AsChar::is_dec_digit`][crate::input::AsChar::is_dec_digit]: Tests if byte is ASCII digit: `[0-9]`
124//! - [`AsChar::is_hex_digit`][crate::input::AsChar::is_hex_digit]: Tests if byte is ASCII hex digit: `[0-9A-Fa-f]`
125//! - [`AsChar::is_oct_digit`][crate::input::AsChar::is_oct_digit]: Tests if byte is ASCII octal digit: `[0-7]`
126//! - [`AsChar::is_space`][crate::input::AsChar::is_space]: Tests if byte is ASCII space or tab: `[ \t]`
127//! - [`AsChar::is_newline`][crate::input::AsChar::is_newline]: Tests if byte is ASCII newline: `[\n]`
128//!
129//! Alternatively there are ready to use functions:
130//!
131//! - [`alpha0`][crate::character::alpha0]: Recognizes zero or more lowercase and uppercase alphabetic characters: `[a-zA-Z]`. [`alpha1`][crate::character::alpha1] does the same but returns at least one character
132//! - [`alphanumeric0`][crate::character::alphanumeric0]: Recognizes zero or more numerical and alphabetic characters: `[0-9a-zA-Z]`. [`alphanumeric1`][crate::character::alphanumeric1] does the same but returns at least one character
133//! - [`any`][crate::bytes::any]: Matches one token
134//! - [`crlf`][crate::character::crlf]: Recognizes the string `\r\n`
135//! - [`digit0`][crate::character::digit0]: Recognizes zero or more numerical characters: `[0-9]`. [`digit1`][crate::character::digit1] does the same but returns at least one character
136//! - [`f64`][crate::character::f64]: Recognizes floating point number in a byte string and returns a `f64`
137//! - [`f32`][crate::character::f32]: Recognizes floating point number in a byte string and returns a `f32`
138//! - [`hex_digit0`][crate::character::hex_digit0]: Recognizes zero or more hexadecimal numerical characters: `[0-9A-Fa-f]`. [`hex_digit1`][crate::character::hex_digit1] does the same but returns at least one character
139//! - [`hex_u32`][crate::number::hex_u32]: Recognizes a hex-encoded integer
140//! - [`line_ending`][crate::character::line_ending]: Recognizes an end of line (both `\n` and `\r\n`)
141//! - [`multispace0`][crate::character::multispace0]: Recognizes zero or more spaces, tabs, carriage returns and line feeds. [`multispace1`][crate::character::multispace1] does the same but returns at least one character
142//! - [`newline`][crate::character::newline]: Matches a newline character `\n`
143//! - [`not_line_ending`][crate::character::not_line_ending]: Recognizes a string of any char except `\r` or `\n`
144//! - [`oct_digit0`][crate::character::oct_digit0]: Recognizes zero or more octal characters: `[0-7]`. [`oct_digit1`][crate::character::oct_digit1] does the same but returns at least one character
145//! - [`rest`][rest]: Return the remaining input
146//! - [`space0`][crate::character::space0]: Recognizes zero or more spaces and tabs. [`space1`][crate::character::space1] does the same but returns at least one character
147//! - [`tab`][crate::character::tab]: Matches a tab character `\t`
148
149#![allow(unused_imports)]
150
151#[cfg(feature = "alloc")]
152use crate::lib::std::boxed::Box;
153
154use crate::error::{ErrorKind, FromExternalError, ParseError};
155use crate::input::IntoOutput;
156use crate::input::{AsChar, InputIter, InputLength, InputTakeAtPosition, Location, ParseTo};
157use crate::input::{Compare, CompareResult, Offset, Slice};
158use crate::lib::std::borrow::Borrow;
159use crate::lib::std::convert;
160#[cfg(feature = "std")]
161use crate::lib::std::fmt::Debug;
162use crate::lib::std::mem::transmute;
163use crate::lib::std::ops::{Range, RangeFrom, RangeTo};
164use crate::IntoOutputIResult;
165use crate::*;
166
167#[cfg(test)]
168mod tests;
169
170/// Return the remaining input.
171///
172/// ```rust
173/// # use nom8::error::ErrorKind;
174/// use nom8::combinator::rest;
175/// assert_eq!(rest::<_,(_, ErrorKind)>("abc"), Ok(("", "abc")));
176/// assert_eq!(rest::<_,(_, ErrorKind)>(""), Ok(("", "")));
177/// ```
178#[inline]
179pub fn rest<T, E: ParseError<T>>(input: T) -> IResult<T, <T as IntoOutput>::Output, E>
180where
181  T: Slice<RangeFrom<usize>>,
182  T: InputLength,
183  T: IntoOutput,
184{
185  Ok((input.slice(input.input_len()..), input)).into_output()
186}
187
188/// Return the length of the remaining input.
189///
190/// ```rust
191/// # use nom8::error::ErrorKind;
192/// use nom8::combinator::rest_len;
193/// assert_eq!(rest_len::<_,(_, ErrorKind)>("abc"), Ok(("abc", 3)));
194/// assert_eq!(rest_len::<_,(_, ErrorKind)>(""), Ok(("", 0)));
195/// ```
196#[inline]
197pub fn rest_len<T, E: ParseError<T>>(input: T) -> IResult<T, usize, E>
198where
199  T: InputLength,
200{
201  let len = input.input_len();
202  Ok((input, len))
203}
204
205/// Implementation of [`Parser::by_ref`][Parser::by_ref]
206#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
207pub struct ByRef<'p, P> {
208  p: &'p mut P,
209}
210
211impl<'p, P> ByRef<'p, P> {
212  pub(crate) fn new(p: &'p mut P) -> Self {
213    Self { p }
214  }
215}
216
217impl<'p, I, O, E, P: Parser<I, O, E>> Parser<I, O, E> for ByRef<'p, P> {
218  fn parse(&mut self, i: I) -> IResult<I, O, E> {
219    self.p.parse(i)
220  }
221}
222
223/// Maps a function on the result of a parser.
224///
225/// **WARNING:** Deprecated, replaced with [`Parser::map`]
226///
227/// ```rust
228/// use nom8::{Err,error::ErrorKind, IResult,Parser};
229/// use nom8::character::digit1;
230/// use nom8::combinator::map;
231/// # fn main() {
232///
233/// let mut parser = map(digit1, |s: &str| s.len());
234///
235/// // the parser will count how many characters were returned by digit1
236/// assert_eq!(parser.parse("123456"), Ok(("", 6)));
237///
238/// // this will fail if digit1 fails
239/// assert_eq!(parser.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
240/// # }
241/// ```
242#[deprecated(since = "8.0.0", note = "Replaced with `Parser::map")]
243pub fn map<I, O1, O2, E, F, G>(mut parser: F, mut f: G) -> impl FnMut(I) -> IResult<I, O2, E>
244where
245  F: Parser<I, O1, E>,
246  G: FnMut(O1) -> O2,
247{
248  move |input: I| {
249    let (input, o1) = parser.parse(input)?;
250    Ok((input, f(o1)))
251  }
252}
253
254/// Implementation of [`Parser::map`]
255#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
256pub struct Map<F, G, O1> {
257  f: F,
258  g: G,
259  phantom: core::marker::PhantomData<O1>,
260}
261
262impl<F, G, O1> Map<F, G, O1> {
263  pub(crate) fn new(f: F, g: G) -> Self {
264    Self {
265      f,
266      g,
267      phantom: Default::default(),
268    }
269  }
270}
271
272impl<'a, I, O1, O2, E, F: Parser<I, O1, E>, G: Fn(O1) -> O2> Parser<I, O2, E> for Map<F, G, O1> {
273  fn parse(&mut self, i: I) -> IResult<I, O2, E> {
274    match self.f.parse(i) {
275      Err(e) => Err(e),
276      Ok((i, o)) => Ok((i, (self.g)(o))),
277    }
278  }
279}
280
281/// Applies a function returning a `Result` over the result of a parser.
282///
283/// **WARNING:** Deprecated, replaced with [`Parser::map_res`]
284///
285/// ```rust
286/// # use nom8::{Err,error::ErrorKind, IResult};
287/// use nom8::character::digit1;
288/// use nom8::combinator::map_res;
289/// # fn main() {
290///
291/// let mut parse = map_res(digit1, |s: &str| s.parse::<u8>());
292///
293/// // the parser will convert the result of digit1 to a number
294/// assert_eq!(parse("123"), Ok(("", 123)));
295///
296/// // this will fail if digit1 fails
297/// assert_eq!(parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
298///
299/// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
300/// assert_eq!(parse("123456"), Err(Err::Error(("123456", ErrorKind::MapRes))));
301/// # }
302/// ```
303#[deprecated(since = "8.0.0", note = "Replaced with `Parser::map_res")]
304pub fn map_res<I: Clone, O1, O2, E: FromExternalError<I, E2>, E2, F, G>(
305  mut parser: F,
306  mut f: G,
307) -> impl FnMut(I) -> IResult<I, O2, E>
308where
309  F: Parser<I, O1, E>,
310  G: FnMut(O1) -> Result<O2, E2>,
311{
312  move |input: I| {
313    let i = input.clone();
314    let (input, o1) = parser.parse(input)?;
315    match f(o1) {
316      Ok(o2) => Ok((input, o2)),
317      Err(e) => Err(Err::Error(E::from_external_error(i, ErrorKind::MapRes, e))),
318    }
319  }
320}
321
322/// Implementation of [`Parser::map_res`]
323#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
324pub struct MapRes<F, G, O1> {
325  f: F,
326  g: G,
327  phantom: core::marker::PhantomData<O1>,
328}
329
330impl<F, G, O1> MapRes<F, G, O1> {
331  pub(crate) fn new(f: F, g: G) -> Self {
332    Self {
333      f,
334      g,
335      phantom: Default::default(),
336    }
337  }
338}
339
340impl<I, O1, O2, E, E2, F, G> Parser<I, O2, E> for MapRes<F, G, O1>
341where
342  I: Clone,
343  F: Parser<I, O1, E>,
344  G: FnMut(O1) -> Result<O2, E2>,
345  E: FromExternalError<I, E2>,
346{
347  fn parse(&mut self, input: I) -> IResult<I, O2, E> {
348    let i = input.clone();
349    let (input, o1) = self.f.parse(input)?;
350    match (self.g)(o1) {
351      Ok(o2) => Ok((input, o2)),
352      Err(e) => Err(Err::Error(E::from_external_error(i, ErrorKind::MapRes, e))),
353    }
354  }
355}
356
357/// Applies a function returning an `Option` over the result of a parser.
358///
359/// **WARNING:** Deprecated, replaced with [`Parser::map_opt`]
360///
361/// ```rust
362/// # use nom8::{Err,error::ErrorKind, IResult};
363/// use nom8::character::digit1;
364/// use nom8::combinator::map_opt;
365/// # fn main() {
366///
367/// let mut parse = map_opt(digit1, |s: &str| s.parse::<u8>().ok());
368///
369/// // the parser will convert the result of digit1 to a number
370/// assert_eq!(parse("123"), Ok(("", 123)));
371///
372/// // this will fail if digit1 fails
373/// assert_eq!(parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
374///
375/// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
376/// assert_eq!(parse("123456"), Err(Err::Error(("123456", ErrorKind::MapOpt))));
377/// # }
378/// ```
379#[deprecated(since = "8.0.0", note = "Replaced with `Parser::map_res")]
380pub fn map_opt<I: Clone, O1, O2, E: ParseError<I>, F, G>(
381  mut parser: F,
382  mut f: G,
383) -> impl FnMut(I) -> IResult<I, O2, E>
384where
385  F: Parser<I, O1, E>,
386  G: FnMut(O1) -> Option<O2>,
387{
388  move |input: I| {
389    let i = input.clone();
390    let (input, o1) = parser.parse(input)?;
391    match f(o1) {
392      Some(o2) => Ok((input, o2)),
393      None => Err(Err::Error(E::from_error_kind(i, ErrorKind::MapOpt))),
394    }
395  }
396}
397
398/// Implementation of [`Parser::map_opt`]
399#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
400pub struct MapOpt<F, G, O1> {
401  f: F,
402  g: G,
403  phantom: core::marker::PhantomData<O1>,
404}
405
406impl<F, G, O1> MapOpt<F, G, O1> {
407  pub(crate) fn new(f: F, g: G) -> Self {
408    Self {
409      f,
410      g,
411      phantom: Default::default(),
412    }
413  }
414}
415
416impl<I, O1, O2, E, F, G> Parser<I, O2, E> for MapOpt<F, G, O1>
417where
418  I: Clone,
419  F: Parser<I, O1, E>,
420  G: FnMut(O1) -> Option<O2>,
421  E: ParseError<I>,
422{
423  fn parse(&mut self, input: I) -> IResult<I, O2, E> {
424    let i = input.clone();
425    let (input, o1) = self.f.parse(input)?;
426    match (self.g)(o1) {
427      Some(o2) => Ok((input, o2)),
428      None => Err(Err::Error(E::from_error_kind(i, ErrorKind::MapOpt))),
429    }
430  }
431}
432
433/// Applies a parser over the result of another one.
434///
435/// **WARNING:** Deprecated, replaced with [`Parser::and_then`]
436///
437/// ```rust
438/// # use nom8::{Err,error::ErrorKind, IResult};
439/// use nom8::character::digit1;
440/// use nom8::bytes::take;
441/// use nom8::combinator::map_parser;
442/// # fn main() {
443///
444/// let mut parse = map_parser(take(5u8), digit1);
445///
446/// assert_eq!(parse("12345"), Ok(("", "12345")));
447/// assert_eq!(parse("123ab"), Ok(("", "123")));
448/// assert_eq!(parse("123"), Err(Err::Error(("123", ErrorKind::Eof))));
449/// # }
450/// ```
451#[deprecated(since = "8.0.0", note = "Replaced with `Parser::and_then")]
452pub fn map_parser<I, O1, O2, E: ParseError<I>, F, G>(
453  mut parser: F,
454  mut applied_parser: G,
455) -> impl FnMut(I) -> IResult<I, O2, E>
456where
457  F: Parser<I, O1, E>,
458  G: Parser<O1, O2, E>,
459{
460  move |input: I| {
461    let (input, o1) = parser.parse(input)?;
462    let (_, o2) = applied_parser.parse(o1)?;
463    Ok((input, o2))
464  }
465}
466
467/// Implementation of [`Parser::and_then`]
468#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
469pub struct AndThen<F, G, O1> {
470  f: F,
471  g: G,
472  phantom: core::marker::PhantomData<O1>,
473}
474
475impl<F, G, O1> AndThen<F, G, O1> {
476  pub(crate) fn new(f: F, g: G) -> Self {
477    Self {
478      f,
479      g,
480      phantom: Default::default(),
481    }
482  }
483}
484
485impl<'a, I, O1, O2, E, F: Parser<I, O1, E>, G: Parser<O1, O2, E>> Parser<I, O2, E>
486  for AndThen<F, G, O1>
487{
488  fn parse(&mut self, i: I) -> IResult<I, O2, E> {
489    let (i, o1) = self.f.parse(i)?;
490    let (_, o2) = self.g.parse(o1)?;
491    Ok((i, o2))
492  }
493}
494
495/// Creates a new parser from the output of the first parser, then apply that parser over the rest of the input.
496///
497/// **WARNING:** Deprecated, replaced with [`Parser::flat_map`]
498///
499/// ```rust
500/// # use nom8::{Err,error::ErrorKind, IResult};
501/// use nom8::bytes::take;
502/// use nom8::number::u8;
503/// use nom8::combinator::flat_map;
504/// # fn main() {
505///
506/// let mut parse = flat_map(u8, take);
507///
508/// assert_eq!(parse(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..])));
509/// assert_eq!(parse(&[4, 0, 1, 2][..]), Err(Err::Error((&[0, 1, 2][..], ErrorKind::Eof))));
510/// # }
511/// ```
512#[deprecated(since = "8.0.0", note = "Replaced with `Parser::flat_map")]
513pub fn flat_map<I, O1, O2, E: ParseError<I>, F, G, H>(
514  mut parser: F,
515  mut applied_parser: G,
516) -> impl FnMut(I) -> IResult<I, O2, E>
517where
518  F: Parser<I, O1, E>,
519  G: FnMut(O1) -> H,
520  H: Parser<I, O2, E>,
521{
522  move |input: I| {
523    let (input, o1) = parser.parse(input)?;
524    applied_parser(o1).parse(input)
525  }
526}
527
528/// Implementation of [`Parser::flat_map`]
529#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
530pub struct FlatMap<F, G, O1> {
531  f: F,
532  g: G,
533  phantom: core::marker::PhantomData<O1>,
534}
535
536impl<F, G, O1> FlatMap<F, G, O1> {
537  pub(crate) fn new(f: F, g: G) -> Self {
538    Self {
539      f,
540      g,
541      phantom: Default::default(),
542    }
543  }
544}
545
546impl<'a, I, O1, O2, E, F: Parser<I, O1, E>, G: Fn(O1) -> H, H: Parser<I, O2, E>> Parser<I, O2, E>
547  for FlatMap<F, G, O1>
548{
549  fn parse(&mut self, i: I) -> IResult<I, O2, E> {
550    let (i, o1) = self.f.parse(i)?;
551    (self.g)(o1).parse(i)
552  }
553}
554
555/// Optional parser, will return `None` on [`Err::Error`].
556///
557/// To chain an error up, see [`cut`].
558///
559/// ```rust
560/// # use nom8::{Err,error::ErrorKind, IResult};
561/// use nom8::combinator::opt;
562/// use nom8::character::alpha1;
563/// # fn main() {
564///
565/// fn parser(i: &str) -> IResult<&str, Option<&str>> {
566///   opt(alpha1)(i)
567/// }
568///
569/// assert_eq!(parser("abcd;"), Ok((";", Some("abcd"))));
570/// assert_eq!(parser("123;"), Ok(("123;", None)));
571/// # }
572/// ```
573pub fn opt<I: Clone, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, Option<O>, E>
574where
575  F: Parser<I, O, E>,
576{
577  move |input: I| {
578    let i = input.clone();
579    match f.parse(input) {
580      Ok((i, o)) => Ok((i, Some(o))),
581      Err(Err::Error(_)) => Ok((i, None)),
582      Err(e) => Err(e),
583    }
584  }
585}
586
587/// Implementation of [`Parser::and`]
588#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
589pub struct And<F, G> {
590  f: F,
591  g: G,
592}
593
594impl<F, G> And<F, G> {
595  pub(crate) fn new(f: F, g: G) -> Self {
596    Self { f, g }
597  }
598}
599
600impl<'a, I, O1, O2, E, F: Parser<I, O1, E>, G: Parser<I, O2, E>> Parser<I, (O1, O2), E>
601  for And<F, G>
602{
603  fn parse(&mut self, i: I) -> IResult<I, (O1, O2), E> {
604    let (i, o1) = self.f.parse(i)?;
605    let (i, o2) = self.g.parse(i)?;
606    Ok((i, (o1, o2)))
607  }
608}
609
610/// Implementation of [`Parser::or`]
611#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
612pub struct Or<F, G> {
613  f: F,
614  g: G,
615}
616
617impl<F, G> Or<F, G> {
618  pub(crate) fn new(f: F, g: G) -> Self {
619    Self { f, g }
620  }
621}
622
623impl<'a, I: Clone, O, E: crate::error::ParseError<I>, F: Parser<I, O, E>, G: Parser<I, O, E>>
624  Parser<I, O, E> for Or<F, G>
625{
626  fn parse(&mut self, i: I) -> IResult<I, O, E> {
627    match self.f.parse(i.clone()) {
628      Err(Err::Error(e1)) => match self.g.parse(i) {
629        Err(Err::Error(e2)) => Err(Err::Error(e1.or(e2))),
630        res => res,
631      },
632      res => res,
633    }
634  }
635}
636
637/// Calls the parser if the condition is met.
638///
639/// ```rust
640/// # use nom8::{Err, error::{Error, ErrorKind}, IResult};
641/// use nom8::combinator::cond;
642/// use nom8::character::alpha1;
643/// # fn main() {
644///
645/// fn parser(b: bool, i: &str) -> IResult<&str, Option<&str>> {
646///   cond(b, alpha1)(i)
647/// }
648///
649/// assert_eq!(parser(true, "abcd;"), Ok((";", Some("abcd"))));
650/// assert_eq!(parser(false, "abcd;"), Ok(("abcd;", None)));
651/// assert_eq!(parser(true, "123;"), Err(Err::Error(Error::new("123;", ErrorKind::Alpha))));
652/// assert_eq!(parser(false, "123;"), Ok(("123;", None)));
653/// # }
654/// ```
655pub fn cond<I, O, E: ParseError<I>, F>(
656  b: bool,
657  mut f: F,
658) -> impl FnMut(I) -> IResult<I, Option<O>, E>
659where
660  F: Parser<I, O, E>,
661{
662  move |input: I| {
663    if b {
664      match f.parse(input) {
665        Ok((i, o)) => Ok((i, Some(o))),
666        Err(e) => Err(e),
667      }
668    } else {
669      Ok((input, None))
670    }
671  }
672}
673
674/// Tries to apply its parser without consuming the input.
675///
676/// ```rust
677/// # use nom8::{Err,error::ErrorKind, IResult};
678/// use nom8::combinator::peek;
679/// use nom8::character::alpha1;
680/// # fn main() {
681///
682/// let mut parser = peek(alpha1);
683///
684/// assert_eq!(parser("abcd;"), Ok(("abcd;", "abcd")));
685/// assert_eq!(parser("123;"), Err(Err::Error(("123;", ErrorKind::Alpha))));
686/// # }
687/// ```
688pub fn peek<I: Clone, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, O, E>
689where
690  F: Parser<I, O, E>,
691{
692  move |input: I| {
693    let i = input.clone();
694    match f.parse(input) {
695      Ok((_, o)) => Ok((i, o)),
696      Err(e) => Err(e),
697    }
698  }
699}
700
701/// returns its input if it is at the end of input data
702///
703/// When we're at the end of the data, this combinator
704/// will succeed
705///
706/// ```
707/// # use std::str;
708/// # use nom8::{Err, error::ErrorKind, IResult};
709/// # use nom8::combinator::eof;
710///
711/// # fn main() {
712/// let parser = eof;
713/// assert_eq!(parser("abc"), Err(Err::Error(("abc", ErrorKind::Eof))));
714/// assert_eq!(parser(""), Ok(("", "")));
715/// # }
716/// ```
717pub fn eof<I, E: ParseError<I>>(input: I) -> IResult<I, <I as IntoOutput>::Output, E>
718where
719  I: InputLength,
720  I: Clone,
721  I: IntoOutput,
722{
723  if input.input_len() == 0 {
724    let clone = input.clone();
725    Ok((input, clone)).into_output()
726  } else {
727    Err(Err::Error(E::from_error_kind(input, ErrorKind::Eof)))
728  }
729}
730
731/// Transforms Incomplete into `Error`.
732///
733/// **WARNING:** Deprecated, replaced with [`Parser::complete`]
734///
735/// ```rust
736/// # use nom8::{Err,error::ErrorKind, IResult, input::Streaming};
737/// use nom8::bytes::take;
738/// use nom8::combinator::complete;
739/// # fn main() {
740///
741/// let mut parser = complete(take(5u8));
742///
743/// assert_eq!(parser(Streaming("abcdefg")), Ok((Streaming("fg"), "abcde")));
744/// assert_eq!(parser(Streaming("abcd")), Err(Err::Error((Streaming("abcd"), ErrorKind::Complete))));
745/// # }
746/// ```
747#[deprecated(since = "8.0.0", note = "Replaced with `Parser::complete")]
748pub fn complete<I: Clone, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, O, E>
749where
750  F: Parser<I, O, E>,
751{
752  move |input: I| {
753    let i = input.clone();
754    match f.parse(input) {
755      Err(Err::Incomplete(_)) => Err(Err::Error(E::from_error_kind(i, ErrorKind::Complete))),
756      rest => rest,
757    }
758  }
759}
760
761/// Implementation of [`Parser::complete`]
762#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
763pub struct Complete<F> {
764  f: F,
765}
766
767impl<F> Complete<F> {
768  pub(crate) fn new(f: F) -> Self {
769    Self { f }
770  }
771}
772
773impl<F, I, O, E> Parser<I, O, E> for Complete<F>
774where
775  I: Clone,
776  F: Parser<I, O, E>,
777  E: ParseError<I>,
778{
779  fn parse(&mut self, input: I) -> IResult<I, O, E> {
780    let i = input.clone();
781    match (self.f).parse(input) {
782      Err(Err::Incomplete(_)) => Err(Err::Error(E::from_error_kind(i, ErrorKind::Complete))),
783      rest => rest,
784    }
785  }
786}
787
788/// Succeeds if all the input has been consumed by its child parser.
789///
790/// ```rust
791/// # use nom8::{Err,error::ErrorKind, IResult};
792/// use nom8::combinator::all_consuming;
793/// use nom8::character::alpha1;
794/// # fn main() {
795///
796/// let mut parser = all_consuming(alpha1);
797///
798/// assert_eq!(parser("abcd"), Ok(("", "abcd")));
799/// assert_eq!(parser("abcd;"),Err(Err::Error((";", ErrorKind::Eof))));
800/// assert_eq!(parser("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
801/// # }
802/// ```
803pub fn all_consuming<I, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, O, E>
804where
805  I: InputLength,
806  F: Parser<I, O, E>,
807{
808  move |input: I| {
809    let (input, res) = f.parse(input)?;
810    if input.input_len() == 0 {
811      Ok((input, res))
812    } else {
813      Err(Err::Error(E::from_error_kind(input, ErrorKind::Eof)))
814    }
815  }
816}
817
818/// Returns the result of the child parser if it satisfies a verification function.
819///
820/// The verification function takes as argument a reference to the output of the
821/// parser.
822///
823/// **WARNING:** Deprecated, replaced with [`Parser::map`]
824///
825/// ```rust
826/// # use nom8::{Err,error::ErrorKind, IResult};
827/// use nom8::combinator::verify;
828/// use nom8::character::alpha1;
829/// # fn main() {
830///
831/// let mut parser = verify(alpha1, |s: &str| s.len() == 4);
832///
833/// assert_eq!(parser("abcd"), Ok(("", "abcd")));
834/// assert_eq!(parser("abcde"), Err(Err::Error(("abcde", ErrorKind::Verify))));
835/// assert_eq!(parser("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
836/// # }
837/// ```
838#[deprecated(since = "8.0.0", note = "Replaced with `Parser::verify")]
839pub fn verify<I: Clone, O1, O2, E: ParseError<I>, F, G>(
840  mut first: F,
841  second: G,
842) -> impl FnMut(I) -> IResult<I, O1, E>
843where
844  F: Parser<I, O1, E>,
845  G: Fn(&O2) -> bool,
846  O1: Borrow<O2>,
847  O2: ?Sized,
848{
849  move |input: I| {
850    let i = input.clone();
851    let (input, o) = first.parse(input)?;
852
853    if second(o.borrow()) {
854      Ok((input, o))
855    } else {
856      Err(Err::Error(E::from_error_kind(i, ErrorKind::Verify)))
857    }
858  }
859}
860
861/// Implementation of [`Parser::verify`]
862#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
863pub struct Verify<F, G, O2: ?Sized> {
864  first: F,
865  second: G,
866  phantom: core::marker::PhantomData<O2>,
867}
868
869impl<F, G, O2: ?Sized> Verify<F, G, O2> {
870  pub(crate) fn new(first: F, second: G) -> Self {
871    Self {
872      first,
873      second,
874      phantom: Default::default(),
875    }
876  }
877}
878
879impl<I, O1, O2, E, F: Parser<I, O1, E>, G> Parser<I, O1, E> for Verify<F, G, O2>
880where
881  I: Clone,
882  E: ParseError<I>,
883  F: Parser<I, O1, E>,
884  G: Fn(&O2) -> bool,
885  O1: Borrow<O2>,
886  O2: ?Sized,
887{
888  fn parse(&mut self, input: I) -> IResult<I, O1, E> {
889    let i = input.clone();
890    let (input, o) = (self.first).parse(input)?;
891
892    if (self.second)(o.borrow()) {
893      Ok((input, o))
894    } else {
895      Err(Err::Error(E::from_error_kind(i, ErrorKind::Verify)))
896    }
897  }
898}
899
900/// Returns the provided value if the child parser succeeds.
901///
902/// **WARNING:** Deprecated, replaced with [`Parser::value`]
903///
904/// ```rust
905/// # use nom8::{Err,error::ErrorKind, IResult};
906/// use nom8::combinator::value;
907/// use nom8::character::alpha1;
908/// # fn main() {
909///
910/// let mut parser = value(1234, alpha1);
911///
912/// assert_eq!(parser("abcd"), Ok(("", 1234)));
913/// assert_eq!(parser("123abcd;"), Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
914/// # }
915/// ```
916#[deprecated(since = "8.0.0", note = "Replaced with `Parser::value")]
917pub fn value<I, O1: Clone, O2, E: ParseError<I>, F>(
918  val: O1,
919  mut parser: F,
920) -> impl FnMut(I) -> IResult<I, O1, E>
921where
922  F: Parser<I, O2, E>,
923{
924  move |input: I| parser.parse(input).map(|(i, _)| (i, val.clone()))
925}
926
927/// Implementation of [`Parser::value`]
928#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
929pub struct Value<F, O1, O2> {
930  parser: F,
931  val: O2,
932  phantom: core::marker::PhantomData<O1>,
933}
934
935impl<F, O1, O2> Value<F, O1, O2> {
936  pub(crate) fn new(parser: F, val: O2) -> Self {
937    Self {
938      parser,
939      val,
940      phantom: Default::default(),
941    }
942  }
943}
944
945impl<I, O1, O2: Clone, E: ParseError<I>, F: Parser<I, O1, E>> Parser<I, O2, E>
946  for Value<F, O1, O2>
947{
948  fn parse(&mut self, input: I) -> IResult<I, O2, E> {
949    (self.parser)
950      .parse(input)
951      .map(|(i, _)| (i, self.val.clone()))
952  }
953}
954
955/// Succeeds if the child parser returns an error.
956///
957/// ```rust
958/// # use nom8::{Err,error::ErrorKind, IResult};
959/// use nom8::combinator::not;
960/// use nom8::character::alpha1;
961/// # fn main() {
962///
963/// let mut parser = not(alpha1);
964///
965/// assert_eq!(parser("123"), Ok(("123", ())));
966/// assert_eq!(parser("abcd"), Err(Err::Error(("abcd", ErrorKind::Not))));
967/// # }
968/// ```
969pub fn not<I: Clone, O, E: ParseError<I>, F>(mut parser: F) -> impl FnMut(I) -> IResult<I, (), E>
970where
971  F: Parser<I, O, E>,
972{
973  move |input: I| {
974    let i = input.clone();
975    match parser.parse(input) {
976      Ok(_) => Err(Err::Error(E::from_error_kind(i, ErrorKind::Not))),
977      Err(Err::Error(_)) => Ok((i, ())),
978      Err(e) => Err(e),
979    }
980  }
981}
982
983/// If the child parser was successful, return the consumed input as produced value.
984///
985/// **WARNING:** Deprecated, replaced with [`Parser::recognize`]
986///
987/// ```rust
988/// # use nom8::{Err,error::ErrorKind, IResult};
989/// use nom8::combinator::recognize;
990/// use nom8::character::{alpha1};
991/// use nom8::sequence::separated_pair;
992/// # fn main() {
993///
994/// let mut parser = recognize(separated_pair(alpha1, ',', alpha1));
995///
996/// assert_eq!(parser("abcd,efgh"), Ok(("", "abcd,efgh")));
997/// assert_eq!(parser("abcd;"),Err(Err::Error((";", ErrorKind::OneOf))));
998/// # }
999/// ```
1000#[deprecated(since = "8.0.0", note = "Replaced with `Parser::recognize")]
1001pub fn recognize<I, O, E: ParseError<I>, F>(
1002  mut parser: F,
1003) -> impl FnMut(I) -> IResult<I, <I as IntoOutput>::Output, E>
1004where
1005  I: Clone,
1006  I: Offset,
1007  I: Slice<RangeTo<usize>>,
1008  I: IntoOutput,
1009  F: Parser<I, O, E>,
1010{
1011  move |input: I| {
1012    let i = input.clone();
1013    match parser.parse(i) {
1014      Ok((i, _)) => {
1015        let index = input.offset(&i);
1016        Ok((i, input.slice(..index))).into_output()
1017      }
1018      Err(e) => Err(e),
1019    }
1020  }
1021}
1022
1023/// Implementation of [`Parser::recognize`]
1024#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
1025pub struct Recognize<F, O> {
1026  parser: F,
1027  o: core::marker::PhantomData<O>,
1028}
1029
1030impl<F, O> Recognize<F, O> {
1031  pub(crate) fn new(parser: F) -> Self {
1032    Self {
1033      parser,
1034      o: Default::default(),
1035    }
1036  }
1037}
1038
1039impl<I, O, E, F> Parser<I, <I as IntoOutput>::Output, E> for Recognize<F, O>
1040where
1041  I: Clone,
1042  I: Offset,
1043  I: Slice<RangeTo<usize>>,
1044  I: IntoOutput,
1045  E: ParseError<I>,
1046  F: Parser<I, O, E>,
1047{
1048  fn parse(&mut self, input: I) -> IResult<I, <I as IntoOutput>::Output, E> {
1049    let i = input.clone();
1050    match (self.parser).parse(i) {
1051      Ok((i, _)) => {
1052        let index = input.offset(&i);
1053        Ok((i, input.slice(..index))).into_output()
1054      }
1055      Err(e) => Err(e),
1056    }
1057  }
1058}
1059
1060/// if the child parser was successful, return the consumed input with the output
1061/// as a tuple. Functions similarly to [recognize](fn.recognize.html) except it
1062/// returns the parser output as well.
1063///
1064/// This can be useful especially in cases where the output is not the same type
1065/// as the input, or the input is a user defined type.
1066///
1067/// Returned tuple is of the format `(consumed input, produced output)`.
1068///
1069/// **WARNING:** Deprecated, replaced with [`Parser::with_recognized`] (output ordering is changed)
1070///
1071/// ```rust
1072/// # use nom8::prelude::*;
1073/// # use nom8::{Err,error::ErrorKind, IResult};
1074/// use nom8::combinator::{consumed, value, recognize, map};
1075/// use nom8::character::{alpha1};
1076/// use nom8::bytes::tag;
1077/// use nom8::sequence::separated_pair;
1078///
1079/// fn inner_parser(input: &str) -> IResult<&str, bool> {
1080///     value(true, tag("1234"))(input)
1081/// }
1082///
1083/// # fn main() {
1084///
1085/// let mut consumed_parser = consumed(value(true, separated_pair(alpha1, ',', alpha1)));
1086///
1087/// assert_eq!(consumed_parser("abcd,efgh1"), Ok(("1", ("abcd,efgh", true))));
1088/// assert_eq!(consumed_parser("abcd;"),Err(Err::Error((";", ErrorKind::OneOf))));
1089///
1090///
1091/// // the first output (representing the consumed input)
1092/// // should be the same as that of the `recognize` parser.
1093/// let mut recognize_parser = recognize(inner_parser);
1094/// let mut consumed_parser = consumed(inner_parser).map(|(consumed, output)| consumed);
1095///
1096/// assert_eq!(recognize_parser("1234"), consumed_parser.parse("1234"));
1097/// assert_eq!(recognize_parser("abcd"), consumed_parser.parse("abcd"));
1098/// # }
1099/// ```
1100#[deprecated(
1101  since = "8.0.0",
1102  note = "Replaced with `Parser::with_recognized (output ordering is changed)"
1103)]
1104pub fn consumed<I, O, F, E>(
1105  mut parser: F,
1106) -> impl FnMut(I) -> IResult<I, (<I as IntoOutput>::Output, O), E>
1107where
1108  I: Clone + Offset + Slice<RangeTo<usize>>,
1109  I: IntoOutput,
1110  E: ParseError<I>,
1111  F: Parser<I, O, E>,
1112{
1113  move |input: I| {
1114    let i = input.clone();
1115    match parser.parse(i) {
1116      Ok((remaining, result)) => {
1117        let index = input.offset(&remaining);
1118        let consumed = input.slice(..index).into_output();
1119        Ok((remaining, (consumed, result)))
1120      }
1121      Err(e) => Err(e),
1122    }
1123  }
1124}
1125
1126/// Implementation of [`Parser::with_recognized`]
1127#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
1128pub struct WithRecognized<F, O> {
1129  parser: F,
1130  o: core::marker::PhantomData<O>,
1131}
1132
1133impl<F, O> WithRecognized<F, O> {
1134  pub(crate) fn new(parser: F) -> Self {
1135    Self {
1136      parser,
1137      o: Default::default(),
1138    }
1139  }
1140}
1141
1142impl<I, O, E, F> Parser<I, (O, <I as IntoOutput>::Output), E> for WithRecognized<F, O>
1143where
1144  I: Clone,
1145  I: Offset,
1146  I: Slice<RangeTo<usize>>,
1147  I: IntoOutput,
1148  E: ParseError<I>,
1149  F: Parser<I, O, E>,
1150{
1151  fn parse(&mut self, input: I) -> IResult<I, (O, <I as IntoOutput>::Output), E> {
1152    let i = input.clone();
1153    match (self.parser).parse(i) {
1154      Ok((remaining, result)) => {
1155        let index = input.offset(&remaining);
1156        let consumed = input.slice(..index).into_output();
1157        Ok((remaining, (result, consumed)))
1158      }
1159      Err(e) => Err(e),
1160    }
1161  }
1162}
1163
1164/// Implementation of [`Parser::span`]
1165#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
1166pub struct Span<F, O> {
1167  parser: F,
1168  o: core::marker::PhantomData<O>,
1169}
1170
1171impl<F, O> Span<F, O> {
1172  pub(crate) fn new(parser: F) -> Self {
1173    Self {
1174      parser,
1175      o: Default::default(),
1176    }
1177  }
1178}
1179
1180impl<I, O, E, F> Parser<I, Range<usize>, E> for Span<F, O>
1181where
1182  I: Clone + Location,
1183  E: ParseError<I>,
1184  F: Parser<I, O, E>,
1185{
1186  fn parse(&mut self, input: I) -> IResult<I, Range<usize>, E> {
1187    let start = input.location();
1188    self.parser.parse(input).map(move |(remaining, _)| {
1189      let end = remaining.location();
1190      (remaining, (start..end))
1191    })
1192  }
1193}
1194
1195/// Implementation of [`Parser::with_span`]
1196#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
1197pub struct WithSpan<F, O> {
1198  parser: F,
1199  o: core::marker::PhantomData<O>,
1200}
1201
1202impl<F, O> WithSpan<F, O> {
1203  pub(crate) fn new(parser: F) -> Self {
1204    Self {
1205      parser,
1206      o: Default::default(),
1207    }
1208  }
1209}
1210
1211impl<I, O, E, F> Parser<I, (O, Range<usize>), E> for WithSpan<F, O>
1212where
1213  I: Clone + Location,
1214  E: ParseError<I>,
1215  F: Parser<I, O, E>,
1216{
1217  fn parse(&mut self, input: I) -> IResult<I, (O, Range<usize>), E> {
1218    let start = input.location();
1219    self.parser.parse(input).map(move |(remaining, output)| {
1220      let end = remaining.location();
1221      (remaining, (output, (start..end)))
1222    })
1223  }
1224}
1225
1226/// Transforms an [`Err::Error`] (recoverable) to [`Err::Failure`] (unrecoverable)
1227///
1228/// This commits the parse result, preventing alternative branch paths like with
1229/// [`nom8::branch::alt`][crate::branch::alt].
1230///
1231/// # Example
1232///
1233/// Without `cut`:
1234/// ```rust
1235/// # use nom8::{Err,error::ErrorKind, IResult};
1236/// # use nom8::bytes::one_of;
1237/// # use nom8::character::digit1;
1238/// # use nom8::combinator::rest;
1239/// # use nom8::branch::alt;
1240/// # use nom8::sequence::preceded;
1241/// # fn main() {
1242///
1243/// fn parser(input: &str) -> IResult<&str, &str> {
1244///   alt((
1245///     preceded(one_of("+-"), digit1),
1246///     rest
1247///   ))(input)
1248/// }
1249///
1250/// assert_eq!(parser("+10 ab"), Ok((" ab", "10")));
1251/// assert_eq!(parser("ab"), Ok(("", "ab")));
1252/// assert_eq!(parser("+"), Ok(("", "+")));
1253/// # }
1254/// ```
1255///
1256/// With `cut`:
1257/// ```rust
1258/// # use nom8::{Err,error::ErrorKind, IResult, error::Error};
1259/// # use nom8::bytes::one_of;
1260/// # use nom8::character::digit1;
1261/// # use nom8::combinator::rest;
1262/// # use nom8::branch::alt;
1263/// # use nom8::sequence::preceded;
1264/// use nom8::combinator::cut;
1265/// # fn main() {
1266///
1267/// fn parser(input: &str) -> IResult<&str, &str> {
1268///   alt((
1269///     preceded(one_of("+-"), cut(digit1)),
1270///     rest
1271///   ))(input)
1272/// }
1273///
1274/// assert_eq!(parser("+10 ab"), Ok((" ab", "10")));
1275/// assert_eq!(parser("ab"), Ok(("", "ab")));
1276/// assert_eq!(parser("+"), Err(Err::Failure(Error { input: "", code: ErrorKind::Digit })));
1277/// # }
1278/// ```
1279pub fn cut<I, O, E: ParseError<I>, F>(mut parser: F) -> impl FnMut(I) -> IResult<I, O, E>
1280where
1281  F: Parser<I, O, E>,
1282{
1283  move |input: I| match parser.parse(input) {
1284    Err(Err::Error(e)) => Err(Err::Failure(e)),
1285    rest => rest,
1286  }
1287}
1288
1289/// automatically converts the child parser's result to another type
1290///
1291/// it will be able to convert the output value and the error value
1292/// as long as the `Into` implementations are available
1293///
1294/// **WARNING:** Deprecated, replaced with [`Parser::output_into`] and [`Parser::err_into`]
1295///
1296/// ```rust
1297/// # use nom8::IResult;
1298/// use nom8::combinator::into;
1299/// use nom8::character::alpha1;
1300/// # fn main() {
1301///
1302///  fn parser1(i: &str) -> IResult<&str, &str> {
1303///    alpha1(i)
1304///  }
1305///
1306///  let mut parser2 = into(parser1);
1307///
1308/// // the parser converts the &str output of the child parser into a Vec<u8>
1309/// let bytes: IResult<&str, Vec<u8>> = parser2("abcd");
1310/// assert_eq!(bytes, Ok(("", vec![97, 98, 99, 100])));
1311/// # }
1312/// ```
1313#[deprecated(
1314  since = "8.0.0",
1315  note = "Replaced with `Parser::output_into` and `Parser::err_into`"
1316)]
1317pub fn into<I, O1, O2, E1, E2, F>(mut parser: F) -> impl FnMut(I) -> IResult<I, O2, E2>
1318where
1319  O1: convert::Into<O2>,
1320  E1: convert::Into<E2>,
1321  E1: ParseError<I>,
1322  E2: ParseError<I>,
1323  F: Parser<I, O1, E1>,
1324{
1325  //map(parser, Into::into)
1326  move |input: I| match parser.parse(input) {
1327    Ok((i, o)) => Ok((i, o.into())),
1328    Err(Err::Error(e)) => Err(Err::Error(e.into())),
1329    Err(Err::Failure(e)) => Err(Err::Failure(e.into())),
1330    Err(Err::Incomplete(e)) => Err(Err::Incomplete(e)),
1331  }
1332}
1333
1334/// Implementation of [`Parser::output_into`]
1335#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
1336pub struct OutputInto<F, O1, O2: From<O1>> {
1337  f: F,
1338  phantom_out1: core::marker::PhantomData<O1>,
1339  phantom_out2: core::marker::PhantomData<O2>,
1340}
1341
1342impl<F, O1, O2: From<O1>> OutputInto<F, O1, O2> {
1343  pub(crate) fn new(f: F) -> Self {
1344    Self {
1345      f,
1346      phantom_out1: Default::default(),
1347      phantom_out2: Default::default(),
1348    }
1349  }
1350}
1351
1352impl<'a, I: Clone, O1, O2: From<O1>, E, F: Parser<I, O1, E>> Parser<I, O2, E>
1353  for OutputInto<F, O1, O2>
1354{
1355  fn parse(&mut self, i: I) -> IResult<I, O2, E> {
1356    match self.f.parse(i) {
1357      Ok((i, o)) => Ok((i, o.into())),
1358      Err(err) => Err(err),
1359    }
1360  }
1361}
1362
1363/// Implementation of [`Parser::err_into`]
1364#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
1365pub struct ErrInto<F, E1, E2: From<E1>> {
1366  f: F,
1367  phantom_err1: core::marker::PhantomData<E1>,
1368  phantom_err2: core::marker::PhantomData<E2>,
1369}
1370
1371impl<F, E1, E2: From<E1>> ErrInto<F, E1, E2> {
1372  pub(crate) fn new(f: F) -> Self {
1373    Self {
1374      f,
1375      phantom_err1: Default::default(),
1376      phantom_err2: Default::default(),
1377    }
1378  }
1379}
1380
1381impl<'a, I: Clone, O, E1, E2: crate::error::ParseError<I> + From<E1>, F: Parser<I, O, E1>>
1382  Parser<I, O, E2> for ErrInto<F, E1, E2>
1383{
1384  fn parse(&mut self, i: I) -> IResult<I, O, E2> {
1385    match self.f.parse(i) {
1386      Ok(ok) => Ok(ok),
1387      Err(Err::Error(e)) => Err(Err::Error(e.into())),
1388      Err(Err::Failure(e)) => Err(Err::Failure(e.into())),
1389      Err(Err::Incomplete(e)) => Err(Err::Incomplete(e)),
1390    }
1391  }
1392}
1393
1394/// Creates an iterator from input data and a parser.
1395///
1396/// Call the iterator's [ParserIterator::finish] method to get the remaining input if successful,
1397/// or the error value if we encountered an error.
1398///
1399/// On [`Err::Error`], iteration will stop.  To instead chain an error up, see [`cut`].
1400///
1401/// ```rust
1402/// use nom8::{combinator::iterator, IResult, bytes::tag, character::alpha1, sequence::terminated};
1403/// use std::collections::HashMap;
1404///
1405/// let data = "abc|defg|hijkl|mnopqr|123";
1406/// let mut it = iterator(data, terminated(alpha1, tag("|")));
1407///
1408/// let parsed = it.map(|v| (v, v.len())).collect::<HashMap<_,_>>();
1409/// let res: IResult<_,_> = it.finish();
1410///
1411/// assert_eq!(parsed, [("abc", 3usize), ("defg", 4), ("hijkl", 5), ("mnopqr", 6)].iter().cloned().collect());
1412/// assert_eq!(res, Ok(("123", ())));
1413/// ```
1414pub fn iterator<Input, Output, Error, F>(
1415  input: Input,
1416  f: F,
1417) -> ParserIterator<Input, Output, Error, F>
1418where
1419  F: Parser<Input, Output, Error>,
1420  Error: ParseError<Input>,
1421{
1422  ParserIterator {
1423    iterator: f,
1424    input,
1425    output: Default::default(),
1426    state: Some(State::Running),
1427  }
1428}
1429
1430/// Main structure associated to the [iterator] function.
1431pub struct ParserIterator<I, O, E, F> {
1432  iterator: F,
1433  input: I,
1434  output: core::marker::PhantomData<O>,
1435  state: Option<State<E>>,
1436}
1437
1438impl<I: Clone, O, E, F> ParserIterator<I, O, E, F> {
1439  /// Returns the remaining input if parsing was successful, or the error if we encountered an error.
1440  pub fn finish(mut self) -> IResult<I, (), E> {
1441    match self.state.take().unwrap() {
1442      State::Running | State::Done => Ok((self.input, ())),
1443      State::Failure(e) => Err(Err::Failure(e)),
1444      State::Incomplete(i) => Err(Err::Incomplete(i)),
1445    }
1446  }
1447}
1448
1449impl<'a, Input, Output, Error, F> core::iter::Iterator
1450  for &'a mut ParserIterator<Input, Output, Error, F>
1451where
1452  F: Parser<Input, Output, Error>,
1453  Input: Clone,
1454{
1455  type Item = Output;
1456
1457  fn next(&mut self) -> Option<Self::Item> {
1458    if let State::Running = self.state.take().unwrap() {
1459      let input = self.input.clone();
1460
1461      match self.iterator.parse(input) {
1462        Ok((i, o)) => {
1463          self.input = i;
1464          self.state = Some(State::Running);
1465          Some(o)
1466        }
1467        Err(Err::Error(_)) => {
1468          self.state = Some(State::Done);
1469          None
1470        }
1471        Err(Err::Failure(e)) => {
1472          self.state = Some(State::Failure(e));
1473          None
1474        }
1475        Err(Err::Incomplete(i)) => {
1476          self.state = Some(State::Incomplete(i));
1477          None
1478        }
1479      }
1480    } else {
1481      None
1482    }
1483  }
1484}
1485
1486enum State<E> {
1487  Running,
1488  Done,
1489  Failure(E),
1490  Incomplete(Needed),
1491}
1492
1493/// a parser which always succeeds with given value without consuming any input.
1494///
1495/// It can be used for example as the last alternative in `alt` to
1496/// specify the default case.
1497///
1498/// ```rust
1499/// # use nom8::{Err,error::ErrorKind, IResult};
1500/// use nom8::branch::alt;
1501/// use nom8::combinator::{success, value};
1502/// # fn main() {
1503///
1504/// let mut parser = success::<_,_,(_,ErrorKind)>(10);
1505/// assert_eq!(parser("xyz"), Ok(("xyz", 10)));
1506///
1507/// let mut sign = alt((value(-1, '-'), value(1, '+'), success::<_,_,(_,ErrorKind)>(1)));
1508/// assert_eq!(sign("+10"), Ok(("10", 1)));
1509/// assert_eq!(sign("-10"), Ok(("10", -1)));
1510/// assert_eq!(sign("10"), Ok(("10", 1)));
1511/// # }
1512/// ```
1513pub fn success<I, O: Clone, E: ParseError<I>>(val: O) -> impl Fn(I) -> IResult<I, O, E> {
1514  move |input: I| Ok((input, val.clone()))
1515}
1516
1517/// A parser which always fails.
1518///
1519/// ```rust
1520/// # use nom8::{Err, error::ErrorKind, IResult};
1521/// use nom8::combinator::fail;
1522///
1523/// let s = "string";
1524/// assert_eq!(fail::<_, &str, _>(s), Err(Err::Error((s, ErrorKind::Fail))));
1525/// ```
1526pub fn fail<I, O, E: ParseError<I>>(i: I) -> IResult<I, O, E> {
1527  Err(Err::Error(E::from_error_kind(i, ErrorKind::Fail)))
1528}