nom8/
input.rs

1//! Input capability for nom combinators to parse
2//!
3//! Input types include:
4//! - `&str` and `&[u8]` are the standard input types
5//! - [`Located`] can track the location within the original buffer to report
6//!   [spans][crate::Parser::with_span]
7//! - [`Stateful`] to thread global state through your parsers
8//! - [`Streaming`] can mark an input as partial buffer that is being streamed into
9//!
10//! # How do a parse a custom input type?
11//!
12//! While historically, nom has worked mainly on `&[u8]` and `&str`, it can actually
13//! use any type as input, as long as they follow a specific set of traits.
14//! Those traits were developed first to abstract away the differences between
15//! `&[u8]` and `&str`, but were then employed for more interesting types,
16//! like [nom_locate](https://github.com/fflorent/nom_locate), a wrapper type
17//! that can carry line and column information, or to parse
18//! [a list of tokens](https://github.com/Rydgel/monkey-rust/blob/master/lib/parser/mod.rs).
19//!
20//! ## Implementing a custom type
21//!
22//! Let's assume we have an input type we'll call `MyInput`. `MyInput` is a sequence of `MyItem` type.
23//! The goal is to define nom parsers with this signature: `MyInput -> IResult<MyInput, Output>`.
24//!
25//! ```rust,ignore
26//! fn parser(i: MyInput) -> IResult<MyInput, Output> {
27//!     tag("test")(i)
28//! }
29//! ```
30//!
31//! Here are the traits we have to implement for `MyInput`:
32//!
33//! | trait | usage |
34//! |---|---|
35//! | [InputIsStreaming] | Marks the input as being the complete buffer or a partial buffer for streaming input |
36//! | [AsBytes] |Casts the input type to a byte slice|
37//! | [Compare] |Character comparison operations|
38//! | [ExtendInto] |Abstracts something which can extend an `Extend`|
39//! | [FindSubstring] |Look for a substring in self|
40//! | [FindToken] |Look for self in the given input stream|
41//! | [InputIter] |Common iteration operations on the input type|
42//! | [InputLength] |Calculate the input length|
43//! | [IntoOutput] |Adapt a captired `Input` into an appropriate type|
44//! | [Location] |Calculate location within initial input|
45//! | [InputTake] |Slicing operations|
46//! | [InputTakeAtPosition] |Look for a specific token and split at its position|
47//! | [Offset] |Calculate the offset between slices|
48//! | [ParseTo] |Used to integrate `&str`'s `parse()` method|
49//! | [Slice] |Slicing operations using ranges|
50//!
51//! Here are the traits we have to implement for `MyItem`:
52//!
53//! | trait | usage |
54//! |---|---|
55//! | [AsChar][AsChar] |Transforms common types to a char for basic token parsing|
56
57use core::num::NonZeroUsize;
58
59use crate::error::{ErrorKind, ParseError};
60use crate::lib::std::iter::{Copied, Enumerate};
61use crate::lib::std::ops::{
62  Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
63};
64use crate::lib::std::slice::Iter;
65use crate::lib::std::str::from_utf8;
66use crate::lib::std::str::CharIndices;
67use crate::lib::std::str::Chars;
68use crate::lib::std::str::FromStr;
69use crate::{Err, IResult, Needed};
70
71#[cfg(feature = "alloc")]
72use crate::lib::std::string::String;
73#[cfg(feature = "alloc")]
74use crate::lib::std::vec::Vec;
75
76/// Allow collecting the span of a parsed token
77///
78/// See [`Parser::span`][crate::Parser::span] and [`Parser::with_span`][crate::Parser::with_span] for more details
79#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
80pub struct Located<I> {
81  initial: I,
82  input: I,
83}
84
85impl<I> Located<I>
86where
87  I: Clone + IntoOutput + Offset,
88{
89  /// Wrap another Input with span tracking
90  pub fn new(input: I) -> Self {
91    let initial = input.clone();
92    Self { initial, input }
93  }
94
95  fn location(&self) -> usize {
96    self.initial.offset(&self.input)
97  }
98}
99
100impl<I> AsRef<I> for Located<I> {
101  fn as_ref(&self) -> &I {
102    &self.input
103  }
104}
105
106impl<I> crate::lib::std::ops::Deref for Located<I> {
107  type Target = I;
108
109  #[inline(always)]
110  fn deref(&self) -> &Self::Target {
111    &self.input
112  }
113}
114
115/// Thread global state through your parsers
116///
117/// Use cases
118/// - Recusion checks
119/// - Errror recovery
120/// - Debugging
121///
122/// # Example
123///
124/// ```
125/// # use std::cell::Cell;
126/// # use nom8::prelude::*;
127/// # use nom8::input::Stateful;
128/// # use nom8::character::alpha1;
129/// # type Error = ();
130///
131/// #[derive(Clone, Debug)]
132/// struct State<'s>(&'s Cell<u32>);
133///
134/// impl<'s> State<'s> {
135///     fn count(&self) {
136///         self.0.set(self.0.get() + 1);
137///     }
138/// }
139///
140/// type Input<'is> = Stateful<&'is str, State<'is>>;
141///
142/// fn word(i: Input<'_>) -> IResult<Input<'_>, &str> {
143///   i.state.count();
144///   alpha1(i)
145/// }
146///
147/// let data = "Hello";
148/// let state = Cell::new(0);
149/// let input = Input { input: data, state: State(&state) };
150/// let output = word.parse(input).finish().unwrap();
151/// assert_eq!(state.get(), 1);
152/// ```
153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
154pub struct Stateful<I, S> {
155  /// Inner input being wrapped in state
156  pub input: I,
157  /// User-provided state
158  pub state: S,
159}
160
161impl<I, S> AsRef<I> for Stateful<I, S> {
162  fn as_ref(&self) -> &I {
163    &self.input
164  }
165}
166
167impl<I, S> crate::lib::std::ops::Deref for Stateful<I, S> {
168  type Target = I;
169
170  fn deref(&self) -> &Self::Target {
171    self.as_ref()
172  }
173}
174
175/// Mark the input as a partial buffer for streaming input.
176///
177/// Complete input means that we already have all of the data.  This will be the common case with
178/// small files that can be read entirely to memory.
179///
180/// In contrast, streaming input assumes that we might not have all of the data.
181/// This can happen with some network protocol or large file parsers, where the
182/// input buffer can be full and need to be resized or refilled.
183/// - [`Err::Incomplete`] will report how much more data is needed.
184/// - [`Parser::complete`][crate::Parser::complete] transform [`Err::Incomplete`] to
185///   [`Err::Error`]
186///
187/// See also [`InputIsStreaming`] to tell whether the input supports complete or streaming parsing.
188///
189/// # Example
190///
191/// Here is how it works in practice:
192///
193/// ```rust
194/// use nom8::{IResult, Err, Needed, error::{Error, ErrorKind}, bytes, character, input::Streaming};
195///
196/// fn take_streaming(i: Streaming<&[u8]>) -> IResult<Streaming<&[u8]>, &[u8]> {
197///   bytes::take(4u8)(i)
198/// }
199///
200/// fn take_complete(i: &[u8]) -> IResult<&[u8], &[u8]> {
201///   bytes::take(4u8)(i)
202/// }
203///
204/// // both parsers will take 4 bytes as expected
205/// assert_eq!(take_streaming(Streaming(&b"abcde"[..])), Ok((Streaming(&b"e"[..]), &b"abcd"[..])));
206/// assert_eq!(take_complete(&b"abcde"[..]), Ok((&b"e"[..], &b"abcd"[..])));
207///
208/// // if the input is smaller than 4 bytes, the streaming parser
209/// // will return `Incomplete` to indicate that we need more data
210/// assert_eq!(take_streaming(Streaming(&b"abc"[..])), Err(Err::Incomplete(Needed::new(1))));
211///
212/// // but the complete parser will return an error
213/// assert_eq!(take_complete(&b"abc"[..]), Err(Err::Error(Error::new(&b"abc"[..], ErrorKind::Eof))));
214///
215/// // the alpha0 function recognizes 0 or more alphabetic characters
216/// fn alpha0_streaming(i: Streaming<&str>) -> IResult<Streaming<&str>, &str> {
217///   character::alpha0(i)
218/// }
219///
220/// fn alpha0_complete(i: &str) -> IResult<&str, &str> {
221///   character::alpha0(i)
222/// }
223///
224/// // if there's a clear limit to the recognized characters, both parsers work the same way
225/// assert_eq!(alpha0_streaming(Streaming("abcd;")), Ok((Streaming(";"), "abcd")));
226/// assert_eq!(alpha0_complete("abcd;"), Ok((";", "abcd")));
227///
228/// // but when there's no limit, the streaming version returns `Incomplete`, because it cannot
229/// // know if more input data should be recognized. The whole input could be "abcd;", or
230/// // "abcde;"
231/// assert_eq!(alpha0_streaming(Streaming("abcd")), Err(Err::Incomplete(Needed::new(1))));
232///
233/// // while the complete version knows that all of the data is there
234/// assert_eq!(alpha0_complete("abcd"), Ok(("", "abcd")));
235/// ```
236#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
237pub struct Streaming<I>(pub I);
238
239impl<I> Streaming<I> {
240  /// Convert to complete counterpart
241  #[inline(always)]
242  pub fn into_complete(self) -> I {
243    self.0
244  }
245}
246
247impl<I> crate::lib::std::ops::Deref for Streaming<I> {
248  type Target = I;
249
250  #[inline(always)]
251  fn deref(&self) -> &Self::Target {
252    &self.0
253  }
254}
255
256/// Number of indices input has advanced since start of parsing
257pub trait Location {
258  /// Number of indices input has advanced since start of parsing
259  fn location(&self) -> usize;
260}
261
262impl<I> Location for Located<I>
263where
264  I: Clone + IntoOutput + Offset,
265{
266  fn location(&self) -> usize {
267    self.location()
268  }
269}
270
271impl<I, S> Location for Stateful<I, S>
272where
273  I: Location,
274{
275  fn location(&self) -> usize {
276    self.input.location()
277  }
278}
279
280impl<I> Location for Streaming<I>
281where
282  I: Location,
283{
284  fn location(&self) -> usize {
285    self.0.location()
286  }
287}
288
289/// Marks the input as being the complete buffer or a partial buffer for streaming input
290///
291/// See [Streaming] for marking a presumed complete buffer type as a streaming buffer.
292pub trait InputIsStreaming<const YES: bool>: Sized {
293  /// Complete counterpart
294  ///
295  /// - Set to `Self` if this is a complete buffer.
296  /// - Set to [`std::convert::Infallible`] if there isn't an associated complete buffer type
297  type Complete: InputIsStreaming<false>;
298  /// Streaming counterpart
299  ///
300  /// - Set to `Self` if this is a streaming buffer.
301  /// - Set to [`std::convert::Infallible`] if there isn't an associated streaming buffer type
302  type Streaming: InputIsStreaming<true>;
303
304  /// Convert to complete counterpart
305  fn into_complete(self) -> Self::Complete;
306  /// Convert to streaming counterpart
307  fn into_streaming(self) -> Self::Streaming;
308}
309
310impl<I> InputIsStreaming<true> for Located<I>
311where
312  I: InputIsStreaming<true>,
313{
314  type Complete = Located<<I as InputIsStreaming<true>>::Complete>;
315  type Streaming = Self;
316
317  #[inline(always)]
318  fn into_complete(self) -> Self::Complete {
319    Located {
320      initial: self.initial.into_complete(),
321      input: self.input.into_complete(),
322    }
323  }
324  #[inline(always)]
325  fn into_streaming(self) -> Self::Streaming {
326    self
327  }
328}
329
330impl<I> InputIsStreaming<false> for Located<I>
331where
332  I: InputIsStreaming<false>,
333{
334  type Complete = Self;
335  type Streaming = Located<<I as InputIsStreaming<false>>::Streaming>;
336
337  #[inline(always)]
338  fn into_complete(self) -> Self::Complete {
339    self
340  }
341  #[inline(always)]
342  fn into_streaming(self) -> Self::Streaming {
343    Located {
344      initial: self.initial.into_streaming(),
345      input: self.input.into_streaming(),
346    }
347  }
348}
349
350impl<I, S> InputIsStreaming<true> for Stateful<I, S>
351where
352  I: InputIsStreaming<true>,
353{
354  type Complete = Stateful<<I as InputIsStreaming<true>>::Complete, S>;
355  type Streaming = Self;
356
357  #[inline(always)]
358  fn into_complete(self) -> Self::Complete {
359    Stateful {
360      input: self.input.into_complete(),
361      state: self.state,
362    }
363  }
364  #[inline(always)]
365  fn into_streaming(self) -> Self::Streaming {
366    self
367  }
368}
369
370impl<I, S> InputIsStreaming<false> for Stateful<I, S>
371where
372  I: InputIsStreaming<false>,
373{
374  type Complete = Self;
375  type Streaming = Stateful<<I as InputIsStreaming<false>>::Streaming, S>;
376
377  #[inline(always)]
378  fn into_complete(self) -> Self::Complete {
379    self
380  }
381  #[inline(always)]
382  fn into_streaming(self) -> Self::Streaming {
383    Stateful {
384      input: self.input.into_streaming(),
385      state: self.state,
386    }
387  }
388}
389
390impl<I> InputIsStreaming<true> for Streaming<I>
391where
392  I: InputIsStreaming<false>,
393{
394  type Complete = I;
395  type Streaming = Self;
396
397  #[inline(always)]
398  fn into_complete(self) -> Self::Complete {
399    self.0
400  }
401  #[inline(always)]
402  fn into_streaming(self) -> Self::Streaming {
403    self
404  }
405}
406
407impl<'a, T> InputIsStreaming<false> for &'a [T] {
408  type Complete = Self;
409  type Streaming = Streaming<Self>;
410
411  #[inline(always)]
412  fn into_complete(self) -> Self::Complete {
413    self
414  }
415  #[inline(always)]
416  fn into_streaming(self) -> Self::Streaming {
417    Streaming(self)
418  }
419}
420
421impl<T, const L: usize> InputIsStreaming<false> for [T; L] {
422  type Complete = Self;
423  type Streaming = Streaming<Self>;
424
425  #[inline(always)]
426  fn into_complete(self) -> Self::Complete {
427    self
428  }
429  #[inline(always)]
430  fn into_streaming(self) -> Self::Streaming {
431    Streaming(self)
432  }
433}
434
435impl<'a, T, const L: usize> InputIsStreaming<false> for &'a [T; L] {
436  type Complete = Self;
437  type Streaming = Streaming<Self>;
438
439  #[inline(always)]
440  fn into_complete(self) -> Self::Complete {
441    self
442  }
443  #[inline(always)]
444  fn into_streaming(self) -> Self::Streaming {
445    Streaming(self)
446  }
447}
448
449impl<'a> InputIsStreaming<false> for &'a str {
450  type Complete = Self;
451  type Streaming = Streaming<Self>;
452
453  #[inline(always)]
454  fn into_complete(self) -> Self::Complete {
455    self
456  }
457  #[inline(always)]
458  fn into_streaming(self) -> Self::Streaming {
459    Streaming(self)
460  }
461}
462
463impl<'a> InputIsStreaming<false> for (&'a [u8], usize) {
464  type Complete = Self;
465  type Streaming = Streaming<Self>;
466
467  #[inline(always)]
468  fn into_complete(self) -> Self::Complete {
469    self
470  }
471  #[inline(always)]
472  fn into_streaming(self) -> Self::Streaming {
473    Streaming(self)
474  }
475}
476
477impl<const YES: bool> InputIsStreaming<YES> for crate::lib::std::convert::Infallible {
478  type Complete = Self;
479  type Streaming = Self;
480
481  #[inline(always)]
482  fn into_complete(self) -> Self::Complete {
483    self
484  }
485  #[inline(always)]
486  fn into_streaming(self) -> Self::Streaming {
487    self
488  }
489}
490
491/// Abstract method to calculate the input length
492pub trait InputLength {
493  /// Calculates the input length, as indicated by its name,
494  /// and the name of the trait itself
495  fn input_len(&self) -> usize;
496}
497
498impl<I> InputLength for Located<I>
499where
500  I: InputLength,
501{
502  fn input_len(&self) -> usize {
503    self.input.input_len()
504  }
505}
506
507impl<I, S> InputLength for Stateful<I, S>
508where
509  I: InputLength,
510{
511  fn input_len(&self) -> usize {
512    self.input.input_len()
513  }
514}
515
516impl<I> InputLength for Streaming<I>
517where
518  I: InputLength,
519{
520  #[inline(always)]
521  fn input_len(&self) -> usize {
522    self.0.input_len()
523  }
524}
525
526impl<'a, T> InputLength for &'a [T] {
527  #[inline]
528  fn input_len(&self) -> usize {
529    self.len()
530  }
531}
532
533impl<const LEN: usize> InputLength for [u8; LEN] {
534  #[inline]
535  fn input_len(&self) -> usize {
536    self.len()
537  }
538}
539
540impl<'a, const LEN: usize> InputLength for &'a [u8; LEN] {
541  #[inline]
542  fn input_len(&self) -> usize {
543    self.len()
544  }
545}
546
547impl<'a> InputLength for &'a str {
548  #[inline]
549  fn input_len(&self) -> usize {
550    self.len()
551  }
552}
553
554impl<'a> InputLength for (&'a [u8], usize) {
555  #[inline]
556  fn input_len(&self) -> usize {
557    self.0.len() * 8 - self.1
558  }
559}
560
561/// Useful functions to calculate the offset between slices and show a hexdump of a slice
562pub trait Offset {
563  /// Offset between the first byte of self and the first byte of the argument
564  fn offset(&self, second: &Self) -> usize;
565}
566
567impl<I> Offset for Located<I>
568where
569  I: Offset,
570{
571  fn offset(&self, other: &Self) -> usize {
572    self.input.offset(&other.input)
573  }
574}
575
576impl<I, S> Offset for Stateful<I, S>
577where
578  I: Offset,
579{
580  fn offset(&self, other: &Self) -> usize {
581    self.input.offset(&other.input)
582  }
583}
584
585impl<I> Offset for Streaming<I>
586where
587  I: Offset,
588{
589  #[inline(always)]
590  fn offset(&self, second: &Self) -> usize {
591    self.0.offset(&second.0)
592  }
593}
594
595impl Offset for [u8] {
596  fn offset(&self, second: &Self) -> usize {
597    let fst = self.as_ptr();
598    let snd = second.as_ptr();
599
600    snd as usize - fst as usize
601  }
602}
603
604impl<'a> Offset for &'a [u8] {
605  fn offset(&self, second: &Self) -> usize {
606    let fst = self.as_ptr();
607    let snd = second.as_ptr();
608
609    snd as usize - fst as usize
610  }
611}
612
613impl Offset for str {
614  fn offset(&self, second: &Self) -> usize {
615    let fst = self.as_ptr();
616    let snd = second.as_ptr();
617
618    snd as usize - fst as usize
619  }
620}
621
622impl<'a> Offset for &'a str {
623  fn offset(&self, second: &Self) -> usize {
624    let fst = self.as_ptr();
625    let snd = second.as_ptr();
626
627    snd as usize - fst as usize
628  }
629}
630
631/// Helper trait for types that can be viewed as a byte slice
632pub trait AsBytes {
633  /// Casts the input type to a byte slice
634  fn as_bytes(&self) -> &[u8];
635}
636
637impl<I> AsBytes for Located<I>
638where
639  I: AsBytes,
640{
641  fn as_bytes(&self) -> &[u8] {
642    self.input.as_bytes()
643  }
644}
645
646impl<I, S> AsBytes for Stateful<I, S>
647where
648  I: AsBytes,
649{
650  fn as_bytes(&self) -> &[u8] {
651    self.input.as_bytes()
652  }
653}
654
655impl<I> AsBytes for Streaming<I>
656where
657  I: AsBytes,
658{
659  #[inline(always)]
660  fn as_bytes(&self) -> &[u8] {
661    self.0.as_bytes()
662  }
663}
664
665impl AsBytes for [u8] {
666  #[inline(always)]
667  fn as_bytes(&self) -> &[u8] {
668    self
669  }
670}
671
672impl<'a> AsBytes for &'a [u8] {
673  #[inline(always)]
674  fn as_bytes(&self) -> &[u8] {
675    *self
676  }
677}
678
679impl<const LEN: usize> AsBytes for [u8; LEN] {
680  #[inline(always)]
681  fn as_bytes(&self) -> &[u8] {
682    self
683  }
684}
685
686impl<'a, const LEN: usize> AsBytes for &'a [u8; LEN] {
687  #[inline(always)]
688  fn as_bytes(&self) -> &[u8] {
689    *self
690  }
691}
692
693impl<'a> AsBytes for &'a str {
694  #[inline(always)]
695  fn as_bytes(&self) -> &[u8] {
696    (*self).as_bytes()
697  }
698}
699
700impl AsBytes for str {
701  #[inline(always)]
702  fn as_bytes(&self) -> &[u8] {
703    self.as_ref()
704  }
705}
706
707/// Transforms common types to a char for basic token parsing
708pub trait AsChar {
709  /// Makes a char from self
710  ///
711  /// ```
712  /// use nom8::input::AsChar as _;
713  ///
714  /// assert_eq!('a'.as_char(), 'a');
715  /// assert_eq!(u8::MAX.as_char(), std::char::from_u32(u8::MAX as u32).unwrap());
716  /// ```
717  fn as_char(self) -> char;
718
719  /// Tests that self is an alphabetic character
720  ///
721  /// Warning: for `&str` it recognizes alphabetic
722  /// characters outside of the 52 ASCII letters
723  fn is_alpha(self) -> bool;
724
725  /// Tests that self is an alphabetic character
726  /// or a decimal digit
727  fn is_alphanum(self) -> bool;
728  /// Tests that self is a decimal digit
729  fn is_dec_digit(self) -> bool;
730  /// Tests that self is an hex digit
731  fn is_hex_digit(self) -> bool;
732  /// Tests that self is an octal digit
733  fn is_oct_digit(self) -> bool;
734  /// Gets the len in bytes for self
735  fn len(self) -> usize;
736  /// Tests that self is ASCII space or tab
737  fn is_space(self) -> bool;
738  /// Tests if byte is ASCII newline: \n
739  fn is_newline(self) -> bool;
740}
741
742impl AsChar for u8 {
743  #[inline]
744  fn as_char(self) -> char {
745    self as char
746  }
747  #[inline]
748  fn is_alpha(self) -> bool {
749    (self >= 0x41 && self <= 0x5A) || (self >= 0x61 && self <= 0x7A)
750  }
751  #[inline]
752  fn is_alphanum(self) -> bool {
753    self.is_alpha() || self.is_dec_digit()
754  }
755  #[inline]
756  fn is_dec_digit(self) -> bool {
757    self >= 0x30 && self <= 0x39
758  }
759  #[inline]
760  fn is_hex_digit(self) -> bool {
761    (self >= 0x30 && self <= 0x39)
762      || (self >= 0x41 && self <= 0x46)
763      || (self >= 0x61 && self <= 0x66)
764  }
765  #[inline]
766  fn is_oct_digit(self) -> bool {
767    self >= 0x30 && self <= 0x37
768  }
769  #[inline]
770  fn len(self) -> usize {
771    1
772  }
773  #[inline]
774  fn is_space(self) -> bool {
775    self == b' ' || self == b'\t'
776  }
777  fn is_newline(self) -> bool {
778    self == b'\n'
779  }
780}
781impl<'a> AsChar for &'a u8 {
782  #[inline]
783  fn as_char(self) -> char {
784    *self as char
785  }
786  #[inline]
787  fn is_alpha(self) -> bool {
788    (*self >= 0x41 && *self <= 0x5A) || (*self >= 0x61 && *self <= 0x7A)
789  }
790  #[inline]
791  fn is_alphanum(self) -> bool {
792    self.is_alpha() || self.is_dec_digit()
793  }
794  #[inline]
795  fn is_dec_digit(self) -> bool {
796    *self >= 0x30 && *self <= 0x39
797  }
798  #[inline]
799  fn is_hex_digit(self) -> bool {
800    (*self >= 0x30 && *self <= 0x39)
801      || (*self >= 0x41 && *self <= 0x46)
802      || (*self >= 0x61 && *self <= 0x66)
803  }
804  #[inline]
805  fn is_oct_digit(self) -> bool {
806    *self >= 0x30 && *self <= 0x37
807  }
808  #[inline]
809  fn len(self) -> usize {
810    1
811  }
812  #[inline]
813  fn is_space(self) -> bool {
814    *self == b' ' || *self == b'\t'
815  }
816  fn is_newline(self) -> bool {
817    *self == b'\n'
818  }
819}
820
821impl AsChar for char {
822  #[inline]
823  fn as_char(self) -> char {
824    self
825  }
826  #[inline]
827  fn is_alpha(self) -> bool {
828    self.is_ascii_alphabetic()
829  }
830  #[inline]
831  fn is_alphanum(self) -> bool {
832    self.is_alpha() || self.is_dec_digit()
833  }
834  #[inline]
835  fn is_dec_digit(self) -> bool {
836    self.is_ascii_digit()
837  }
838  #[inline]
839  fn is_hex_digit(self) -> bool {
840    self.is_ascii_hexdigit()
841  }
842  #[inline]
843  fn is_oct_digit(self) -> bool {
844    self.is_digit(8)
845  }
846  #[inline]
847  fn len(self) -> usize {
848    self.len_utf8()
849  }
850  #[inline]
851  fn is_space(self) -> bool {
852    self == ' ' || self == '\t'
853  }
854  fn is_newline(self) -> bool {
855    self == '\n'
856  }
857}
858
859impl<'a> AsChar for &'a char {
860  #[inline]
861  fn as_char(self) -> char {
862    *self
863  }
864  #[inline]
865  fn is_alpha(self) -> bool {
866    self.is_ascii_alphabetic()
867  }
868  #[inline]
869  fn is_alphanum(self) -> bool {
870    self.is_alpha() || self.is_dec_digit()
871  }
872  #[inline]
873  fn is_dec_digit(self) -> bool {
874    self.is_ascii_digit()
875  }
876  #[inline]
877  fn is_hex_digit(self) -> bool {
878    self.is_ascii_hexdigit()
879  }
880  #[inline]
881  fn is_oct_digit(self) -> bool {
882    self.is_digit(8)
883  }
884  #[inline]
885  fn len(self) -> usize {
886    self.len_utf8()
887  }
888  #[inline]
889  fn is_space(self) -> bool {
890    *self == ' ' || *self == '\t'
891  }
892  fn is_newline(self) -> bool {
893    *self == '\n'
894  }
895}
896
897/// Abstracts common iteration operations on the input type
898pub trait InputIter {
899  /// The current input type is a sequence of that `Item` type.
900  ///
901  /// Example: `u8` for `&[u8]` or `char` for `&str`
902  type Item;
903  /// An iterator over the input type, producing the item and its position
904  /// for use with [Slice]. If we're iterating over `&str`, the position
905  /// corresponds to the byte index of the character
906  type Iter: Iterator<Item = (usize, Self::Item)>;
907
908  /// An iterator over the input type, producing the item
909  type IterElem: Iterator<Item = Self::Item>;
910
911  /// Returns an iterator over the elements and their byte offsets
912  fn iter_indices(&self) -> Self::Iter;
913  /// Returns an iterator over the elements
914  fn iter_elements(&self) -> Self::IterElem;
915  /// Finds the byte position of the element
916  fn position<P>(&self, predicate: P) -> Option<usize>
917  where
918    P: Fn(Self::Item) -> bool;
919  /// Get the byte offset from the element's position in the stream
920  fn slice_index(&self, count: usize) -> Result<usize, Needed>;
921}
922
923impl<I> InputIter for Located<I>
924where
925  I: InputIter,
926{
927  type Item = I::Item;
928  type Iter = I::Iter;
929  type IterElem = I::IterElem;
930
931  fn iter_indices(&self) -> Self::Iter {
932    self.input.iter_indices()
933  }
934
935  fn iter_elements(&self) -> Self::IterElem {
936    self.input.iter_elements()
937  }
938
939  fn position<P>(&self, predicate: P) -> Option<usize>
940  where
941    P: Fn(Self::Item) -> bool,
942  {
943    self.input.position(predicate)
944  }
945
946  fn slice_index(&self, count: usize) -> Result<usize, Needed> {
947    self.input.slice_index(count)
948  }
949}
950
951impl<I, S> InputIter for Stateful<I, S>
952where
953  I: InputIter,
954{
955  type Item = I::Item;
956  type Iter = I::Iter;
957  type IterElem = I::IterElem;
958
959  fn iter_indices(&self) -> Self::Iter {
960    self.input.iter_indices()
961  }
962
963  fn iter_elements(&self) -> Self::IterElem {
964    self.input.iter_elements()
965  }
966
967  fn position<P>(&self, predicate: P) -> Option<usize>
968  where
969    P: Fn(Self::Item) -> bool,
970  {
971    self.input.position(predicate)
972  }
973
974  fn slice_index(&self, count: usize) -> Result<usize, Needed> {
975    self.input.slice_index(count)
976  }
977}
978
979impl<I> InputIter for Streaming<I>
980where
981  I: InputIter,
982{
983  type Item = I::Item;
984  type Iter = I::Iter;
985  type IterElem = I::IterElem;
986
987  #[inline(always)]
988  fn iter_indices(&self) -> Self::Iter {
989    self.0.iter_indices()
990  }
991  #[inline(always)]
992  fn iter_elements(&self) -> Self::IterElem {
993    self.0.iter_elements()
994  }
995  #[inline(always)]
996  fn position<P>(&self, predicate: P) -> Option<usize>
997  where
998    P: Fn(Self::Item) -> bool,
999  {
1000    self.0.position(predicate)
1001  }
1002  #[inline(always)]
1003  fn slice_index(&self, count: usize) -> Result<usize, Needed> {
1004    self.0.slice_index(count)
1005  }
1006}
1007impl<'a> InputIter for &'a [u8] {
1008  type Item = u8;
1009  type Iter = Enumerate<Self::IterElem>;
1010  type IterElem = Copied<Iter<'a, u8>>;
1011
1012  #[inline]
1013  fn iter_indices(&self) -> Self::Iter {
1014    self.iter_elements().enumerate()
1015  }
1016  #[inline]
1017  fn iter_elements(&self) -> Self::IterElem {
1018    self.iter().copied()
1019  }
1020  #[inline]
1021  fn position<P>(&self, predicate: P) -> Option<usize>
1022  where
1023    P: Fn(Self::Item) -> bool,
1024  {
1025    self.iter().position(|b| predicate(*b))
1026  }
1027  #[inline]
1028  fn slice_index(&self, count: usize) -> Result<usize, Needed> {
1029    if let Some(needed) = count.checked_sub(self.len()).and_then(NonZeroUsize::new) {
1030      Err(Needed::Size(needed))
1031    } else {
1032      Ok(count)
1033    }
1034  }
1035}
1036
1037impl<'a, const LEN: usize> InputIter for &'a [u8; LEN] {
1038  type Item = u8;
1039  type Iter = Enumerate<Self::IterElem>;
1040  type IterElem = Copied<Iter<'a, u8>>;
1041
1042  fn iter_indices(&self) -> Self::Iter {
1043    (&self[..]).iter_indices()
1044  }
1045
1046  fn iter_elements(&self) -> Self::IterElem {
1047    (&self[..]).iter_elements()
1048  }
1049
1050  fn position<P>(&self, predicate: P) -> Option<usize>
1051  where
1052    P: Fn(Self::Item) -> bool,
1053  {
1054    (&self[..]).position(predicate)
1055  }
1056
1057  fn slice_index(&self, count: usize) -> Result<usize, Needed> {
1058    (&self[..]).slice_index(count)
1059  }
1060}
1061
1062impl<'a> InputIter for &'a str {
1063  type Item = char;
1064  type Iter = CharIndices<'a>;
1065  type IterElem = Chars<'a>;
1066  #[inline]
1067  fn iter_indices(&self) -> Self::Iter {
1068    self.char_indices()
1069  }
1070  #[inline]
1071  fn iter_elements(&self) -> Self::IterElem {
1072    self.chars()
1073  }
1074  fn position<P>(&self, predicate: P) -> Option<usize>
1075  where
1076    P: Fn(Self::Item) -> bool,
1077  {
1078    for (o, c) in self.char_indices() {
1079      if predicate(c) {
1080        return Some(o);
1081      }
1082    }
1083    None
1084  }
1085  #[inline]
1086  fn slice_index(&self, count: usize) -> Result<usize, Needed> {
1087    let mut cnt = 0;
1088    for (index, _) in self.char_indices() {
1089      if cnt == count {
1090        return Ok(index);
1091      }
1092      cnt += 1;
1093    }
1094    if cnt == count {
1095      return Ok(self.len());
1096    }
1097    Err(Needed::Unknown)
1098  }
1099}
1100
1101/// Abstracts slicing operations
1102pub trait InputTake: Sized {
1103  /// Returns a slice of `count` bytes. panics if count > length
1104  fn take(&self, count: usize) -> Self;
1105  /// Split the stream at the `count` byte offset. panics if count > length
1106  fn take_split(&self, count: usize) -> (Self, Self);
1107}
1108
1109impl<I> InputTake for Located<I>
1110where
1111  I: InputTake + Clone,
1112{
1113  fn take(&self, count: usize) -> Self {
1114    Self {
1115      initial: self.initial.clone(),
1116      input: self.input.take(count),
1117    }
1118  }
1119
1120  fn take_split(&self, count: usize) -> (Self, Self) {
1121    let (left, right) = self.input.take_split(count);
1122    (
1123      Self {
1124        initial: self.initial.clone(),
1125        input: left,
1126      },
1127      Self {
1128        initial: self.initial.clone(),
1129        input: right,
1130      },
1131    )
1132  }
1133}
1134
1135impl<I, S> InputTake for Stateful<I, S>
1136where
1137  I: InputTake,
1138  S: Clone,
1139{
1140  fn take(&self, count: usize) -> Self {
1141    Self {
1142      input: self.input.take(count),
1143      state: self.state.clone(),
1144    }
1145  }
1146
1147  fn take_split(&self, count: usize) -> (Self, Self) {
1148    let (left, right) = self.input.take_split(count);
1149    (
1150      Self {
1151        input: left,
1152        state: self.state.clone(),
1153      },
1154      Self {
1155        input: right,
1156        state: self.state.clone(),
1157      },
1158    )
1159  }
1160}
1161
1162impl<I> InputTake for Streaming<I>
1163where
1164  I: InputTake,
1165{
1166  #[inline(always)]
1167  fn take(&self, count: usize) -> Self {
1168    Streaming(self.0.take(count))
1169  }
1170  #[inline(always)]
1171  fn take_split(&self, count: usize) -> (Self, Self) {
1172    let (start, end) = self.0.take_split(count);
1173    (Streaming(start), Streaming(end))
1174  }
1175}
1176
1177impl<'a> InputTake for &'a [u8] {
1178  #[inline]
1179  fn take(&self, count: usize) -> Self {
1180    &self[0..count]
1181  }
1182  #[inline]
1183  fn take_split(&self, count: usize) -> (Self, Self) {
1184    let (prefix, suffix) = self.split_at(count);
1185    (suffix, prefix)
1186  }
1187}
1188
1189impl<'a> InputTake for &'a str {
1190  #[inline]
1191  fn take(&self, count: usize) -> Self {
1192    &self[..count]
1193  }
1194
1195  // return byte index
1196  #[inline]
1197  fn take_split(&self, count: usize) -> (Self, Self) {
1198    let (prefix, suffix) = self.split_at(count);
1199    (suffix, prefix)
1200  }
1201}
1202
1203/// Dummy trait used for default implementations (currently only used for `InputTakeAtPosition` and `Compare`).
1204///
1205/// When implementing a custom input type, it is possible to use directly the
1206/// default implementation: If the input type implements `InputLength`, `InputIter`,
1207/// `InputTake` and `Clone`, you can implement `UnspecializedInput` and get
1208/// a default version of `InputTakeAtPosition` and `Compare`.
1209///
1210/// For performance reasons, you might want to write a custom implementation of
1211/// `InputTakeAtPosition` (like the one for `&[u8]`).
1212pub trait UnspecializedInput {}
1213
1214/// Methods to take as much input as possible until the provided function returns true for the current element.
1215///
1216/// A large part of nom's basic parsers are built using this trait.
1217pub trait InputTakeAtPosition: Sized {
1218  /// The current input type is a sequence of that `Item` type.
1219  ///
1220  /// Example: `u8` for `&[u8]` or `char` for `&str`
1221  type Item;
1222
1223  /// Looks for the first element of the input type for which the condition returns true,
1224  /// and returns the input up to this position.
1225  ///
1226  /// *streaming version*: If no element is found matching the condition, this will return `Incomplete`
1227  fn split_at_position_streaming<P, E: ParseError<Self>>(
1228    &self,
1229    predicate: P,
1230  ) -> IResult<Self, Self, E>
1231  where
1232    P: Fn(Self::Item) -> bool;
1233
1234  /// Looks for the first element of the input type for which the condition returns true
1235  /// and returns the input up to this position.
1236  ///
1237  /// Fails if the produced slice is empty.
1238  ///
1239  /// *streaming version*: If no element is found matching the condition, this will return `Incomplete`
1240  fn split_at_position1_streaming<P, E: ParseError<Self>>(
1241    &self,
1242    predicate: P,
1243    e: ErrorKind,
1244  ) -> IResult<Self, Self, E>
1245  where
1246    P: Fn(Self::Item) -> bool;
1247
1248  /// Looks for the first element of the input type for which the condition returns true,
1249  /// and returns the input up to this position.
1250  ///
1251  /// *complete version*: If no element is found matching the condition, this will return the whole input
1252  fn split_at_position_complete<P, E: ParseError<Self>>(
1253    &self,
1254    predicate: P,
1255  ) -> IResult<Self, Self, E>
1256  where
1257    P: Fn(Self::Item) -> bool;
1258
1259  /// Looks for the first element of the input type for which the condition returns true
1260  /// and returns the input up to this position.
1261  ///
1262  /// Fails if the produced slice is empty.
1263  ///
1264  /// *complete version*: If no element is found matching the condition, this will return the whole input
1265  fn split_at_position1_complete<P, E: ParseError<Self>>(
1266    &self,
1267    predicate: P,
1268    e: ErrorKind,
1269  ) -> IResult<Self, Self, E>
1270  where
1271    P: Fn(Self::Item) -> bool;
1272}
1273
1274impl<I> InputTakeAtPosition for Located<I>
1275where
1276  I: InputTakeAtPosition + Clone,
1277{
1278  type Item = <I as InputTakeAtPosition>::Item;
1279
1280  fn split_at_position_complete<P, E>(&self, predicate: P) -> IResult<Self, Self, E>
1281  where
1282    P: Fn(Self::Item) -> bool,
1283    E: ParseError<Self>,
1284  {
1285    located_clone_map_result(self, move |data| data.split_at_position_complete(predicate))
1286  }
1287
1288  fn split_at_position_streaming<P, E>(&self, predicate: P) -> IResult<Self, Self, E>
1289  where
1290    P: Fn(Self::Item) -> bool,
1291    E: ParseError<Self>,
1292  {
1293    located_clone_map_result(self, move |data| {
1294      data.split_at_position_streaming(predicate)
1295    })
1296  }
1297
1298  fn split_at_position1_streaming<P, E>(
1299    &self,
1300    predicate: P,
1301    kind: ErrorKind,
1302  ) -> IResult<Self, Self, E>
1303  where
1304    P: Fn(Self::Item) -> bool,
1305    E: ParseError<Self>,
1306  {
1307    located_clone_map_result(self, move |data| {
1308      data.split_at_position1_streaming(predicate, kind)
1309    })
1310  }
1311
1312  fn split_at_position1_complete<P, E>(
1313    &self,
1314    predicate: P,
1315    kind: ErrorKind,
1316  ) -> IResult<Self, Self, E>
1317  where
1318    P: Fn(Self::Item) -> bool,
1319    E: ParseError<Self>,
1320  {
1321    located_clone_map_result(self, move |data| {
1322      data.split_at_position1_complete(predicate, kind)
1323    })
1324  }
1325}
1326
1327fn located_clone_map_result<I, E, F>(input: &Located<I>, f: F) -> IResult<Located<I>, Located<I>, E>
1328where
1329  I: Clone,
1330  E: ParseError<Located<I>>,
1331  F: FnOnce(&I) -> IResult<I, I>,
1332{
1333  let map_error = |error: crate::error::Error<I>| {
1334    E::from_error_kind(
1335      Located {
1336        initial: input.initial.clone(),
1337        input: error.input,
1338      },
1339      error.code,
1340    )
1341  };
1342  f(&input.input)
1343    .map(|(remaining, output)| {
1344      (
1345        Located {
1346          initial: input.initial.clone(),
1347          input: remaining,
1348        },
1349        Located {
1350          initial: input.initial.clone(),
1351          input: output,
1352        },
1353      )
1354    })
1355    .map_err(|error| match error {
1356      Err::Error(error) => Err::Error(map_error(error)),
1357      Err::Failure(error) => Err::Failure(map_error(error)),
1358      Err::Incomplete(needed) => Err::Incomplete(needed),
1359    })
1360}
1361
1362impl<I, S> InputTakeAtPosition for Stateful<I, S>
1363where
1364  I: InputTakeAtPosition,
1365  S: Clone,
1366{
1367  type Item = <I as InputTakeAtPosition>::Item;
1368
1369  fn split_at_position_complete<P, E>(&self, predicate: P) -> IResult<Self, Self, E>
1370  where
1371    P: Fn(Self::Item) -> bool,
1372    E: ParseError<Self>,
1373  {
1374    stateful_clone_map_result(self, move |data| data.split_at_position_complete(predicate))
1375  }
1376
1377  fn split_at_position_streaming<P, E>(&self, predicate: P) -> IResult<Self, Self, E>
1378  where
1379    P: Fn(Self::Item) -> bool,
1380    E: ParseError<Self>,
1381  {
1382    stateful_clone_map_result(self, move |data| {
1383      data.split_at_position_streaming(predicate)
1384    })
1385  }
1386
1387  fn split_at_position1_streaming<P, E>(
1388    &self,
1389    predicate: P,
1390    kind: ErrorKind,
1391  ) -> IResult<Self, Self, E>
1392  where
1393    P: Fn(Self::Item) -> bool,
1394    E: ParseError<Self>,
1395  {
1396    stateful_clone_map_result(self, move |data| {
1397      data.split_at_position1_streaming(predicate, kind)
1398    })
1399  }
1400
1401  fn split_at_position1_complete<P, E>(
1402    &self,
1403    predicate: P,
1404    kind: ErrorKind,
1405  ) -> IResult<Self, Self, E>
1406  where
1407    P: Fn(Self::Item) -> bool,
1408    E: ParseError<Self>,
1409  {
1410    stateful_clone_map_result(self, move |data| {
1411      data.split_at_position1_complete(predicate, kind)
1412    })
1413  }
1414}
1415
1416fn stateful_clone_map_result<I, S, E, F>(
1417  input: &Stateful<I, S>,
1418  f: F,
1419) -> IResult<Stateful<I, S>, Stateful<I, S>, E>
1420where
1421  E: ParseError<Stateful<I, S>>,
1422  S: Clone,
1423  F: FnOnce(&I) -> IResult<I, I>,
1424{
1425  let map_error = |error: crate::error::Error<I>| {
1426    E::from_error_kind(
1427      Stateful {
1428        input: error.input,
1429        state: input.state.clone(),
1430      },
1431      error.code,
1432    )
1433  };
1434  f(&input.input)
1435    .map(|(remaining, output)| {
1436      (
1437        Stateful {
1438          input: remaining,
1439          state: input.state.clone(),
1440        },
1441        Stateful {
1442          input: output,
1443          state: input.state.clone(),
1444        },
1445      )
1446    })
1447    .map_err(|error| match error {
1448      Err::Error(error) => Err::Error(map_error(error)),
1449      Err::Failure(error) => Err::Failure(map_error(error)),
1450      Err::Incomplete(needed) => Err::Incomplete(needed),
1451    })
1452}
1453
1454impl<I> InputTakeAtPosition for Streaming<I>
1455where
1456  I: InputTakeAtPosition,
1457{
1458  type Item = <I as InputTakeAtPosition>::Item;
1459
1460  fn split_at_position_complete<P, E>(&self, predicate: P) -> IResult<Self, Self, E>
1461  where
1462    P: Fn(Self::Item) -> bool,
1463    E: ParseError<Self>,
1464  {
1465    streaming_clone_map_result(self, move |data| data.split_at_position_complete(predicate))
1466  }
1467
1468  fn split_at_position_streaming<P, E>(&self, predicate: P) -> IResult<Self, Self, E>
1469  where
1470    P: Fn(Self::Item) -> bool,
1471    E: ParseError<Self>,
1472  {
1473    streaming_clone_map_result(self, move |data| {
1474      data.split_at_position_streaming(predicate)
1475    })
1476  }
1477
1478  fn split_at_position1_streaming<P, E>(
1479    &self,
1480    predicate: P,
1481    kind: ErrorKind,
1482  ) -> IResult<Self, Self, E>
1483  where
1484    P: Fn(Self::Item) -> bool,
1485    E: ParseError<Self>,
1486  {
1487    streaming_clone_map_result(self, move |data| {
1488      data.split_at_position1_streaming(predicate, kind)
1489    })
1490  }
1491
1492  fn split_at_position1_complete<P, E>(
1493    &self,
1494    predicate: P,
1495    kind: ErrorKind,
1496  ) -> IResult<Self, Self, E>
1497  where
1498    P: Fn(Self::Item) -> bool,
1499    E: ParseError<Self>,
1500  {
1501    streaming_clone_map_result(self, move |data| {
1502      data.split_at_position1_complete(predicate, kind)
1503    })
1504  }
1505}
1506
1507fn streaming_clone_map_result<I, E, F>(
1508  input: &Streaming<I>,
1509  f: F,
1510) -> IResult<Streaming<I>, Streaming<I>, E>
1511where
1512  E: ParseError<Streaming<I>>,
1513  F: FnOnce(&I) -> IResult<I, I>,
1514{
1515  let map_error =
1516    |error: crate::error::Error<I>| E::from_error_kind(Streaming(error.input), error.code);
1517  f(&input.0)
1518    .map(|(remaining, output)| (Streaming(remaining), Streaming(output)))
1519    .map_err(|error| match error {
1520      Err::Error(error) => Err::Error(map_error(error)),
1521      Err::Failure(error) => Err::Failure(map_error(error)),
1522      Err::Incomplete(needed) => Err::Incomplete(needed),
1523    })
1524}
1525
1526impl<I: InputLength + InputIter + InputTake + Clone + UnspecializedInput> InputTakeAtPosition
1527  for I
1528{
1529  type Item = <I as InputIter>::Item;
1530
1531  fn split_at_position_streaming<P, E: ParseError<Self>>(
1532    &self,
1533    predicate: P,
1534  ) -> IResult<Self, Self, E>
1535  where
1536    P: Fn(Self::Item) -> bool,
1537  {
1538    match self.position(predicate) {
1539      Some(n) => Ok(self.take_split(n)),
1540      None => Err(Err::Incomplete(Needed::new(1))),
1541    }
1542  }
1543
1544  fn split_at_position1_streaming<P, E: ParseError<Self>>(
1545    &self,
1546    predicate: P,
1547    e: ErrorKind,
1548  ) -> IResult<Self, Self, E>
1549  where
1550    P: Fn(Self::Item) -> bool,
1551  {
1552    match self.position(predicate) {
1553      Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
1554      Some(n) => Ok(self.take_split(n)),
1555      None => Err(Err::Incomplete(Needed::new(1))),
1556    }
1557  }
1558
1559  fn split_at_position_complete<P, E: ParseError<Self>>(
1560    &self,
1561    predicate: P,
1562  ) -> IResult<Self, Self, E>
1563  where
1564    P: Fn(Self::Item) -> bool,
1565  {
1566    match self.position(predicate) {
1567      Some(n) => Ok(self.take_split(n)),
1568      None => Ok(self.take_split(self.input_len())),
1569    }
1570  }
1571
1572  fn split_at_position1_complete<P, E: ParseError<Self>>(
1573    &self,
1574    predicate: P,
1575    e: ErrorKind,
1576  ) -> IResult<Self, Self, E>
1577  where
1578    P: Fn(Self::Item) -> bool,
1579  {
1580    match self.position(predicate) {
1581      Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
1582      Some(n) => Ok(self.take_split(n)),
1583      None => {
1584        if self.input_len() == 0 {
1585          Err(Err::Error(E::from_error_kind(self.clone(), e)))
1586        } else {
1587          Ok(self.take_split(self.input_len()))
1588        }
1589      }
1590    }
1591  }
1592}
1593
1594impl<'a> InputTakeAtPosition for &'a [u8] {
1595  type Item = u8;
1596
1597  fn split_at_position_streaming<P, E: ParseError<Self>>(
1598    &self,
1599    predicate: P,
1600  ) -> IResult<Self, Self, E>
1601  where
1602    P: Fn(Self::Item) -> bool,
1603  {
1604    match self.iter().position(|c| predicate(*c)) {
1605      Some(i) => Ok(self.take_split(i)),
1606      None => Err(Err::Incomplete(Needed::new(1))),
1607    }
1608  }
1609
1610  fn split_at_position1_streaming<P, E: ParseError<Self>>(
1611    &self,
1612    predicate: P,
1613    e: ErrorKind,
1614  ) -> IResult<Self, Self, E>
1615  where
1616    P: Fn(Self::Item) -> bool,
1617  {
1618    match self.iter().position(|c| predicate(*c)) {
1619      Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
1620      Some(i) => Ok(self.take_split(i)),
1621      None => Err(Err::Incomplete(Needed::new(1))),
1622    }
1623  }
1624
1625  fn split_at_position_complete<P, E: ParseError<Self>>(
1626    &self,
1627    predicate: P,
1628  ) -> IResult<Self, Self, E>
1629  where
1630    P: Fn(Self::Item) -> bool,
1631  {
1632    match self.iter().position(|c| predicate(*c)) {
1633      Some(i) => Ok(self.take_split(i)),
1634      None => Ok(self.take_split(self.input_len())),
1635    }
1636  }
1637
1638  fn split_at_position1_complete<P, E: ParseError<Self>>(
1639    &self,
1640    predicate: P,
1641    e: ErrorKind,
1642  ) -> IResult<Self, Self, E>
1643  where
1644    P: Fn(Self::Item) -> bool,
1645  {
1646    match self.iter().position(|c| predicate(*c)) {
1647      Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
1648      Some(i) => Ok(self.take_split(i)),
1649      None => {
1650        if self.is_empty() {
1651          Err(Err::Error(E::from_error_kind(self, e)))
1652        } else {
1653          Ok(self.take_split(self.input_len()))
1654        }
1655      }
1656    }
1657  }
1658}
1659
1660impl<'a> InputTakeAtPosition for &'a str {
1661  type Item = char;
1662
1663  fn split_at_position_streaming<P, E: ParseError<Self>>(
1664    &self,
1665    predicate: P,
1666  ) -> IResult<Self, Self, E>
1667  where
1668    P: Fn(Self::Item) -> bool,
1669  {
1670    match self.find(predicate) {
1671      // find() returns a byte index that is already in the slice at a char boundary
1672      Some(i) => unsafe { Ok((self.get_unchecked(i..), self.get_unchecked(..i))) },
1673      None => Err(Err::Incomplete(Needed::new(1))),
1674    }
1675  }
1676
1677  fn split_at_position1_streaming<P, E: ParseError<Self>>(
1678    &self,
1679    predicate: P,
1680    e: ErrorKind,
1681  ) -> IResult<Self, Self, E>
1682  where
1683    P: Fn(Self::Item) -> bool,
1684  {
1685    match self.find(predicate) {
1686      Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
1687      // find() returns a byte index that is already in the slice at a char boundary
1688      Some(i) => unsafe { Ok((self.get_unchecked(i..), self.get_unchecked(..i))) },
1689      None => Err(Err::Incomplete(Needed::new(1))),
1690    }
1691  }
1692
1693  fn split_at_position_complete<P, E: ParseError<Self>>(
1694    &self,
1695    predicate: P,
1696  ) -> IResult<Self, Self, E>
1697  where
1698    P: Fn(Self::Item) -> bool,
1699  {
1700    match self.find(predicate) {
1701      // find() returns a byte index that is already in the slice at a char boundary
1702      Some(i) => unsafe { Ok((self.get_unchecked(i..), self.get_unchecked(..i))) },
1703      // the end of slice is a char boundary
1704      None => unsafe {
1705        Ok((
1706          self.get_unchecked(self.len()..),
1707          self.get_unchecked(..self.len()),
1708        ))
1709      },
1710    }
1711  }
1712
1713  fn split_at_position1_complete<P, E: ParseError<Self>>(
1714    &self,
1715    predicate: P,
1716    e: ErrorKind,
1717  ) -> IResult<Self, Self, E>
1718  where
1719    P: Fn(Self::Item) -> bool,
1720  {
1721    match self.find(predicate) {
1722      Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
1723      // find() returns a byte index that is already in the slice at a char boundary
1724      Some(i) => unsafe { Ok((self.get_unchecked(i..), self.get_unchecked(..i))) },
1725      None => {
1726        if self.is_empty() {
1727          Err(Err::Error(E::from_error_kind(self, e)))
1728        } else {
1729          // the end of slice is a char boundary
1730          unsafe {
1731            Ok((
1732              self.get_unchecked(self.len()..),
1733              self.get_unchecked(..self.len()),
1734            ))
1735          }
1736        }
1737      }
1738    }
1739  }
1740}
1741
1742/// Indicates whether a comparison was successful, an error, or
1743/// if more data was needed
1744#[derive(Debug, PartialEq)]
1745pub enum CompareResult {
1746  /// Comparison was successful
1747  Ok,
1748  /// We need more data to be sure
1749  Incomplete,
1750  /// Comparison failed
1751  Error,
1752}
1753
1754/// Abstracts comparison operations
1755pub trait Compare<T> {
1756  /// Compares self to another value for equality
1757  fn compare(&self, t: T) -> CompareResult;
1758  /// Compares self to another value for equality
1759  /// independently of the case.
1760  ///
1761  /// Warning: for `&str`, the comparison is done
1762  /// by lowercasing both strings and comparing
1763  /// the result. This is a temporary solution until
1764  /// a better one appears
1765  fn compare_no_case(&self, t: T) -> CompareResult;
1766}
1767
1768impl<I, U> Compare<U> for Located<I>
1769where
1770  I: Compare<U>,
1771{
1772  fn compare(&self, other: U) -> CompareResult {
1773    self.input.compare(other)
1774  }
1775
1776  fn compare_no_case(&self, other: U) -> CompareResult {
1777    self.input.compare_no_case(other)
1778  }
1779}
1780
1781impl<I, S, U> Compare<U> for Stateful<I, S>
1782where
1783  I: Compare<U>,
1784{
1785  fn compare(&self, other: U) -> CompareResult {
1786    self.input.compare(other)
1787  }
1788
1789  fn compare_no_case(&self, other: U) -> CompareResult {
1790    self.input.compare_no_case(other)
1791  }
1792}
1793
1794impl<I, T> Compare<T> for Streaming<I>
1795where
1796  I: Compare<T>,
1797{
1798  #[inline(always)]
1799  fn compare(&self, t: T) -> CompareResult {
1800    self.0.compare(t)
1801  }
1802
1803  #[inline(always)]
1804  fn compare_no_case(&self, t: T) -> CompareResult {
1805    self.0.compare_no_case(t)
1806  }
1807}
1808
1809fn lowercase_byte(c: u8) -> u8 {
1810  match c {
1811    b'A'..=b'Z' => c - b'A' + b'a',
1812    _ => c,
1813  }
1814}
1815
1816impl<'a, 'b> Compare<&'b [u8]> for &'a [u8] {
1817  #[inline(always)]
1818  fn compare(&self, t: &'b [u8]) -> CompareResult {
1819    let pos = self.iter().zip(t.iter()).position(|(a, b)| a != b);
1820
1821    match pos {
1822      Some(_) => CompareResult::Error,
1823      None => {
1824        if self.len() >= t.len() {
1825          CompareResult::Ok
1826        } else {
1827          CompareResult::Incomplete
1828        }
1829      }
1830    }
1831  }
1832
1833  #[inline(always)]
1834  fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
1835    if self
1836      .iter()
1837      .zip(t)
1838      .any(|(a, b)| lowercase_byte(*a) != lowercase_byte(*b))
1839    {
1840      CompareResult::Error
1841    } else if self.len() < t.len() {
1842      CompareResult::Incomplete
1843    } else {
1844      CompareResult::Ok
1845    }
1846  }
1847}
1848
1849impl<'a, 'b, const LEN: usize> Compare<&'b [u8; LEN]> for &'a [u8] {
1850  #[inline(always)]
1851  fn compare(&self, t: &'b [u8; LEN]) -> CompareResult {
1852    self.compare(&t[..])
1853  }
1854
1855  #[inline(always)]
1856  fn compare_no_case(&self, t: &'b [u8; LEN]) -> CompareResult {
1857    self.compare_no_case(&t[..])
1858  }
1859}
1860
1861impl<
1862    T: InputLength + InputIter<Item = u8> + InputTake + UnspecializedInput,
1863    O: InputLength + InputIter<Item = u8> + InputTake,
1864  > Compare<O> for T
1865{
1866  #[inline(always)]
1867  fn compare(&self, t: O) -> CompareResult {
1868    let pos = self
1869      .iter_elements()
1870      .zip(t.iter_elements())
1871      .position(|(a, b)| a != b);
1872
1873    match pos {
1874      Some(_) => CompareResult::Error,
1875      None => {
1876        if self.input_len() >= t.input_len() {
1877          CompareResult::Ok
1878        } else {
1879          CompareResult::Incomplete
1880        }
1881      }
1882    }
1883  }
1884
1885  #[inline(always)]
1886  fn compare_no_case(&self, t: O) -> CompareResult {
1887    if self
1888      .iter_elements()
1889      .zip(t.iter_elements())
1890      .any(|(a, b)| lowercase_byte(a) != lowercase_byte(b))
1891    {
1892      CompareResult::Error
1893    } else if self.input_len() < t.input_len() {
1894      CompareResult::Incomplete
1895    } else {
1896      CompareResult::Ok
1897    }
1898  }
1899}
1900
1901impl<'a, 'b> Compare<&'b str> for &'a [u8] {
1902  #[inline(always)]
1903  fn compare(&self, t: &'b str) -> CompareResult {
1904    self.compare(AsBytes::as_bytes(t))
1905  }
1906  #[inline(always)]
1907  fn compare_no_case(&self, t: &'b str) -> CompareResult {
1908    self.compare_no_case(AsBytes::as_bytes(t))
1909  }
1910}
1911
1912impl<'a, 'b> Compare<&'b str> for &'a str {
1913  #[inline(always)]
1914  fn compare(&self, t: &'b str) -> CompareResult {
1915    self.as_bytes().compare(t.as_bytes())
1916  }
1917
1918  //FIXME: this version is too simple and does not use the current locale
1919  #[inline(always)]
1920  fn compare_no_case(&self, t: &'b str) -> CompareResult {
1921    let pos = self
1922      .chars()
1923      .zip(t.chars())
1924      .position(|(a, b)| a.to_lowercase().ne(b.to_lowercase()));
1925
1926    match pos {
1927      Some(_) => CompareResult::Error,
1928      None => {
1929        if self.len() >= t.len() {
1930          CompareResult::Ok
1931        } else {
1932          CompareResult::Incomplete
1933        }
1934      }
1935    }
1936  }
1937}
1938
1939impl<'a, 'b> Compare<&'b [u8]> for &'a str {
1940  #[inline(always)]
1941  fn compare(&self, t: &'b [u8]) -> CompareResult {
1942    AsBytes::as_bytes(self).compare(t)
1943  }
1944  #[inline(always)]
1945  fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
1946    AsBytes::as_bytes(self).compare_no_case(t)
1947  }
1948}
1949
1950impl<'a, const LEN: usize> Compare<[u8; LEN]> for &'a [u8] {
1951  #[inline(always)]
1952  fn compare(&self, t: [u8; LEN]) -> CompareResult {
1953    self.compare(&t[..])
1954  }
1955
1956  #[inline(always)]
1957  fn compare_no_case(&self, t: [u8; LEN]) -> CompareResult {
1958    self.compare_no_case(&t[..])
1959  }
1960}
1961
1962/// Check if a token in in a set of possible tokens
1963///
1964/// This is generally implemented on patterns that a token may match and supports `u8` and `char`
1965/// tokens along with the following patterns
1966/// - `b'c'` and `'c'`
1967/// - `b""` and `""`
1968/// - `|c| true`
1969/// - `b'a'..=b'z'`, `'a'..='z'` (etc for each [range type][std::ops])
1970/// - `(pattern1, pattern2, ...)`
1971///
1972/// For example, you could implement `hex_digit0` as:
1973/// ```
1974/// # use nom8::prelude::*;
1975/// # use nom8::{Err, error::ErrorKind, error::Error, Needed};
1976/// # use nom8::bytes::take_while1;
1977/// fn hex_digit1(input: &str) -> IResult<&str, &str> {
1978///     take_while1(('a'..='f', 'A'..='F', '0'..='9')).parse(input)
1979/// }
1980///
1981/// assert_eq!(hex_digit1("21cZ"), Ok(("Z", "21c")));
1982/// assert_eq!(hex_digit1("H2"), Err(Err::Error(Error::new("H2", ErrorKind::TakeWhile1))));
1983/// assert_eq!(hex_digit1(""), Err(Err::Error(Error::new("", ErrorKind::TakeWhile1))));
1984/// ```
1985pub trait FindToken<T> {
1986  /// Returns true if self contains the token
1987  fn find_token(&self, token: T) -> bool;
1988}
1989
1990impl<I, T> FindToken<T> for Streaming<I>
1991where
1992  I: FindToken<T>,
1993{
1994  #[inline(always)]
1995  fn find_token(&self, token: T) -> bool {
1996    self.0.find_token(token)
1997  }
1998}
1999
2000impl FindToken<u8> for u8 {
2001  fn find_token(&self, token: u8) -> bool {
2002    *self == token
2003  }
2004}
2005
2006impl<'a> FindToken<&'a u8> for u8 {
2007  fn find_token(&self, token: &u8) -> bool {
2008    self.find_token(*token)
2009  }
2010}
2011
2012impl FindToken<char> for u8 {
2013  fn find_token(&self, token: char) -> bool {
2014    self.as_char() == token
2015  }
2016}
2017
2018impl<'a> FindToken<&'a char> for u8 {
2019  fn find_token(&self, token: &char) -> bool {
2020    self.find_token(*token)
2021  }
2022}
2023
2024impl<C: AsChar> FindToken<C> for char {
2025  fn find_token(&self, token: C) -> bool {
2026    *self == token.as_char()
2027  }
2028}
2029
2030impl<C: AsChar, F: Fn(C) -> bool> FindToken<C> for F {
2031  fn find_token(&self, token: C) -> bool {
2032    self(token)
2033  }
2034}
2035
2036impl<C1: AsChar, C2: AsChar + Clone> FindToken<C1> for Range<C2> {
2037  fn find_token(&self, token: C1) -> bool {
2038    let start = self.start.clone().as_char();
2039    let end = self.end.clone().as_char();
2040    (start..end).contains(&token.as_char())
2041  }
2042}
2043
2044impl<C1: AsChar, C2: AsChar + Clone> FindToken<C1> for RangeInclusive<C2> {
2045  fn find_token(&self, token: C1) -> bool {
2046    let start = self.start().clone().as_char();
2047    let end = self.end().clone().as_char();
2048    (start..=end).contains(&token.as_char())
2049  }
2050}
2051
2052impl<C1: AsChar, C2: AsChar + Clone> FindToken<C1> for RangeFrom<C2> {
2053  fn find_token(&self, token: C1) -> bool {
2054    let start = self.start.clone().as_char();
2055    (start..).contains(&token.as_char())
2056  }
2057}
2058
2059impl<C1: AsChar, C2: AsChar + Clone> FindToken<C1> for RangeTo<C2> {
2060  fn find_token(&self, token: C1) -> bool {
2061    let end = self.end.clone().as_char();
2062    (..end).contains(&token.as_char())
2063  }
2064}
2065
2066impl<C1: AsChar, C2: AsChar + Clone> FindToken<C1> for RangeToInclusive<C2> {
2067  fn find_token(&self, token: C1) -> bool {
2068    let end = self.end.clone().as_char();
2069    (..=end).contains(&token.as_char())
2070  }
2071}
2072
2073impl<C1: AsChar> FindToken<C1> for RangeFull {
2074  fn find_token(&self, _token: C1) -> bool {
2075    true
2076  }
2077}
2078
2079impl<'a> FindToken<u8> for &'a [u8] {
2080  fn find_token(&self, token: u8) -> bool {
2081    memchr::memchr(token, self).is_some()
2082  }
2083}
2084
2085impl<'a, 'b> FindToken<&'a u8> for &'b [u8] {
2086  fn find_token(&self, token: &u8) -> bool {
2087    self.find_token(*token)
2088  }
2089}
2090
2091impl<'a> FindToken<char> for &'a [u8] {
2092  fn find_token(&self, token: char) -> bool {
2093    self.iter().any(|i| i.as_char() == token)
2094  }
2095}
2096
2097impl<'a, 'b> FindToken<&'a char> for &'b [u8] {
2098  fn find_token(&self, token: &char) -> bool {
2099    self.find_token(*token)
2100  }
2101}
2102
2103impl<const LEN: usize> FindToken<u8> for [u8; LEN] {
2104  fn find_token(&self, token: u8) -> bool {
2105    memchr::memchr(token, &self[..]).is_some()
2106  }
2107}
2108
2109impl<'a, const LEN: usize> FindToken<&'a u8> for [u8; LEN] {
2110  fn find_token(&self, token: &u8) -> bool {
2111    self.find_token(*token)
2112  }
2113}
2114
2115impl<'a, const LEN: usize> FindToken<char> for [u8; LEN] {
2116  fn find_token(&self, token: char) -> bool {
2117    self.iter().any(|i| i.as_char() == token)
2118  }
2119}
2120
2121impl<'a, const LEN: usize> FindToken<&'a char> for [u8; LEN] {
2122  fn find_token(&self, token: &char) -> bool {
2123    self.find_token(*token)
2124  }
2125}
2126
2127impl<'a> FindToken<u8> for &'a str {
2128  fn find_token(&self, token: u8) -> bool {
2129    self.as_bytes().find_token(token)
2130  }
2131}
2132
2133impl<'a, 'b> FindToken<&'a u8> for &'b str {
2134  fn find_token(&self, token: &u8) -> bool {
2135    self.as_bytes().find_token(token)
2136  }
2137}
2138
2139impl<'a> FindToken<char> for &'a str {
2140  fn find_token(&self, token: char) -> bool {
2141    self.chars().any(|i| i == token)
2142  }
2143}
2144
2145impl<'a, 'b> FindToken<&'a char> for &'b str {
2146  fn find_token(&self, token: &char) -> bool {
2147    self.find_token(*token)
2148  }
2149}
2150
2151impl<'a> FindToken<u8> for &'a [char] {
2152  fn find_token(&self, token: u8) -> bool {
2153    self.iter().any(|i| *i == token.as_char())
2154  }
2155}
2156
2157impl<'a, 'b> FindToken<&'a u8> for &'b [char] {
2158  fn find_token(&self, token: &u8) -> bool {
2159    self.find_token(*token)
2160  }
2161}
2162
2163impl<'a> FindToken<char> for &'a [char] {
2164  fn find_token(&self, token: char) -> bool {
2165    self.iter().any(|i| *i == token)
2166  }
2167}
2168
2169impl<'a, 'b> FindToken<&'a char> for &'b [char] {
2170  fn find_token(&self, token: &char) -> bool {
2171    self.find_token(*token)
2172  }
2173}
2174
2175impl<T> FindToken<T> for () {
2176  fn find_token(&self, _token: T) -> bool {
2177    false
2178  }
2179}
2180
2181macro_rules! impl_find_token_for_tuple {
2182  ($($haystack:ident),+) => (
2183    #[allow(non_snake_case)]
2184    impl<T, $($haystack),+> FindToken<T> for ($($haystack),+,)
2185    where
2186    T: Clone,
2187      $($haystack: FindToken<T>),+
2188    {
2189      fn find_token(&self, token: T) -> bool {
2190        let ($(ref $haystack),+,) = *self;
2191        $($haystack.find_token(token.clone()) || )+ false
2192      }
2193    }
2194  )
2195}
2196
2197macro_rules! impl_find_token_for_tuples {
2198    ($haystack1:ident, $($haystack:ident),+) => {
2199        impl_find_token_for_tuples!(__impl $haystack1; $($haystack),+);
2200    };
2201    (__impl $($haystack:ident),+; $haystack1:ident $(,$haystack2:ident)*) => {
2202        impl_find_token_for_tuple!($($haystack),+);
2203        impl_find_token_for_tuples!(__impl $($haystack),+, $haystack1; $($haystack2),*);
2204    };
2205    (__impl $($haystack:ident),+;) => {
2206        impl_find_token_for_tuple!($($haystack),+);
2207    }
2208}
2209
2210impl_find_token_for_tuples!(
2211  F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21
2212);
2213
2214/// Look for a substring in self
2215pub trait FindSubstring<T> {
2216  /// Returns the byte position of the substring if it is found
2217  fn find_substring(&self, substr: T) -> Option<usize>;
2218}
2219
2220impl<I, T> FindSubstring<T> for Located<I>
2221where
2222  I: FindSubstring<T>,
2223{
2224  #[inline(always)]
2225  fn find_substring(&self, substr: T) -> Option<usize> {
2226    self.input.find_substring(substr)
2227  }
2228}
2229
2230impl<I, S, T> FindSubstring<T> for Stateful<I, S>
2231where
2232  I: FindSubstring<T>,
2233{
2234  #[inline(always)]
2235  fn find_substring(&self, substr: T) -> Option<usize> {
2236    self.input.find_substring(substr)
2237  }
2238}
2239
2240impl<I, T> FindSubstring<T> for Streaming<I>
2241where
2242  I: FindSubstring<T>,
2243{
2244  #[inline(always)]
2245  fn find_substring(&self, substr: T) -> Option<usize> {
2246    self.0.find_substring(substr)
2247  }
2248}
2249
2250impl<'a, 'b> FindSubstring<&'b [u8]> for &'a [u8] {
2251  fn find_substring(&self, substr: &'b [u8]) -> Option<usize> {
2252    if substr.len() > self.len() {
2253      return None;
2254    }
2255
2256    let (&substr_first, substr_rest) = match substr.split_first() {
2257      Some(split) => split,
2258      // an empty substring is found at position 0
2259      // This matches the behavior of str.find("").
2260      None => return Some(0),
2261    };
2262
2263    if substr_rest.is_empty() {
2264      return memchr::memchr(substr_first, self);
2265    }
2266
2267    let mut offset = 0;
2268    let haystack = &self[..self.len() - substr_rest.len()];
2269
2270    while let Some(position) = memchr::memchr(substr_first, &haystack[offset..]) {
2271      offset += position;
2272      let next_offset = offset + 1;
2273      if &self[next_offset..][..substr_rest.len()] == substr_rest {
2274        return Some(offset);
2275      }
2276
2277      offset = next_offset;
2278    }
2279
2280    None
2281  }
2282}
2283
2284impl<'a, 'b> FindSubstring<&'b str> for &'a [u8] {
2285  fn find_substring(&self, substr: &'b str) -> Option<usize> {
2286    self.find_substring(AsBytes::as_bytes(substr))
2287  }
2288}
2289
2290impl<'a, 'b> FindSubstring<&'b str> for &'a str {
2291  //returns byte index
2292  fn find_substring(&self, substr: &'b str) -> Option<usize> {
2293    self.find(substr)
2294  }
2295}
2296
2297/// Used to integrate `str`'s `parse()` method
2298pub trait ParseTo<R> {
2299  /// Succeeds if `parse()` succeeded. The byte slice implementation
2300  /// will first convert it to a `&str`, then apply the `parse()` function
2301  fn parse_to(&self) -> Option<R>;
2302}
2303
2304impl<I, R> ParseTo<R> for Located<I>
2305where
2306  I: ParseTo<R>,
2307{
2308  #[inline(always)]
2309  fn parse_to(&self) -> Option<R> {
2310    self.input.parse_to()
2311  }
2312}
2313
2314impl<I, S, R> ParseTo<R> for Stateful<I, S>
2315where
2316  I: ParseTo<R>,
2317{
2318  #[inline(always)]
2319  fn parse_to(&self) -> Option<R> {
2320    self.input.parse_to()
2321  }
2322}
2323
2324impl<I, R> ParseTo<R> for Streaming<I>
2325where
2326  I: ParseTo<R>,
2327{
2328  #[inline(always)]
2329  fn parse_to(&self) -> Option<R> {
2330    self.0.parse_to()
2331  }
2332}
2333
2334impl<'a, R: FromStr> ParseTo<R> for &'a [u8] {
2335  fn parse_to(&self) -> Option<R> {
2336    from_utf8(self).ok().and_then(|s| s.parse().ok())
2337  }
2338}
2339
2340impl<'a, R: FromStr> ParseTo<R> for &'a str {
2341  fn parse_to(&self) -> Option<R> {
2342    self.parse().ok()
2343  }
2344}
2345
2346/// Slicing operations using ranges.
2347///
2348/// This trait is loosely based on
2349/// `Index`, but can actually return
2350/// something else than a `&[T]` or `&str`
2351pub trait Slice<R> {
2352  /// Slices self according to the range argument
2353  fn slice(&self, range: R) -> Self;
2354}
2355
2356impl<I, R> Slice<R> for Located<I>
2357where
2358  I: Slice<R> + Clone,
2359{
2360  #[inline(always)]
2361  fn slice(&self, range: R) -> Self {
2362    Located {
2363      initial: self.initial.clone(),
2364      input: self.input.slice(range),
2365    }
2366  }
2367}
2368
2369impl<I, S, R> Slice<R> for Stateful<I, S>
2370where
2371  I: Slice<R>,
2372  S: Clone,
2373{
2374  #[inline(always)]
2375  fn slice(&self, range: R) -> Self {
2376    Self {
2377      input: self.input.slice(range),
2378      state: self.state.clone(),
2379    }
2380  }
2381}
2382
2383impl<I, R> Slice<R> for Streaming<I>
2384where
2385  I: Slice<R>,
2386{
2387  #[inline(always)]
2388  fn slice(&self, range: R) -> Self {
2389    Streaming(self.0.slice(range))
2390  }
2391}
2392
2393macro_rules! impl_fn_slice {
2394  ( $ty:ty ) => {
2395    fn slice(&self, range: $ty) -> Self {
2396      &self[range]
2397    }
2398  };
2399}
2400
2401macro_rules! slice_range_impl {
2402  ( [ $for_type:ident ], $ty:ty ) => {
2403    impl<'a, $for_type> Slice<$ty> for &'a [$for_type] {
2404      impl_fn_slice!($ty);
2405    }
2406  };
2407  ( $for_type:ty, $ty:ty ) => {
2408    impl<'a> Slice<$ty> for &'a $for_type {
2409      impl_fn_slice!($ty);
2410    }
2411  };
2412}
2413
2414macro_rules! slice_ranges_impl {
2415  ( [ $for_type:ident ] ) => {
2416    slice_range_impl! {[$for_type], Range<usize>}
2417    slice_range_impl! {[$for_type], RangeTo<usize>}
2418    slice_range_impl! {[$for_type], RangeFrom<usize>}
2419    slice_range_impl! {[$for_type], RangeFull}
2420  };
2421  ( $for_type:ty ) => {
2422    slice_range_impl! {$for_type, Range<usize>}
2423    slice_range_impl! {$for_type, RangeTo<usize>}
2424    slice_range_impl! {$for_type, RangeFrom<usize>}
2425    slice_range_impl! {$for_type, RangeFull}
2426  };
2427}
2428
2429slice_ranges_impl! {[T]}
2430slice_ranges_impl! {str}
2431
2432/// Convert an `Input` into an appropriate `Output` type
2433pub trait IntoOutput {
2434  /// Output type
2435  type Output;
2436  /// Convert an `Input` into an appropriate `Output` type
2437  fn into_output(self) -> Self::Output;
2438  /// Convert an `Output` type to be used as `Input`
2439  fn merge_output(self, inner: Self::Output) -> Self;
2440}
2441
2442impl<I> IntoOutput for Located<I>
2443where
2444  I: IntoOutput,
2445{
2446  type Output = I::Output;
2447  #[inline]
2448  fn into_output(self) -> Self::Output {
2449    self.input.into_output()
2450  }
2451  #[inline]
2452  fn merge_output(mut self, inner: Self::Output) -> Self {
2453    self.input = I::merge_output(self.input, inner);
2454    self
2455  }
2456}
2457
2458impl<I, S> IntoOutput for Stateful<I, S>
2459where
2460  I: IntoOutput,
2461{
2462  type Output = I::Output;
2463  #[inline]
2464  fn into_output(self) -> Self::Output {
2465    self.input.into_output()
2466  }
2467  #[inline]
2468  fn merge_output(mut self, inner: Self::Output) -> Self {
2469    self.input = I::merge_output(self.input, inner);
2470    self
2471  }
2472}
2473
2474impl<I> IntoOutput for Streaming<I>
2475where
2476  I: IntoOutput,
2477{
2478  type Output = I::Output;
2479  #[inline]
2480  fn into_output(self) -> Self::Output {
2481    self.into_complete().into_output()
2482  }
2483  #[inline]
2484  fn merge_output(self, inner: Self::Output) -> Self {
2485    Streaming(I::merge_output(self.0, inner))
2486  }
2487}
2488
2489impl<'a, T> IntoOutput for &'a [T] {
2490  type Output = Self;
2491  #[inline]
2492  fn into_output(self) -> Self::Output {
2493    self
2494  }
2495  #[inline]
2496  fn merge_output(self, inner: Self::Output) -> Self {
2497    inner
2498  }
2499}
2500
2501impl<const LEN: usize> IntoOutput for [u8; LEN] {
2502  type Output = Self;
2503  #[inline]
2504  fn into_output(self) -> Self::Output {
2505    self
2506  }
2507  #[inline]
2508  fn merge_output(self, inner: Self::Output) -> Self {
2509    inner
2510  }
2511}
2512
2513impl<'a, const LEN: usize> IntoOutput for &'a [u8; LEN] {
2514  type Output = Self;
2515  #[inline]
2516  fn into_output(self) -> Self::Output {
2517    self
2518  }
2519  #[inline]
2520  fn merge_output(self, inner: Self::Output) -> Self {
2521    inner
2522  }
2523}
2524
2525impl<'a> IntoOutput for &'a str {
2526  type Output = Self;
2527  #[inline]
2528  fn into_output(self) -> Self::Output {
2529    self
2530  }
2531  #[inline]
2532  fn merge_output(self, inner: Self::Output) -> Self {
2533    inner
2534  }
2535}
2536
2537impl<'a> IntoOutput for (&'a [u8], usize) {
2538  type Output = Self;
2539  #[inline]
2540  fn into_output(self) -> Self::Output {
2541    self
2542  }
2543  #[inline]
2544  fn merge_output(self, inner: Self::Output) -> Self {
2545    inner
2546  }
2547}
2548
2549/// Abstracts something which can extend an `Extend`.
2550/// Used to build modified input slices in `escaped_transform`
2551pub trait ExtendInto {
2552  /// The current input type is a sequence of that `Item` type.
2553  ///
2554  /// Example: `u8` for `&[u8]` or `char` for `&str`
2555  type Item;
2556
2557  /// The type that will be produced
2558  type Extender;
2559
2560  /// Create a new `Extend` of the correct type
2561  fn new_builder(&self) -> Self::Extender;
2562  /// Accumulate the input into an accumulator
2563  fn extend_into(&self, acc: &mut Self::Extender);
2564}
2565
2566impl<I> ExtendInto for Located<I>
2567where
2568  I: ExtendInto,
2569{
2570  type Item = I::Item;
2571  type Extender = I::Extender;
2572
2573  fn new_builder(&self) -> Self::Extender {
2574    self.input.new_builder()
2575  }
2576
2577  fn extend_into(&self, extender: &mut Self::Extender) {
2578    self.input.extend_into(extender)
2579  }
2580}
2581
2582impl<I, S> ExtendInto for Stateful<I, S>
2583where
2584  I: ExtendInto,
2585{
2586  type Item = I::Item;
2587  type Extender = I::Extender;
2588
2589  fn new_builder(&self) -> Self::Extender {
2590    self.input.new_builder()
2591  }
2592
2593  fn extend_into(&self, extender: &mut Self::Extender) {
2594    self.input.extend_into(extender)
2595  }
2596}
2597
2598impl<I> ExtendInto for Streaming<I>
2599where
2600  I: ExtendInto,
2601{
2602  type Item = I::Item;
2603  type Extender = I::Extender;
2604
2605  #[inline(always)]
2606  fn new_builder(&self) -> Self::Extender {
2607    self.0.new_builder()
2608  }
2609  #[inline(always)]
2610  fn extend_into(&self, acc: &mut Self::Extender) {
2611    self.0.extend_into(acc)
2612  }
2613}
2614
2615#[cfg(feature = "alloc")]
2616impl ExtendInto for [u8] {
2617  type Item = u8;
2618  type Extender = Vec<u8>;
2619
2620  #[inline]
2621  fn new_builder(&self) -> Vec<u8> {
2622    Vec::new()
2623  }
2624  #[inline]
2625  fn extend_into(&self, acc: &mut Vec<u8>) {
2626    acc.extend(self.iter().cloned());
2627  }
2628}
2629
2630#[cfg(feature = "alloc")]
2631impl ExtendInto for &[u8] {
2632  type Item = u8;
2633  type Extender = Vec<u8>;
2634
2635  #[inline]
2636  fn new_builder(&self) -> Vec<u8> {
2637    Vec::new()
2638  }
2639  #[inline]
2640  fn extend_into(&self, acc: &mut Vec<u8>) {
2641    acc.extend_from_slice(self);
2642  }
2643}
2644
2645#[cfg(feature = "alloc")]
2646impl ExtendInto for str {
2647  type Item = char;
2648  type Extender = String;
2649
2650  #[inline]
2651  fn new_builder(&self) -> String {
2652    String::new()
2653  }
2654  #[inline]
2655  fn extend_into(&self, acc: &mut String) {
2656    acc.push_str(self);
2657  }
2658}
2659
2660#[cfg(feature = "alloc")]
2661impl ExtendInto for &str {
2662  type Item = char;
2663  type Extender = String;
2664
2665  #[inline]
2666  fn new_builder(&self) -> String {
2667    String::new()
2668  }
2669  #[inline]
2670  fn extend_into(&self, acc: &mut String) {
2671    acc.push_str(self);
2672  }
2673}
2674
2675/// Helper trait to convert numbers to usize.
2676///
2677/// By default, usize implements `From<u8>` and `From<u16>` but not
2678/// `From<u32>` and `From<u64>` because that would be invalid on some
2679/// platforms. This trait implements the conversion for platforms
2680/// with 32 and 64 bits pointer platforms
2681pub trait ToUsize {
2682  /// converts self to usize
2683  fn to_usize(&self) -> usize;
2684}
2685
2686impl ToUsize for u8 {
2687  #[inline]
2688  fn to_usize(&self) -> usize {
2689    *self as usize
2690  }
2691}
2692
2693impl ToUsize for u16 {
2694  #[inline]
2695  fn to_usize(&self) -> usize {
2696    *self as usize
2697  }
2698}
2699
2700impl ToUsize for usize {
2701  #[inline]
2702  fn to_usize(&self) -> usize {
2703    *self
2704  }
2705}
2706
2707#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
2708impl ToUsize for u32 {
2709  #[inline]
2710  fn to_usize(&self) -> usize {
2711    *self as usize
2712  }
2713}
2714
2715#[cfg(target_pointer_width = "64")]
2716impl ToUsize for u64 {
2717  #[inline]
2718  fn to_usize(&self) -> usize {
2719    *self as usize
2720  }
2721}
2722
2723/// Equivalent From implementation to avoid orphan rules in bits parsers
2724pub trait ErrorConvert<E> {
2725  /// Transform to another error type
2726  fn convert(self) -> E;
2727}
2728
2729impl<I> ErrorConvert<(I, ErrorKind)> for ((I, usize), ErrorKind) {
2730  fn convert(self) -> (I, ErrorKind) {
2731    ((self.0).0, self.1)
2732  }
2733}
2734
2735impl<I> ErrorConvert<((I, usize), ErrorKind)> for (I, ErrorKind) {
2736  fn convert(self) -> ((I, usize), ErrorKind) {
2737    ((self.0, 0), self.1)
2738  }
2739}
2740
2741use crate::error;
2742impl<I> ErrorConvert<error::Error<I>> for error::Error<(I, usize)> {
2743  fn convert(self) -> error::Error<I> {
2744    error::Error {
2745      input: self.input.0,
2746      code: self.code,
2747    }
2748  }
2749}
2750
2751impl<I> ErrorConvert<error::Error<(I, usize)>> for error::Error<I> {
2752  fn convert(self) -> error::Error<(I, usize)> {
2753    error::Error {
2754      input: (self.input, 0),
2755      code: self.code,
2756    }
2757  }
2758}
2759
2760#[cfg(feature = "alloc")]
2761impl<I> ErrorConvert<error::VerboseError<I>> for error::VerboseError<(I, usize)> {
2762  fn convert(self) -> error::VerboseError<I> {
2763    error::VerboseError {
2764      errors: self.errors.into_iter().map(|(i, e)| (i.0, e)).collect(),
2765    }
2766  }
2767}
2768
2769#[cfg(feature = "alloc")]
2770impl<I> ErrorConvert<error::VerboseError<(I, usize)>> for error::VerboseError<I> {
2771  fn convert(self) -> error::VerboseError<(I, usize)> {
2772    error::VerboseError {
2773      errors: self.errors.into_iter().map(|(i, e)| ((i, 0), e)).collect(),
2774    }
2775  }
2776}
2777
2778/// Helper trait to show a byte slice as a hex dump
2779#[cfg(feature = "std")]
2780pub trait HexDisplay {
2781  /// Converts the value of `self` to a hex dump, returning the owned
2782  /// `String`.
2783  fn to_hex(&self, chunk_size: usize) -> String;
2784
2785  /// Converts the value of `self` to a hex dump beginning at `from` address, returning the owned
2786  /// `String`.
2787  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String;
2788}
2789
2790#[cfg(feature = "std")]
2791static CHARS: &[u8] = b"0123456789abcdef";
2792
2793#[cfg(feature = "std")]
2794impl<I> HexDisplay for Located<I>
2795where
2796  I: HexDisplay,
2797{
2798  #[inline(always)]
2799  fn to_hex(&self, chunk_size: usize) -> String {
2800    self.input.to_hex(chunk_size)
2801  }
2802
2803  #[inline(always)]
2804  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
2805    self.input.to_hex_from(chunk_size, from)
2806  }
2807}
2808
2809#[cfg(feature = "std")]
2810impl<I, S> HexDisplay for Stateful<I, S>
2811where
2812  I: HexDisplay,
2813{
2814  #[inline(always)]
2815  fn to_hex(&self, chunk_size: usize) -> String {
2816    self.input.to_hex(chunk_size)
2817  }
2818
2819  #[inline(always)]
2820  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
2821    self.input.to_hex_from(chunk_size, from)
2822  }
2823}
2824
2825#[cfg(feature = "std")]
2826impl<I> HexDisplay for Streaming<I>
2827where
2828  I: HexDisplay,
2829{
2830  #[inline(always)]
2831  fn to_hex(&self, chunk_size: usize) -> String {
2832    self.0.to_hex(chunk_size)
2833  }
2834
2835  #[inline(always)]
2836  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
2837    self.0.to_hex_from(chunk_size, from)
2838  }
2839}
2840
2841#[cfg(feature = "std")]
2842impl HexDisplay for [u8] {
2843  #[allow(unused_variables)]
2844  fn to_hex(&self, chunk_size: usize) -> String {
2845    self.to_hex_from(chunk_size, 0)
2846  }
2847
2848  #[allow(unused_variables)]
2849  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
2850    let mut v = Vec::with_capacity(self.len() * 3);
2851    let mut i = from;
2852    for chunk in self.chunks(chunk_size) {
2853      let s = format!("{:08x}", i);
2854      for &ch in s.as_bytes().iter() {
2855        v.push(ch);
2856      }
2857      v.push(b'\t');
2858
2859      i += chunk_size;
2860
2861      for &byte in chunk {
2862        v.push(CHARS[(byte >> 4) as usize]);
2863        v.push(CHARS[(byte & 0xf) as usize]);
2864        v.push(b' ');
2865      }
2866      if chunk_size > chunk.len() {
2867        for j in 0..(chunk_size - chunk.len()) {
2868          v.push(b' ');
2869          v.push(b' ');
2870          v.push(b' ');
2871        }
2872      }
2873      v.push(b'\t');
2874
2875      for &byte in chunk {
2876        if (byte >= 32 && byte <= 126) || byte >= 128 {
2877          v.push(byte);
2878        } else {
2879          v.push(b'.');
2880        }
2881      }
2882      v.push(b'\n');
2883    }
2884
2885    String::from_utf8_lossy(&v[..]).into_owned()
2886  }
2887}
2888
2889#[cfg(feature = "std")]
2890impl HexDisplay for str {
2891  #[allow(unused_variables)]
2892  fn to_hex(&self, chunk_size: usize) -> String {
2893    self.to_hex_from(chunk_size, 0)
2894  }
2895
2896  #[allow(unused_variables)]
2897  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
2898    self.as_bytes().to_hex_from(chunk_size, from)
2899  }
2900}
2901
2902#[cfg(test)]
2903mod tests {
2904  use super::*;
2905
2906  #[test]
2907  fn test_offset_u8() {
2908    let s = b"abcd123";
2909    let a = &s[..];
2910    let b = &a[2..];
2911    let c = &a[..4];
2912    let d = &a[3..5];
2913    assert_eq!(a.offset(b), 2);
2914    assert_eq!(a.offset(c), 0);
2915    assert_eq!(a.offset(d), 3);
2916  }
2917
2918  #[test]
2919  fn test_offset_str() {
2920    let s = "abcřèÂßÇd123";
2921    let a = &s[..];
2922    let b = &a[7..];
2923    let c = &a[..5];
2924    let d = &a[5..9];
2925    assert_eq!(a.offset(b), 7);
2926    assert_eq!(a.offset(c), 0);
2927    assert_eq!(a.offset(d), 5);
2928  }
2929}