1 //! Stream capability for combinators to parse
2 //!
3 //! Stream types include:
4 //! - `&[u8]` and [`Bytes`] for binary data
5 //! - `&str` (aliased as [`Str`]) and [`BStr`] for UTF-8 data
6 //! - [`Located`] can track the location within the original buffer to report
7 //! [spans][crate::Parser::with_span]
8 //! - [`Stateful`] to thread global state through your parsers
9 //! - [`Partial`] can mark an input as partial buffer that is being streamed into
10 //! - [Custom stream types][crate::_topic::stream]
11
12 use core::hash::BuildHasher;
13 use core::num::NonZeroUsize;
14
15 use crate::ascii::Caseless as AsciiCaseless;
16 #[cfg(feature = "unstable-recover")]
17 use crate::error::FromRecoverableError;
18 use crate::error::Needed;
19 use crate::lib::std::iter::{Cloned, Enumerate};
20 use crate::lib::std::slice::Iter;
21 use crate::lib::std::str::from_utf8;
22 use crate::lib::std::str::CharIndices;
23 use crate::lib::std::str::FromStr;
24
25 #[allow(unused_imports)]
26 #[cfg(any(feature = "unstable-doc", feature = "unstable-recover"))]
27 use crate::error::ErrMode;
28
29 #[cfg(feature = "alloc")]
30 use crate::lib::std::collections::BTreeMap;
31 #[cfg(feature = "alloc")]
32 use crate::lib::std::collections::BTreeSet;
33 #[cfg(feature = "std")]
34 use crate::lib::std::collections::HashMap;
35 #[cfg(feature = "std")]
36 use crate::lib::std::collections::HashSet;
37 #[cfg(feature = "alloc")]
38 use crate::lib::std::string::String;
39 #[cfg(feature = "alloc")]
40 use crate::lib::std::vec::Vec;
41
42 mod impls;
43 #[cfg(test)]
44 mod tests;
45
46 /// UTF-8 Stream
47 pub type Str<'i> = &'i str;
48
49 /// Improved `Debug` experience for `&[u8]` byte streams
50 #[allow(clippy::derive_hash_xor_eq)]
51 #[derive(Hash)]
52 #[repr(transparent)]
53 pub struct Bytes([u8]);
54
55 impl Bytes {
56 /// Make a stream out of a byte slice-like.
57 #[inline]
new<B: ?Sized + AsRef<[u8]>>(bytes: &B) -> &Self58 pub fn new<B: ?Sized + AsRef<[u8]>>(bytes: &B) -> &Self {
59 Self::from_bytes(bytes.as_ref())
60 }
61
62 #[inline]
from_bytes(slice: &[u8]) -> &Self63 fn from_bytes(slice: &[u8]) -> &Self {
64 unsafe { crate::lib::std::mem::transmute(slice) }
65 }
66
67 #[inline]
as_bytes(&self) -> &[u8]68 fn as_bytes(&self) -> &[u8] {
69 &self.0
70 }
71 }
72
73 /// Improved `Debug` experience for `&[u8]` UTF-8-ish streams
74 #[allow(clippy::derive_hash_xor_eq)]
75 #[derive(Hash)]
76 #[repr(transparent)]
77 pub struct BStr([u8]);
78
79 impl BStr {
80 /// Make a stream out of a byte slice-like.
81 #[inline]
new<B: ?Sized + AsRef<[u8]>>(bytes: &B) -> &Self82 pub fn new<B: ?Sized + AsRef<[u8]>>(bytes: &B) -> &Self {
83 Self::from_bytes(bytes.as_ref())
84 }
85
86 #[inline]
from_bytes(slice: &[u8]) -> &Self87 fn from_bytes(slice: &[u8]) -> &Self {
88 unsafe { crate::lib::std::mem::transmute(slice) }
89 }
90
91 #[inline]
as_bytes(&self) -> &[u8]92 fn as_bytes(&self) -> &[u8] {
93 &self.0
94 }
95 }
96
97 /// Allow collecting the span of a parsed token
98 ///
99 /// Spans are tracked as a [`Range<usize>`] of byte offsets.
100 ///
101 /// Converting byte offsets to line or column numbers is left up to the user, as computing column
102 /// numbers requires domain knowledge (are columns byte-based, codepoint-based, or grapheme-based?)
103 /// and O(n) iteration over the input to determine codepoint and line boundaries.
104 ///
105 /// [The `line-span` crate](https://docs.rs/line-span/latest/line_span/) can help with converting
106 /// byte offsets to line numbers.
107 ///
108 /// See [`Parser::span`][crate::Parser::span] and [`Parser::with_span`][crate::Parser::with_span] for more details
109 #[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
110 #[doc(alias = "LocatedSpan")]
111 pub struct Located<I> {
112 initial: I,
113 input: I,
114 }
115
116 impl<I> Located<I>
117 where
118 I: Clone + Offset,
119 {
120 /// Wrap another Stream with span tracking
new(input: I) -> Self121 pub fn new(input: I) -> Self {
122 let initial = input.clone();
123 Self { initial, input }
124 }
125
location(&self) -> usize126 fn location(&self) -> usize {
127 self.input.offset_from(&self.initial)
128 }
129 }
130
131 impl<I> AsRef<I> for Located<I> {
132 #[inline(always)]
as_ref(&self) -> &I133 fn as_ref(&self) -> &I {
134 &self.input
135 }
136 }
137
138 impl<I> crate::lib::std::ops::Deref for Located<I> {
139 type Target = I;
140
141 #[inline(always)]
deref(&self) -> &Self::Target142 fn deref(&self) -> &Self::Target {
143 &self.input
144 }
145 }
146
147 impl<I: crate::lib::std::fmt::Display> crate::lib::std::fmt::Display for Located<I> {
fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result148 fn fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result {
149 self.input.fmt(f)
150 }
151 }
152
153 /// Allow recovering from parse errors, capturing them as the parser continues
154 ///
155 /// Generally, this will be used indirectly via
156 /// [`RecoverableParser::recoverable_parse`][crate::RecoverableParser::recoverable_parse].
157 #[cfg(feature = "unstable-recover")]
158 #[derive(Clone, Debug)]
159 pub struct Recoverable<I, E>
160 where
161 I: Stream,
162 {
163 input: I,
164 errors: Vec<E>,
165 is_recoverable: bool,
166 }
167
168 #[cfg(feature = "unstable-recover")]
169 impl<I, E> Recoverable<I, E>
170 where
171 I: Stream,
172 {
173 /// Track recoverable errors with the stream
new(input: I) -> Self174 pub fn new(input: I) -> Self {
175 Self {
176 input,
177 errors: Default::default(),
178 is_recoverable: true,
179 }
180 }
181
182 /// Act as a normal stream
unrecoverable(input: I) -> Self183 pub fn unrecoverable(input: I) -> Self {
184 Self {
185 input,
186 errors: Default::default(),
187 is_recoverable: false,
188 }
189 }
190
191 /// Access the current input and errors
into_parts(self) -> (I, Vec<E>)192 pub fn into_parts(self) -> (I, Vec<E>) {
193 (self.input, self.errors)
194 }
195 }
196
197 #[cfg(feature = "unstable-recover")]
198 impl<I, E> AsRef<I> for Recoverable<I, E>
199 where
200 I: Stream,
201 {
202 #[inline(always)]
as_ref(&self) -> &I203 fn as_ref(&self) -> &I {
204 &self.input
205 }
206 }
207
208 #[cfg(feature = "unstable-recover")]
209 impl<I, E> crate::lib::std::ops::Deref for Recoverable<I, E>
210 where
211 I: Stream,
212 {
213 type Target = I;
214
215 #[inline(always)]
deref(&self) -> &Self::Target216 fn deref(&self) -> &Self::Target {
217 &self.input
218 }
219 }
220
221 #[cfg(feature = "unstable-recover")]
222 impl<I: crate::lib::std::fmt::Display, E> crate::lib::std::fmt::Display for Recoverable<I, E>
223 where
224 I: Stream,
225 {
fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result226 fn fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result {
227 crate::lib::std::fmt::Display::fmt(&self.input, f)
228 }
229 }
230
231 /// Thread global state through your parsers
232 ///
233 /// Use cases
234 /// - Recursion checks
235 /// - Error recovery
236 /// - Debugging
237 ///
238 /// # Example
239 ///
240 /// ```
241 /// # use std::cell::Cell;
242 /// # use winnow::prelude::*;
243 /// # use winnow::stream::Stateful;
244 /// # use winnow::ascii::alpha1;
245 /// # type Error = ();
246 ///
247 /// #[derive(Clone, Debug)]
248 /// struct State<'s>(&'s Cell<u32>);
249 ///
250 /// impl<'s> State<'s> {
251 /// fn count(&self) {
252 /// self.0.set(self.0.get() + 1);
253 /// }
254 /// }
255 ///
256 /// type Stream<'is> = Stateful<&'is str, State<'is>>;
257 ///
258 /// fn word<'s>(i: &mut Stream<'s>) -> PResult<&'s str> {
259 /// i.state.count();
260 /// alpha1.parse_next(i)
261 /// }
262 ///
263 /// let data = "Hello";
264 /// let state = Cell::new(0);
265 /// let input = Stream { input: data, state: State(&state) };
266 /// let output = word.parse(input).unwrap();
267 /// assert_eq!(state.get(), 1);
268 /// ```
269 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
270 #[doc(alias = "LocatedSpan")]
271 pub struct Stateful<I, S> {
272 /// Inner input being wrapped in state
273 pub input: I,
274 /// User-provided state
275 pub state: S,
276 }
277
278 impl<I, S> AsRef<I> for Stateful<I, S> {
279 #[inline(always)]
as_ref(&self) -> &I280 fn as_ref(&self) -> &I {
281 &self.input
282 }
283 }
284
285 impl<I, S> crate::lib::std::ops::Deref for Stateful<I, S> {
286 type Target = I;
287
288 #[inline(always)]
deref(&self) -> &Self::Target289 fn deref(&self) -> &Self::Target {
290 self.as_ref()
291 }
292 }
293
294 impl<I: crate::lib::std::fmt::Display, S> crate::lib::std::fmt::Display for Stateful<I, S> {
fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result295 fn fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result {
296 self.input.fmt(f)
297 }
298 }
299
300 /// Mark the input as a partial buffer for streaming input.
301 ///
302 /// Complete input means that we already have all of the data. This will be the common case with
303 /// small files that can be read entirely to memory.
304 ///
305 /// In contrast, streaming input assumes that we might not have all of the data.
306 /// This can happen with some network protocol or large file parsers, where the
307 /// input buffer can be full and need to be resized or refilled.
308 /// - [`ErrMode::Incomplete`] will report how much more data is needed.
309 /// - [`Parser::complete_err`][crate::Parser::complete_err] transform [`ErrMode::Incomplete`] to
310 /// [`ErrMode::Backtrack`]
311 ///
312 /// See also [`StreamIsPartial`] to tell whether the input supports complete or partial parsing.
313 ///
314 /// See also [Special Topics: Parsing Partial Input][crate::_topic::partial].
315 ///
316 /// # Example
317 ///
318 /// Here is how it works in practice:
319 ///
320 /// ```rust
321 /// # use winnow::{PResult, error::ErrMode, error::Needed, error::{InputError, ErrorKind}, token, ascii, stream::Partial};
322 /// # use winnow::prelude::*;
323 ///
324 /// fn take_partial<'s>(i: &mut Partial<&'s [u8]>) -> PResult<&'s [u8], InputError<Partial<&'s [u8]>>> {
325 /// token::take(4u8).parse_next(i)
326 /// }
327 ///
328 /// fn take_complete<'s>(i: &mut &'s [u8]) -> PResult<&'s [u8], InputError<&'s [u8]>> {
329 /// token::take(4u8).parse_next(i)
330 /// }
331 ///
332 /// // both parsers will take 4 bytes as expected
333 /// assert_eq!(take_partial.parse_peek(Partial::new(&b"abcde"[..])), Ok((Partial::new(&b"e"[..]), &b"abcd"[..])));
334 /// assert_eq!(take_complete.parse_peek(&b"abcde"[..]), Ok((&b"e"[..], &b"abcd"[..])));
335 ///
336 /// // if the input is smaller than 4 bytes, the partial parser
337 /// // will return `Incomplete` to indicate that we need more data
338 /// assert_eq!(take_partial.parse_peek(Partial::new(&b"abc"[..])), Err(ErrMode::Incomplete(Needed::new(1))));
339 ///
340 /// // but the complete parser will return an error
341 /// assert_eq!(take_complete.parse_peek(&b"abc"[..]), Err(ErrMode::Backtrack(InputError::new(&b"abc"[..], ErrorKind::Slice))));
342 ///
343 /// // the alpha0 function recognizes 0 or more alphabetic characters
344 /// fn alpha0_partial<'s>(i: &mut Partial<&'s str>) -> PResult<&'s str, InputError<Partial<&'s str>>> {
345 /// ascii::alpha0.parse_next(i)
346 /// }
347 ///
348 /// fn alpha0_complete<'s>(i: &mut &'s str) -> PResult<&'s str, InputError<&'s str>> {
349 /// ascii::alpha0.parse_next(i)
350 /// }
351 ///
352 /// // if there's a clear limit to the recognized characters, both parsers work the same way
353 /// assert_eq!(alpha0_partial.parse_peek(Partial::new("abcd;")), Ok((Partial::new(";"), "abcd")));
354 /// assert_eq!(alpha0_complete.parse_peek("abcd;"), Ok((";", "abcd")));
355 ///
356 /// // but when there's no limit, the partial version returns `Incomplete`, because it cannot
357 /// // know if more input data should be recognized. The whole input could be "abcd;", or
358 /// // "abcde;"
359 /// assert_eq!(alpha0_partial.parse_peek(Partial::new("abcd")), Err(ErrMode::Incomplete(Needed::new(1))));
360 ///
361 /// // while the complete version knows that all of the data is there
362 /// assert_eq!(alpha0_complete.parse_peek("abcd"), Ok(("", "abcd")));
363 /// ```
364 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
365 pub struct Partial<I> {
366 input: I,
367 partial: bool,
368 }
369
370 impl<I> Partial<I>
371 where
372 I: StreamIsPartial,
373 {
374 /// Create a partial input
new(input: I) -> Self375 pub fn new(input: I) -> Self {
376 debug_assert!(
377 !I::is_partial_supported(),
378 "`Partial` can only wrap complete sources"
379 );
380 let partial = true;
381 Self { input, partial }
382 }
383
384 /// Extract the original [`Stream`]
385 #[inline(always)]
into_inner(self) -> I386 pub fn into_inner(self) -> I {
387 self.input
388 }
389 }
390
391 impl<I> Default for Partial<I>
392 where
393 I: Default + StreamIsPartial,
394 {
default() -> Self395 fn default() -> Self {
396 Self::new(I::default())
397 }
398 }
399
400 impl<I> crate::lib::std::ops::Deref for Partial<I> {
401 type Target = I;
402
403 #[inline(always)]
deref(&self) -> &Self::Target404 fn deref(&self) -> &Self::Target {
405 &self.input
406 }
407 }
408
409 impl<I: crate::lib::std::fmt::Display> crate::lib::std::fmt::Display for Partial<I> {
fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result410 fn fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result {
411 self.input.fmt(f)
412 }
413 }
414
415 /// Abstract method to calculate the input length
416 pub trait SliceLen {
417 /// Calculates the input length, as indicated by its name,
418 /// and the name of the trait itself
slice_len(&self) -> usize419 fn slice_len(&self) -> usize;
420 }
421
422 impl<S: SliceLen> SliceLen for AsciiCaseless<S> {
423 #[inline(always)]
slice_len(&self) -> usize424 fn slice_len(&self) -> usize {
425 self.0.slice_len()
426 }
427 }
428
429 impl<'a, T> SliceLen for &'a [T] {
430 #[inline]
slice_len(&self) -> usize431 fn slice_len(&self) -> usize {
432 self.len()
433 }
434 }
435
436 impl<T, const LEN: usize> SliceLen for [T; LEN] {
437 #[inline]
slice_len(&self) -> usize438 fn slice_len(&self) -> usize {
439 self.len()
440 }
441 }
442
443 impl<'a, T, const LEN: usize> SliceLen for &'a [T; LEN] {
444 #[inline]
slice_len(&self) -> usize445 fn slice_len(&self) -> usize {
446 self.len()
447 }
448 }
449
450 impl<'a> SliceLen for &'a str {
451 #[inline]
slice_len(&self) -> usize452 fn slice_len(&self) -> usize {
453 self.len()
454 }
455 }
456
457 impl SliceLen for char {
458 #[inline]
slice_len(&self) -> usize459 fn slice_len(&self) -> usize {
460 self.len_utf8()
461 }
462 }
463
464 impl<'a> SliceLen for &'a Bytes {
465 #[inline]
slice_len(&self) -> usize466 fn slice_len(&self) -> usize {
467 self.len()
468 }
469 }
470
471 impl<'a> SliceLen for &'a BStr {
472 #[inline]
slice_len(&self) -> usize473 fn slice_len(&self) -> usize {
474 self.len()
475 }
476 }
477
478 impl<I> SliceLen for (I, usize, usize)
479 where
480 I: SliceLen,
481 {
482 #[inline(always)]
slice_len(&self) -> usize483 fn slice_len(&self) -> usize {
484 self.0.slice_len() * 8 + self.2 - self.1
485 }
486 }
487
488 impl<I> SliceLen for Located<I>
489 where
490 I: SliceLen,
491 {
492 #[inline(always)]
slice_len(&self) -> usize493 fn slice_len(&self) -> usize {
494 self.input.slice_len()
495 }
496 }
497
498 #[cfg(feature = "unstable-recover")]
499 impl<I, E> SliceLen for Recoverable<I, E>
500 where
501 I: SliceLen,
502 I: Stream,
503 {
504 #[inline(always)]
slice_len(&self) -> usize505 fn slice_len(&self) -> usize {
506 self.input.slice_len()
507 }
508 }
509
510 impl<I, S> SliceLen for Stateful<I, S>
511 where
512 I: SliceLen,
513 {
514 #[inline(always)]
slice_len(&self) -> usize515 fn slice_len(&self) -> usize {
516 self.input.slice_len()
517 }
518 }
519
520 impl<I> SliceLen for Partial<I>
521 where
522 I: SliceLen,
523 {
524 #[inline(always)]
slice_len(&self) -> usize525 fn slice_len(&self) -> usize {
526 self.input.slice_len()
527 }
528 }
529
530 /// Core definition for parser input state
531 pub trait Stream: Offset<<Self as Stream>::Checkpoint> + crate::lib::std::fmt::Debug {
532 /// The smallest unit being parsed
533 ///
534 /// Example: `u8` for `&[u8]` or `char` for `&str`
535 type Token: crate::lib::std::fmt::Debug;
536 /// Sequence of `Token`s
537 ///
538 /// Example: `&[u8]` for `Located<&[u8]>` or `&str` for `Located<&str>`
539 type Slice: crate::lib::std::fmt::Debug;
540
541 /// Iterate with the offset from the current location
542 type IterOffsets: Iterator<Item = (usize, Self::Token)>;
543
544 /// A parse location within the stream
545 type Checkpoint: Offset + Clone + crate::lib::std::fmt::Debug;
546
547 /// Iterate with the offset from the current location
548 fn iter_offsets(&self) -> Self::IterOffsets;
549
550 /// Returns the offset to the end of the input
551 fn eof_offset(&self) -> usize;
552
553 /// Split off the next token from the input
554 fn next_token(&mut self) -> Option<Self::Token>;
555 /// Split off the next token from the input
556 #[inline(always)]
557 fn peek_token(&self) -> Option<(Self, Self::Token)>
558 where
559 Self: Clone,
560 {
561 let mut peek = self.clone();
562 let token = peek.next_token()?;
563 Some((peek, token))
564 }
565
566 /// Finds the offset of the next matching token
567 fn offset_for<P>(&self, predicate: P) -> Option<usize>
568 where
569 P: Fn(Self::Token) -> bool;
570 /// Get the offset for the number of `tokens` into the stream
571 ///
572 /// This means "0 tokens" will return `0` offset
573 fn offset_at(&self, tokens: usize) -> Result<usize, Needed>;
574 /// Split off a slice of tokens from the input
575 ///
576 /// **NOTE:** For inputs with variable width tokens, like `&str`'s `char`, `offset` might not correspond
577 /// with the number of tokens. To get a valid offset, use:
578 /// - [`Stream::eof_offset`]
579 /// - [`Stream::iter_offsets`]
580 /// - [`Stream::offset_for`]
581 /// - [`Stream::offset_at`]
582 ///
583 /// # Panic
584 ///
585 /// This will panic if
586 ///
587 /// * Indexes must be within bounds of the original input;
588 /// * Indexes must uphold invariants of the stream, like for `str` they must lie on UTF-8
589 /// sequence boundaries.
590 ///
591 fn next_slice(&mut self, offset: usize) -> Self::Slice;
592 /// Split off a slice of tokens from the input
593 #[inline(always)]
594 fn peek_slice(&self, offset: usize) -> (Self, Self::Slice)
595 where
596 Self: Clone,
597 {
598 let mut peek = self.clone();
599 let slice = peek.next_slice(offset);
600 (peek, slice)
601 }
602
603 /// Advance to the end of the stream
604 #[inline(always)]
605 fn finish(&mut self) -> Self::Slice {
606 self.next_slice(self.eof_offset())
607 }
608 /// Advance to the end of the stream
609 #[inline(always)]
610 fn peek_finish(&self) -> (Self, Self::Slice)
611 where
612 Self: Clone,
613 {
614 let mut peek = self.clone();
615 let slice = peek.finish();
616 (peek, slice)
617 }
618
619 /// Save the current parse location within the stream
620 fn checkpoint(&self) -> Self::Checkpoint;
621 /// Revert the stream to a prior [`Self::Checkpoint`]
622 ///
623 /// # Panic
624 ///
625 /// May panic if an invalid [`Self::Checkpoint`] is provided
626 fn reset(&mut self, checkpoint: Self::Checkpoint);
627
628 /// Return the inner-most stream
629 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug;
630 }
631
632 impl<'i, T> Stream for &'i [T]
633 where
634 T: Clone + crate::lib::std::fmt::Debug,
635 {
636 type Token = T;
637 type Slice = &'i [T];
638
639 type IterOffsets = Enumerate<Cloned<Iter<'i, T>>>;
640
641 type Checkpoint = Checkpoint<Self>;
642
643 #[inline(always)]
644 fn iter_offsets(&self) -> Self::IterOffsets {
645 self.iter().cloned().enumerate()
646 }
647 #[inline(always)]
648 fn eof_offset(&self) -> usize {
649 self.len()
650 }
651
652 #[inline(always)]
653 fn next_token(&mut self) -> Option<Self::Token> {
654 let (token, next) = self.split_first()?;
655 *self = next;
656 Some(token.clone())
657 }
658
659 #[inline(always)]
660 fn offset_for<P>(&self, predicate: P) -> Option<usize>
661 where
662 P: Fn(Self::Token) -> bool,
663 {
664 self.iter().position(|b| predicate(b.clone()))
665 }
666 #[inline(always)]
667 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
668 if let Some(needed) = tokens.checked_sub(self.len()).and_then(NonZeroUsize::new) {
669 Err(Needed::Size(needed))
670 } else {
671 Ok(tokens)
672 }
673 }
674 #[inline(always)]
675 fn next_slice(&mut self, offset: usize) -> Self::Slice {
676 let (slice, next) = self.split_at(offset);
677 *self = next;
678 slice
679 }
680
681 #[inline(always)]
682 fn checkpoint(&self) -> Self::Checkpoint {
683 Checkpoint(*self)
684 }
685 #[inline(always)]
686 fn reset(&mut self, checkpoint: Self::Checkpoint) {
687 *self = checkpoint.0;
688 }
689
690 #[inline(always)]
691 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
692 self
693 }
694 }
695
696 impl<'i> Stream for &'i str {
697 type Token = char;
698 type Slice = &'i str;
699
700 type IterOffsets = CharIndices<'i>;
701
702 type Checkpoint = Checkpoint<Self>;
703
704 #[inline(always)]
iter_offsets(&self) -> Self::IterOffsets705 fn iter_offsets(&self) -> Self::IterOffsets {
706 self.char_indices()
707 }
708 #[inline(always)]
eof_offset(&self) -> usize709 fn eof_offset(&self) -> usize {
710 self.len()
711 }
712
713 #[inline(always)]
next_token(&mut self) -> Option<Self::Token>714 fn next_token(&mut self) -> Option<Self::Token> {
715 let c = self.chars().next()?;
716 let offset = c.len();
717 *self = &self[offset..];
718 Some(c)
719 }
720
721 #[inline(always)]
offset_for<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Token) -> bool,722 fn offset_for<P>(&self, predicate: P) -> Option<usize>
723 where
724 P: Fn(Self::Token) -> bool,
725 {
726 for (o, c) in self.iter_offsets() {
727 if predicate(c) {
728 return Some(o);
729 }
730 }
731 None
732 }
733 #[inline]
offset_at(&self, tokens: usize) -> Result<usize, Needed>734 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
735 let mut cnt = 0;
736 for (offset, _) in self.iter_offsets() {
737 if cnt == tokens {
738 return Ok(offset);
739 }
740 cnt += 1;
741 }
742
743 if cnt == tokens {
744 Ok(self.eof_offset())
745 } else {
746 Err(Needed::Unknown)
747 }
748 }
749 #[inline(always)]
next_slice(&mut self, offset: usize) -> Self::Slice750 fn next_slice(&mut self, offset: usize) -> Self::Slice {
751 let (slice, next) = self.split_at(offset);
752 *self = next;
753 slice
754 }
755
756 #[inline(always)]
checkpoint(&self) -> Self::Checkpoint757 fn checkpoint(&self) -> Self::Checkpoint {
758 Checkpoint(*self)
759 }
760 #[inline(always)]
reset(&mut self, checkpoint: Self::Checkpoint)761 fn reset(&mut self, checkpoint: Self::Checkpoint) {
762 *self = checkpoint.0;
763 }
764
765 #[inline(always)]
raw(&self) -> &dyn crate::lib::std::fmt::Debug766 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
767 self
768 }
769 }
770
771 impl<'i> Stream for &'i Bytes {
772 type Token = u8;
773 type Slice = &'i [u8];
774
775 type IterOffsets = Enumerate<Cloned<Iter<'i, u8>>>;
776
777 type Checkpoint = Checkpoint<Self>;
778
779 #[inline(always)]
iter_offsets(&self) -> Self::IterOffsets780 fn iter_offsets(&self) -> Self::IterOffsets {
781 self.iter().cloned().enumerate()
782 }
783 #[inline(always)]
eof_offset(&self) -> usize784 fn eof_offset(&self) -> usize {
785 self.len()
786 }
787
788 #[inline(always)]
next_token(&mut self) -> Option<Self::Token>789 fn next_token(&mut self) -> Option<Self::Token> {
790 if self.is_empty() {
791 None
792 } else {
793 let token = self[0];
794 *self = &self[1..];
795 Some(token)
796 }
797 }
798
799 #[inline(always)]
offset_for<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Token) -> bool,800 fn offset_for<P>(&self, predicate: P) -> Option<usize>
801 where
802 P: Fn(Self::Token) -> bool,
803 {
804 self.iter().position(|b| predicate(*b))
805 }
806 #[inline(always)]
offset_at(&self, tokens: usize) -> Result<usize, Needed>807 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
808 if let Some(needed) = tokens.checked_sub(self.len()).and_then(NonZeroUsize::new) {
809 Err(Needed::Size(needed))
810 } else {
811 Ok(tokens)
812 }
813 }
814 #[inline(always)]
next_slice(&mut self, offset: usize) -> Self::Slice815 fn next_slice(&mut self, offset: usize) -> Self::Slice {
816 let (slice, next) = self.0.split_at(offset);
817 *self = Bytes::from_bytes(next);
818 slice
819 }
820
821 #[inline(always)]
checkpoint(&self) -> Self::Checkpoint822 fn checkpoint(&self) -> Self::Checkpoint {
823 Checkpoint(*self)
824 }
825 #[inline(always)]
reset(&mut self, checkpoint: Self::Checkpoint)826 fn reset(&mut self, checkpoint: Self::Checkpoint) {
827 *self = checkpoint.0;
828 }
829
830 #[inline(always)]
raw(&self) -> &dyn crate::lib::std::fmt::Debug831 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
832 self
833 }
834 }
835
836 impl<'i> Stream for &'i BStr {
837 type Token = u8;
838 type Slice = &'i [u8];
839
840 type IterOffsets = Enumerate<Cloned<Iter<'i, u8>>>;
841
842 type Checkpoint = Checkpoint<Self>;
843
844 #[inline(always)]
iter_offsets(&self) -> Self::IterOffsets845 fn iter_offsets(&self) -> Self::IterOffsets {
846 self.iter().cloned().enumerate()
847 }
848 #[inline(always)]
eof_offset(&self) -> usize849 fn eof_offset(&self) -> usize {
850 self.len()
851 }
852
853 #[inline(always)]
next_token(&mut self) -> Option<Self::Token>854 fn next_token(&mut self) -> Option<Self::Token> {
855 if self.is_empty() {
856 None
857 } else {
858 let token = self[0];
859 *self = &self[1..];
860 Some(token)
861 }
862 }
863
864 #[inline(always)]
offset_for<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Token) -> bool,865 fn offset_for<P>(&self, predicate: P) -> Option<usize>
866 where
867 P: Fn(Self::Token) -> bool,
868 {
869 self.iter().position(|b| predicate(*b))
870 }
871 #[inline(always)]
offset_at(&self, tokens: usize) -> Result<usize, Needed>872 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
873 if let Some(needed) = tokens.checked_sub(self.len()).and_then(NonZeroUsize::new) {
874 Err(Needed::Size(needed))
875 } else {
876 Ok(tokens)
877 }
878 }
879 #[inline(always)]
next_slice(&mut self, offset: usize) -> Self::Slice880 fn next_slice(&mut self, offset: usize) -> Self::Slice {
881 let (slice, next) = self.0.split_at(offset);
882 *self = BStr::from_bytes(next);
883 slice
884 }
885
886 #[inline(always)]
checkpoint(&self) -> Self::Checkpoint887 fn checkpoint(&self) -> Self::Checkpoint {
888 Checkpoint(*self)
889 }
890 #[inline(always)]
reset(&mut self, checkpoint: Self::Checkpoint)891 fn reset(&mut self, checkpoint: Self::Checkpoint) {
892 *self = checkpoint.0;
893 }
894
895 #[inline(always)]
raw(&self) -> &dyn crate::lib::std::fmt::Debug896 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
897 self
898 }
899 }
900
901 impl<I> Stream for (I, usize)
902 where
903 I: Stream<Token = u8> + Clone,
904 {
905 type Token = bool;
906 type Slice = (I::Slice, usize, usize);
907
908 type IterOffsets = BitOffsets<I>;
909
910 type Checkpoint = Checkpoint<(I::Checkpoint, usize)>;
911
912 #[inline(always)]
iter_offsets(&self) -> Self::IterOffsets913 fn iter_offsets(&self) -> Self::IterOffsets {
914 BitOffsets {
915 i: self.clone(),
916 o: 0,
917 }
918 }
919 #[inline(always)]
eof_offset(&self) -> usize920 fn eof_offset(&self) -> usize {
921 let offset = self.0.eof_offset() * 8;
922 if offset == 0 {
923 0
924 } else {
925 offset - self.1
926 }
927 }
928
929 #[inline(always)]
next_token(&mut self) -> Option<Self::Token>930 fn next_token(&mut self) -> Option<Self::Token> {
931 next_bit(self)
932 }
933
934 #[inline(always)]
offset_for<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Token) -> bool,935 fn offset_for<P>(&self, predicate: P) -> Option<usize>
936 where
937 P: Fn(Self::Token) -> bool,
938 {
939 self.iter_offsets()
940 .find_map(|(o, b)| predicate(b).then_some(o))
941 }
942 #[inline(always)]
offset_at(&self, tokens: usize) -> Result<usize, Needed>943 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
944 if let Some(needed) = tokens
945 .checked_sub(self.eof_offset())
946 .and_then(NonZeroUsize::new)
947 {
948 Err(Needed::Size(needed))
949 } else {
950 Ok(tokens)
951 }
952 }
953 #[inline(always)]
next_slice(&mut self, offset: usize) -> Self::Slice954 fn next_slice(&mut self, offset: usize) -> Self::Slice {
955 let byte_offset = (offset + self.1) / 8;
956 let end_offset = (offset + self.1) % 8;
957 let s = self.0.next_slice(byte_offset);
958 let start_offset = self.1;
959 self.1 = end_offset;
960 (s, start_offset, end_offset)
961 }
962
963 #[inline(always)]
checkpoint(&self) -> Self::Checkpoint964 fn checkpoint(&self) -> Self::Checkpoint {
965 Checkpoint((self.0.checkpoint(), self.1))
966 }
967 #[inline(always)]
reset(&mut self, checkpoint: Self::Checkpoint)968 fn reset(&mut self, checkpoint: Self::Checkpoint) {
969 self.0.reset(checkpoint.0 .0);
970 self.1 = checkpoint.0 .1;
971 }
972
973 #[inline(always)]
raw(&self) -> &dyn crate::lib::std::fmt::Debug974 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
975 &self.0
976 }
977 }
978
979 /// Iterator for [bit][crate::binary::bits] stream (`(I, usize)`)
980 pub struct BitOffsets<I> {
981 i: (I, usize),
982 o: usize,
983 }
984
985 impl<I> Iterator for BitOffsets<I>
986 where
987 I: Stream<Token = u8> + Clone,
988 {
989 type Item = (usize, bool);
next(&mut self) -> Option<Self::Item>990 fn next(&mut self) -> Option<Self::Item> {
991 let b = next_bit(&mut self.i)?;
992 let o = self.o;
993
994 self.o += 1;
995
996 Some((o, b))
997 }
998 }
999
next_bit<I>(i: &mut (I, usize)) -> Option<bool> where I: Stream<Token = u8> + Clone,1000 fn next_bit<I>(i: &mut (I, usize)) -> Option<bool>
1001 where
1002 I: Stream<Token = u8> + Clone,
1003 {
1004 if i.eof_offset() == 0 {
1005 return None;
1006 }
1007 let offset = i.1;
1008
1009 let mut next_i = i.0.clone();
1010 let byte = next_i.next_token()?;
1011 let bit = (byte >> offset) & 0x1 == 0x1;
1012
1013 let next_offset = offset + 1;
1014 if next_offset == 8 {
1015 i.0 = next_i;
1016 i.1 = 0;
1017 Some(bit)
1018 } else {
1019 i.1 = next_offset;
1020 Some(bit)
1021 }
1022 }
1023
1024 impl<I: Stream> Stream for Located<I> {
1025 type Token = <I as Stream>::Token;
1026 type Slice = <I as Stream>::Slice;
1027
1028 type IterOffsets = <I as Stream>::IterOffsets;
1029
1030 type Checkpoint = Checkpoint<I::Checkpoint>;
1031
1032 #[inline(always)]
iter_offsets(&self) -> Self::IterOffsets1033 fn iter_offsets(&self) -> Self::IterOffsets {
1034 self.input.iter_offsets()
1035 }
1036 #[inline(always)]
eof_offset(&self) -> usize1037 fn eof_offset(&self) -> usize {
1038 self.input.eof_offset()
1039 }
1040
1041 #[inline(always)]
next_token(&mut self) -> Option<Self::Token>1042 fn next_token(&mut self) -> Option<Self::Token> {
1043 self.input.next_token()
1044 }
1045
1046 #[inline(always)]
offset_for<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Token) -> bool,1047 fn offset_for<P>(&self, predicate: P) -> Option<usize>
1048 where
1049 P: Fn(Self::Token) -> bool,
1050 {
1051 self.input.offset_for(predicate)
1052 }
1053 #[inline(always)]
offset_at(&self, tokens: usize) -> Result<usize, Needed>1054 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
1055 self.input.offset_at(tokens)
1056 }
1057 #[inline(always)]
next_slice(&mut self, offset: usize) -> Self::Slice1058 fn next_slice(&mut self, offset: usize) -> Self::Slice {
1059 self.input.next_slice(offset)
1060 }
1061
1062 #[inline(always)]
checkpoint(&self) -> Self::Checkpoint1063 fn checkpoint(&self) -> Self::Checkpoint {
1064 Checkpoint(self.input.checkpoint())
1065 }
1066 #[inline(always)]
reset(&mut self, checkpoint: Self::Checkpoint)1067 fn reset(&mut self, checkpoint: Self::Checkpoint) {
1068 self.input.reset(checkpoint.0);
1069 }
1070
1071 #[inline(always)]
raw(&self) -> &dyn crate::lib::std::fmt::Debug1072 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
1073 &self.input
1074 }
1075 }
1076
1077 #[cfg(feature = "unstable-recover")]
1078 impl<I, E: crate::lib::std::fmt::Debug> Stream for Recoverable<I, E>
1079 where
1080 I: Stream,
1081 {
1082 type Token = <I as Stream>::Token;
1083 type Slice = <I as Stream>::Slice;
1084
1085 type IterOffsets = <I as Stream>::IterOffsets;
1086
1087 type Checkpoint = Checkpoint<I::Checkpoint>;
1088
1089 #[inline(always)]
iter_offsets(&self) -> Self::IterOffsets1090 fn iter_offsets(&self) -> Self::IterOffsets {
1091 self.input.iter_offsets()
1092 }
1093 #[inline(always)]
eof_offset(&self) -> usize1094 fn eof_offset(&self) -> usize {
1095 self.input.eof_offset()
1096 }
1097
1098 #[inline(always)]
next_token(&mut self) -> Option<Self::Token>1099 fn next_token(&mut self) -> Option<Self::Token> {
1100 self.input.next_token()
1101 }
1102
1103 #[inline(always)]
offset_for<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Token) -> bool,1104 fn offset_for<P>(&self, predicate: P) -> Option<usize>
1105 where
1106 P: Fn(Self::Token) -> bool,
1107 {
1108 self.input.offset_for(predicate)
1109 }
1110 #[inline(always)]
offset_at(&self, tokens: usize) -> Result<usize, Needed>1111 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
1112 self.input.offset_at(tokens)
1113 }
1114 #[inline(always)]
next_slice(&mut self, offset: usize) -> Self::Slice1115 fn next_slice(&mut self, offset: usize) -> Self::Slice {
1116 self.input.next_slice(offset)
1117 }
1118
1119 #[inline(always)]
checkpoint(&self) -> Self::Checkpoint1120 fn checkpoint(&self) -> Self::Checkpoint {
1121 Checkpoint(self.input.checkpoint())
1122 }
1123 #[inline(always)]
reset(&mut self, checkpoint: Self::Checkpoint)1124 fn reset(&mut self, checkpoint: Self::Checkpoint) {
1125 self.input.reset(checkpoint.0);
1126 }
1127
1128 #[inline(always)]
raw(&self) -> &dyn crate::lib::std::fmt::Debug1129 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
1130 &self.input
1131 }
1132 }
1133
1134 impl<I: Stream, S: crate::lib::std::fmt::Debug> Stream for Stateful<I, S> {
1135 type Token = <I as Stream>::Token;
1136 type Slice = <I as Stream>::Slice;
1137
1138 type IterOffsets = <I as Stream>::IterOffsets;
1139
1140 type Checkpoint = Checkpoint<I::Checkpoint>;
1141
1142 #[inline(always)]
iter_offsets(&self) -> Self::IterOffsets1143 fn iter_offsets(&self) -> Self::IterOffsets {
1144 self.input.iter_offsets()
1145 }
1146 #[inline(always)]
eof_offset(&self) -> usize1147 fn eof_offset(&self) -> usize {
1148 self.input.eof_offset()
1149 }
1150
1151 #[inline(always)]
next_token(&mut self) -> Option<Self::Token>1152 fn next_token(&mut self) -> Option<Self::Token> {
1153 self.input.next_token()
1154 }
1155
1156 #[inline(always)]
offset_for<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Token) -> bool,1157 fn offset_for<P>(&self, predicate: P) -> Option<usize>
1158 where
1159 P: Fn(Self::Token) -> bool,
1160 {
1161 self.input.offset_for(predicate)
1162 }
1163 #[inline(always)]
offset_at(&self, tokens: usize) -> Result<usize, Needed>1164 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
1165 self.input.offset_at(tokens)
1166 }
1167 #[inline(always)]
next_slice(&mut self, offset: usize) -> Self::Slice1168 fn next_slice(&mut self, offset: usize) -> Self::Slice {
1169 self.input.next_slice(offset)
1170 }
1171
1172 #[inline(always)]
checkpoint(&self) -> Self::Checkpoint1173 fn checkpoint(&self) -> Self::Checkpoint {
1174 Checkpoint(self.input.checkpoint())
1175 }
1176 #[inline(always)]
reset(&mut self, checkpoint: Self::Checkpoint)1177 fn reset(&mut self, checkpoint: Self::Checkpoint) {
1178 self.input.reset(checkpoint.0);
1179 }
1180
1181 #[inline(always)]
raw(&self) -> &dyn crate::lib::std::fmt::Debug1182 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
1183 &self.input
1184 }
1185 }
1186
1187 impl<I: Stream> Stream for Partial<I> {
1188 type Token = <I as Stream>::Token;
1189 type Slice = <I as Stream>::Slice;
1190
1191 type IterOffsets = <I as Stream>::IterOffsets;
1192
1193 type Checkpoint = Checkpoint<I::Checkpoint>;
1194
1195 #[inline(always)]
iter_offsets(&self) -> Self::IterOffsets1196 fn iter_offsets(&self) -> Self::IterOffsets {
1197 self.input.iter_offsets()
1198 }
1199 #[inline(always)]
eof_offset(&self) -> usize1200 fn eof_offset(&self) -> usize {
1201 self.input.eof_offset()
1202 }
1203
1204 #[inline(always)]
next_token(&mut self) -> Option<Self::Token>1205 fn next_token(&mut self) -> Option<Self::Token> {
1206 self.input.next_token()
1207 }
1208
1209 #[inline(always)]
offset_for<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Token) -> bool,1210 fn offset_for<P>(&self, predicate: P) -> Option<usize>
1211 where
1212 P: Fn(Self::Token) -> bool,
1213 {
1214 self.input.offset_for(predicate)
1215 }
1216 #[inline(always)]
offset_at(&self, tokens: usize) -> Result<usize, Needed>1217 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
1218 self.input.offset_at(tokens)
1219 }
1220 #[inline(always)]
next_slice(&mut self, offset: usize) -> Self::Slice1221 fn next_slice(&mut self, offset: usize) -> Self::Slice {
1222 self.input.next_slice(offset)
1223 }
1224
1225 #[inline(always)]
checkpoint(&self) -> Self::Checkpoint1226 fn checkpoint(&self) -> Self::Checkpoint {
1227 Checkpoint(self.input.checkpoint())
1228 }
1229 #[inline(always)]
reset(&mut self, checkpoint: Self::Checkpoint)1230 fn reset(&mut self, checkpoint: Self::Checkpoint) {
1231 self.input.reset(checkpoint.0);
1232 }
1233
1234 #[inline(always)]
raw(&self) -> &dyn crate::lib::std::fmt::Debug1235 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
1236 &self.input
1237 }
1238 }
1239
1240 /// Number of indices input has advanced since start of parsing
1241 ///
1242 /// See [`Located`] for adding location tracking to your [`Stream`]
1243 pub trait Location {
1244 /// Number of indices input has advanced since start of parsing
location(&self) -> usize1245 fn location(&self) -> usize;
1246 }
1247
1248 impl<I> Location for Located<I>
1249 where
1250 I: Clone + Offset,
1251 {
1252 #[inline(always)]
location(&self) -> usize1253 fn location(&self) -> usize {
1254 self.location()
1255 }
1256 }
1257
1258 #[cfg(feature = "unstable-recover")]
1259 impl<I, E> Location for Recoverable<I, E>
1260 where
1261 I: Location,
1262 I: Stream,
1263 {
1264 #[inline(always)]
location(&self) -> usize1265 fn location(&self) -> usize {
1266 self.input.location()
1267 }
1268 }
1269
1270 impl<I, S> Location for Stateful<I, S>
1271 where
1272 I: Location,
1273 {
1274 #[inline(always)]
location(&self) -> usize1275 fn location(&self) -> usize {
1276 self.input.location()
1277 }
1278 }
1279
1280 impl<I> Location for Partial<I>
1281 where
1282 I: Location,
1283 {
1284 #[inline(always)]
location(&self) -> usize1285 fn location(&self) -> usize {
1286 self.input.location()
1287 }
1288 }
1289
1290 /// Capture top-level errors in the middle of parsing so parsing can resume
1291 ///
1292 /// See [`Recoverable`] for adding error recovery tracking to your [`Stream`]
1293 #[cfg(feature = "unstable-recover")]
1294 pub trait Recover<E>: Stream {
1295 /// Capture a top-level error
1296 ///
1297 /// May return `Err(err)` if recovery is not possible (e.g. if [`Recover::is_recovery_supported`]
1298 /// returns `false`).
record_err( &mut self, token_start: &Self::Checkpoint, err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1299 fn record_err(
1300 &mut self,
1301 token_start: &Self::Checkpoint,
1302 err_start: &Self::Checkpoint,
1303 err: ErrMode<E>,
1304 ) -> Result<(), ErrMode<E>>;
1305
1306 /// Report whether the [`Stream`] can save off errors for recovery
is_recovery_supported() -> bool1307 fn is_recovery_supported() -> bool;
1308 }
1309
1310 #[cfg(feature = "unstable-recover")]
1311 impl<'a, T, E> Recover<E> for &'a [T]
1312 where
1313 &'a [T]: Stream,
1314 {
1315 #[inline(always)]
record_err( &mut self, _token_start: &Self::Checkpoint, _err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1316 fn record_err(
1317 &mut self,
1318 _token_start: &Self::Checkpoint,
1319 _err_start: &Self::Checkpoint,
1320 err: ErrMode<E>,
1321 ) -> Result<(), ErrMode<E>> {
1322 Err(err)
1323 }
1324
1325 /// Report whether the [`Stream`] can save off errors for recovery
1326 #[inline(always)]
is_recovery_supported() -> bool1327 fn is_recovery_supported() -> bool {
1328 false
1329 }
1330 }
1331
1332 #[cfg(feature = "unstable-recover")]
1333 impl<'a, E> Recover<E> for &'a str {
1334 #[inline(always)]
record_err( &mut self, _token_start: &Self::Checkpoint, _err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1335 fn record_err(
1336 &mut self,
1337 _token_start: &Self::Checkpoint,
1338 _err_start: &Self::Checkpoint,
1339 err: ErrMode<E>,
1340 ) -> Result<(), ErrMode<E>> {
1341 Err(err)
1342 }
1343
1344 /// Report whether the [`Stream`] can save off errors for recovery
1345 #[inline(always)]
is_recovery_supported() -> bool1346 fn is_recovery_supported() -> bool {
1347 false
1348 }
1349 }
1350
1351 #[cfg(feature = "unstable-recover")]
1352 impl<'a, E> Recover<E> for &'a Bytes {
1353 #[inline(always)]
record_err( &mut self, _token_start: &Self::Checkpoint, _err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1354 fn record_err(
1355 &mut self,
1356 _token_start: &Self::Checkpoint,
1357 _err_start: &Self::Checkpoint,
1358 err: ErrMode<E>,
1359 ) -> Result<(), ErrMode<E>> {
1360 Err(err)
1361 }
1362
1363 /// Report whether the [`Stream`] can save off errors for recovery
1364 #[inline(always)]
is_recovery_supported() -> bool1365 fn is_recovery_supported() -> bool {
1366 false
1367 }
1368 }
1369
1370 #[cfg(feature = "unstable-recover")]
1371 impl<'a, E> Recover<E> for &'a BStr {
1372 #[inline(always)]
record_err( &mut self, _token_start: &Self::Checkpoint, _err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1373 fn record_err(
1374 &mut self,
1375 _token_start: &Self::Checkpoint,
1376 _err_start: &Self::Checkpoint,
1377 err: ErrMode<E>,
1378 ) -> Result<(), ErrMode<E>> {
1379 Err(err)
1380 }
1381
1382 /// Report whether the [`Stream`] can save off errors for recovery
1383 #[inline(always)]
is_recovery_supported() -> bool1384 fn is_recovery_supported() -> bool {
1385 false
1386 }
1387 }
1388
1389 #[cfg(feature = "unstable-recover")]
1390 impl<I, E> Recover<E> for (I, usize)
1391 where
1392 I: Recover<E>,
1393 I: Stream<Token = u8> + Clone,
1394 {
1395 #[inline(always)]
record_err( &mut self, _token_start: &Self::Checkpoint, _err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1396 fn record_err(
1397 &mut self,
1398 _token_start: &Self::Checkpoint,
1399 _err_start: &Self::Checkpoint,
1400 err: ErrMode<E>,
1401 ) -> Result<(), ErrMode<E>> {
1402 Err(err)
1403 }
1404
1405 /// Report whether the [`Stream`] can save off errors for recovery
1406 #[inline(always)]
is_recovery_supported() -> bool1407 fn is_recovery_supported() -> bool {
1408 false
1409 }
1410 }
1411
1412 #[cfg(feature = "unstable-recover")]
1413 impl<I, E> Recover<E> for Located<I>
1414 where
1415 I: Recover<E>,
1416 I: Stream,
1417 {
1418 #[inline(always)]
record_err( &mut self, _token_start: &Self::Checkpoint, _err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1419 fn record_err(
1420 &mut self,
1421 _token_start: &Self::Checkpoint,
1422 _err_start: &Self::Checkpoint,
1423 err: ErrMode<E>,
1424 ) -> Result<(), ErrMode<E>> {
1425 Err(err)
1426 }
1427
1428 /// Report whether the [`Stream`] can save off errors for recovery
1429 #[inline(always)]
is_recovery_supported() -> bool1430 fn is_recovery_supported() -> bool {
1431 false
1432 }
1433 }
1434
1435 #[cfg(feature = "unstable-recover")]
1436 impl<I, E, R> Recover<E> for Recoverable<I, R>
1437 where
1438 I: Stream,
1439 R: FromRecoverableError<Self, E>,
1440 R: crate::lib::std::fmt::Debug,
1441 {
record_err( &mut self, token_start: &Self::Checkpoint, err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1442 fn record_err(
1443 &mut self,
1444 token_start: &Self::Checkpoint,
1445 err_start: &Self::Checkpoint,
1446 err: ErrMode<E>,
1447 ) -> Result<(), ErrMode<E>> {
1448 if self.is_recoverable {
1449 match err {
1450 ErrMode::Incomplete(need) => Err(ErrMode::Incomplete(need)),
1451 ErrMode::Backtrack(err) | ErrMode::Cut(err) => {
1452 self.errors
1453 .push(R::from_recoverable_error(token_start, err_start, self, err));
1454 Ok(())
1455 }
1456 }
1457 } else {
1458 Err(err)
1459 }
1460 }
1461
1462 /// Report whether the [`Stream`] can save off errors for recovery
1463 #[inline(always)]
is_recovery_supported() -> bool1464 fn is_recovery_supported() -> bool {
1465 true
1466 }
1467 }
1468
1469 #[cfg(feature = "unstable-recover")]
1470 impl<I, E, S> Recover<E> for Stateful<I, S>
1471 where
1472 I: Recover<E>,
1473 I: Stream,
1474 S: Clone + crate::lib::std::fmt::Debug,
1475 {
1476 #[inline(always)]
record_err( &mut self, _token_start: &Self::Checkpoint, _err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1477 fn record_err(
1478 &mut self,
1479 _token_start: &Self::Checkpoint,
1480 _err_start: &Self::Checkpoint,
1481 err: ErrMode<E>,
1482 ) -> Result<(), ErrMode<E>> {
1483 Err(err)
1484 }
1485
1486 /// Report whether the [`Stream`] can save off errors for recovery
1487 #[inline(always)]
is_recovery_supported() -> bool1488 fn is_recovery_supported() -> bool {
1489 false
1490 }
1491 }
1492
1493 #[cfg(feature = "unstable-recover")]
1494 impl<I, E> Recover<E> for Partial<I>
1495 where
1496 I: Recover<E>,
1497 I: Stream,
1498 {
1499 #[inline(always)]
record_err( &mut self, _token_start: &Self::Checkpoint, _err_start: &Self::Checkpoint, err: ErrMode<E>, ) -> Result<(), ErrMode<E>>1500 fn record_err(
1501 &mut self,
1502 _token_start: &Self::Checkpoint,
1503 _err_start: &Self::Checkpoint,
1504 err: ErrMode<E>,
1505 ) -> Result<(), ErrMode<E>> {
1506 Err(err)
1507 }
1508
1509 /// Report whether the [`Stream`] can save off errors for recovery
1510 #[inline(always)]
is_recovery_supported() -> bool1511 fn is_recovery_supported() -> bool {
1512 false
1513 }
1514 }
1515
1516 /// Marks the input as being the complete buffer or a partial buffer for streaming input
1517 ///
1518 /// See [`Partial`] for marking a presumed complete buffer type as a streaming buffer.
1519 pub trait StreamIsPartial: Sized {
1520 /// Whether the stream is currently partial or complete
1521 type PartialState;
1522
1523 /// Mark the stream is complete
1524 #[must_use]
complete(&mut self) -> Self::PartialState1525 fn complete(&mut self) -> Self::PartialState;
1526
1527 /// Restore the stream back to its previous state
restore_partial(&mut self, state: Self::PartialState)1528 fn restore_partial(&mut self, state: Self::PartialState);
1529
1530 /// Report whether the [`Stream`] is can ever be incomplete
is_partial_supported() -> bool1531 fn is_partial_supported() -> bool;
1532
1533 /// Report whether the [`Stream`] is currently incomplete
1534 #[inline(always)]
is_partial(&self) -> bool1535 fn is_partial(&self) -> bool {
1536 Self::is_partial_supported()
1537 }
1538 }
1539
1540 impl<'a, T> StreamIsPartial for &'a [T] {
1541 type PartialState = ();
1542
complete(&mut self) -> Self::PartialState1543 fn complete(&mut self) -> Self::PartialState {}
1544
restore_partial(&mut self, _state: Self::PartialState)1545 fn restore_partial(&mut self, _state: Self::PartialState) {}
1546
1547 #[inline(always)]
is_partial_supported() -> bool1548 fn is_partial_supported() -> bool {
1549 false
1550 }
1551 }
1552
1553 impl<'a> StreamIsPartial for &'a str {
1554 type PartialState = ();
1555
complete(&mut self) -> Self::PartialState1556 fn complete(&mut self) -> Self::PartialState {
1557 // Already complete
1558 }
1559
restore_partial(&mut self, _state: Self::PartialState)1560 fn restore_partial(&mut self, _state: Self::PartialState) {}
1561
1562 #[inline(always)]
is_partial_supported() -> bool1563 fn is_partial_supported() -> bool {
1564 false
1565 }
1566 }
1567
1568 impl<'a> StreamIsPartial for &'a Bytes {
1569 type PartialState = ();
1570
complete(&mut self) -> Self::PartialState1571 fn complete(&mut self) -> Self::PartialState {
1572 // Already complete
1573 }
1574
restore_partial(&mut self, _state: Self::PartialState)1575 fn restore_partial(&mut self, _state: Self::PartialState) {}
1576
1577 #[inline(always)]
is_partial_supported() -> bool1578 fn is_partial_supported() -> bool {
1579 false
1580 }
1581 }
1582
1583 impl<'a> StreamIsPartial for &'a BStr {
1584 type PartialState = ();
1585
complete(&mut self) -> Self::PartialState1586 fn complete(&mut self) -> Self::PartialState {
1587 // Already complete
1588 }
1589
restore_partial(&mut self, _state: Self::PartialState)1590 fn restore_partial(&mut self, _state: Self::PartialState) {}
1591
1592 #[inline(always)]
is_partial_supported() -> bool1593 fn is_partial_supported() -> bool {
1594 false
1595 }
1596 }
1597
1598 impl<I> StreamIsPartial for (I, usize)
1599 where
1600 I: StreamIsPartial,
1601 {
1602 type PartialState = I::PartialState;
1603
complete(&mut self) -> Self::PartialState1604 fn complete(&mut self) -> Self::PartialState {
1605 self.0.complete()
1606 }
1607
restore_partial(&mut self, state: Self::PartialState)1608 fn restore_partial(&mut self, state: Self::PartialState) {
1609 self.0.restore_partial(state);
1610 }
1611
1612 #[inline(always)]
is_partial_supported() -> bool1613 fn is_partial_supported() -> bool {
1614 I::is_partial_supported()
1615 }
1616
1617 #[inline(always)]
is_partial(&self) -> bool1618 fn is_partial(&self) -> bool {
1619 self.0.is_partial()
1620 }
1621 }
1622
1623 impl<I> StreamIsPartial for Located<I>
1624 where
1625 I: StreamIsPartial,
1626 {
1627 type PartialState = I::PartialState;
1628
complete(&mut self) -> Self::PartialState1629 fn complete(&mut self) -> Self::PartialState {
1630 self.input.complete()
1631 }
1632
restore_partial(&mut self, state: Self::PartialState)1633 fn restore_partial(&mut self, state: Self::PartialState) {
1634 self.input.restore_partial(state);
1635 }
1636
1637 #[inline(always)]
is_partial_supported() -> bool1638 fn is_partial_supported() -> bool {
1639 I::is_partial_supported()
1640 }
1641
1642 #[inline(always)]
is_partial(&self) -> bool1643 fn is_partial(&self) -> bool {
1644 self.input.is_partial()
1645 }
1646 }
1647
1648 #[cfg(feature = "unstable-recover")]
1649 impl<I, E> StreamIsPartial for Recoverable<I, E>
1650 where
1651 I: StreamIsPartial,
1652 I: Stream,
1653 {
1654 type PartialState = I::PartialState;
1655
complete(&mut self) -> Self::PartialState1656 fn complete(&mut self) -> Self::PartialState {
1657 self.input.complete()
1658 }
1659
restore_partial(&mut self, state: Self::PartialState)1660 fn restore_partial(&mut self, state: Self::PartialState) {
1661 self.input.restore_partial(state);
1662 }
1663
1664 #[inline(always)]
is_partial_supported() -> bool1665 fn is_partial_supported() -> bool {
1666 I::is_partial_supported()
1667 }
1668
1669 #[inline(always)]
is_partial(&self) -> bool1670 fn is_partial(&self) -> bool {
1671 self.input.is_partial()
1672 }
1673 }
1674
1675 impl<I, S> StreamIsPartial for Stateful<I, S>
1676 where
1677 I: StreamIsPartial,
1678 {
1679 type PartialState = I::PartialState;
1680
complete(&mut self) -> Self::PartialState1681 fn complete(&mut self) -> Self::PartialState {
1682 self.input.complete()
1683 }
1684
restore_partial(&mut self, state: Self::PartialState)1685 fn restore_partial(&mut self, state: Self::PartialState) {
1686 self.input.restore_partial(state);
1687 }
1688
1689 #[inline(always)]
is_partial_supported() -> bool1690 fn is_partial_supported() -> bool {
1691 I::is_partial_supported()
1692 }
1693
1694 #[inline(always)]
is_partial(&self) -> bool1695 fn is_partial(&self) -> bool {
1696 self.input.is_partial()
1697 }
1698 }
1699
1700 impl<I> StreamIsPartial for Partial<I>
1701 where
1702 I: StreamIsPartial,
1703 {
1704 type PartialState = bool;
1705
complete(&mut self) -> Self::PartialState1706 fn complete(&mut self) -> Self::PartialState {
1707 core::mem::replace(&mut self.partial, false)
1708 }
1709
restore_partial(&mut self, state: Self::PartialState)1710 fn restore_partial(&mut self, state: Self::PartialState) {
1711 self.partial = state;
1712 }
1713
1714 #[inline(always)]
is_partial_supported() -> bool1715 fn is_partial_supported() -> bool {
1716 true
1717 }
1718
1719 #[inline(always)]
is_partial(&self) -> bool1720 fn is_partial(&self) -> bool {
1721 self.partial
1722 }
1723 }
1724
1725 /// Useful functions to calculate the offset between slices and show a hexdump of a slice
1726 pub trait Offset<Start = Self> {
1727 /// Offset between the first byte of `start` and the first byte of `self`a
1728 ///
1729 /// **Note:** This is an offset, not an index, and may point to the end of input
1730 /// (`start.len()`) when `self` is exhausted.
offset_from(&self, start: &Start) -> usize1731 fn offset_from(&self, start: &Start) -> usize;
1732 }
1733
1734 impl<'a, T> Offset for &'a [T] {
1735 #[inline]
offset_from(&self, start: &Self) -> usize1736 fn offset_from(&self, start: &Self) -> usize {
1737 let fst = (*start).as_ptr();
1738 let snd = (*self).as_ptr();
1739
1740 debug_assert!(
1741 fst <= snd,
1742 "`Offset::offset_from({snd:?}, {fst:?})` only accepts slices of `self`"
1743 );
1744 (snd as usize - fst as usize) / crate::lib::std::mem::size_of::<T>()
1745 }
1746 }
1747
1748 impl<'a, T> Offset<<&'a [T] as Stream>::Checkpoint> for &'a [T]
1749 where
1750 T: Clone + crate::lib::std::fmt::Debug,
1751 {
1752 #[inline(always)]
offset_from(&self, other: &<&'a [T] as Stream>::Checkpoint) -> usize1753 fn offset_from(&self, other: &<&'a [T] as Stream>::Checkpoint) -> usize {
1754 self.checkpoint().offset_from(other)
1755 }
1756 }
1757
1758 impl<'a> Offset for &'a str {
1759 #[inline(always)]
offset_from(&self, start: &Self) -> usize1760 fn offset_from(&self, start: &Self) -> usize {
1761 self.as_bytes().offset_from(&start.as_bytes())
1762 }
1763 }
1764
1765 impl<'a> Offset<<&'a str as Stream>::Checkpoint> for &'a str {
1766 #[inline(always)]
offset_from(&self, other: &<&'a str as Stream>::Checkpoint) -> usize1767 fn offset_from(&self, other: &<&'a str as Stream>::Checkpoint) -> usize {
1768 self.checkpoint().offset_from(other)
1769 }
1770 }
1771
1772 impl<'a> Offset for &'a Bytes {
1773 #[inline(always)]
offset_from(&self, start: &Self) -> usize1774 fn offset_from(&self, start: &Self) -> usize {
1775 self.as_bytes().offset_from(&start.as_bytes())
1776 }
1777 }
1778
1779 impl<'a> Offset<<&'a Bytes as Stream>::Checkpoint> for &'a Bytes {
1780 #[inline(always)]
offset_from(&self, other: &<&'a Bytes as Stream>::Checkpoint) -> usize1781 fn offset_from(&self, other: &<&'a Bytes as Stream>::Checkpoint) -> usize {
1782 self.checkpoint().offset_from(other)
1783 }
1784 }
1785
1786 impl<'a> Offset for &'a BStr {
1787 #[inline(always)]
offset_from(&self, start: &Self) -> usize1788 fn offset_from(&self, start: &Self) -> usize {
1789 self.as_bytes().offset_from(&start.as_bytes())
1790 }
1791 }
1792
1793 impl<'a> Offset<<&'a BStr as Stream>::Checkpoint> for &'a BStr {
1794 #[inline(always)]
offset_from(&self, other: &<&'a BStr as Stream>::Checkpoint) -> usize1795 fn offset_from(&self, other: &<&'a BStr as Stream>::Checkpoint) -> usize {
1796 self.checkpoint().offset_from(other)
1797 }
1798 }
1799
1800 impl<I> Offset for (I, usize)
1801 where
1802 I: Offset,
1803 {
1804 #[inline(always)]
offset_from(&self, start: &Self) -> usize1805 fn offset_from(&self, start: &Self) -> usize {
1806 self.0.offset_from(&start.0) * 8 + self.1 - start.1
1807 }
1808 }
1809
1810 impl<I> Offset<<(I, usize) as Stream>::Checkpoint> for (I, usize)
1811 where
1812 I: Stream<Token = u8> + Clone,
1813 {
1814 #[inline(always)]
offset_from(&self, other: &<(I, usize) as Stream>::Checkpoint) -> usize1815 fn offset_from(&self, other: &<(I, usize) as Stream>::Checkpoint) -> usize {
1816 self.checkpoint().offset_from(other)
1817 }
1818 }
1819
1820 impl<I> Offset for Located<I>
1821 where
1822 I: Stream,
1823 {
1824 #[inline(always)]
offset_from(&self, other: &Self) -> usize1825 fn offset_from(&self, other: &Self) -> usize {
1826 self.offset_from(&other.checkpoint())
1827 }
1828 }
1829
1830 impl<I> Offset<<Located<I> as Stream>::Checkpoint> for Located<I>
1831 where
1832 I: Stream,
1833 {
1834 #[inline(always)]
offset_from(&self, other: &<Located<I> as Stream>::Checkpoint) -> usize1835 fn offset_from(&self, other: &<Located<I> as Stream>::Checkpoint) -> usize {
1836 self.checkpoint().offset_from(other)
1837 }
1838 }
1839
1840 #[cfg(feature = "unstable-recover")]
1841 impl<I, E> Offset for Recoverable<I, E>
1842 where
1843 I: Stream,
1844 E: crate::lib::std::fmt::Debug,
1845 {
1846 #[inline(always)]
offset_from(&self, other: &Self) -> usize1847 fn offset_from(&self, other: &Self) -> usize {
1848 self.offset_from(&other.checkpoint())
1849 }
1850 }
1851
1852 #[cfg(feature = "unstable-recover")]
1853 impl<I, E> Offset<<Recoverable<I, E> as Stream>::Checkpoint> for Recoverable<I, E>
1854 where
1855 I: Stream,
1856 E: crate::lib::std::fmt::Debug,
1857 {
1858 #[inline(always)]
offset_from(&self, other: &<Recoverable<I, E> as Stream>::Checkpoint) -> usize1859 fn offset_from(&self, other: &<Recoverable<I, E> as Stream>::Checkpoint) -> usize {
1860 self.checkpoint().offset_from(other)
1861 }
1862 }
1863
1864 impl<I, S> Offset for Stateful<I, S>
1865 where
1866 I: Stream,
1867 S: Clone + crate::lib::std::fmt::Debug,
1868 {
1869 #[inline(always)]
offset_from(&self, start: &Self) -> usize1870 fn offset_from(&self, start: &Self) -> usize {
1871 self.offset_from(&start.checkpoint())
1872 }
1873 }
1874
1875 impl<I, S> Offset<<Stateful<I, S> as Stream>::Checkpoint> for Stateful<I, S>
1876 where
1877 I: Stream,
1878 S: crate::lib::std::fmt::Debug,
1879 {
1880 #[inline(always)]
offset_from(&self, other: &<Stateful<I, S> as Stream>::Checkpoint) -> usize1881 fn offset_from(&self, other: &<Stateful<I, S> as Stream>::Checkpoint) -> usize {
1882 self.checkpoint().offset_from(other)
1883 }
1884 }
1885
1886 impl<I> Offset for Partial<I>
1887 where
1888 I: Stream,
1889 {
1890 #[inline(always)]
offset_from(&self, start: &Self) -> usize1891 fn offset_from(&self, start: &Self) -> usize {
1892 self.offset_from(&start.checkpoint())
1893 }
1894 }
1895
1896 impl<I> Offset<<Partial<I> as Stream>::Checkpoint> for Partial<I>
1897 where
1898 I: Stream,
1899 {
1900 #[inline(always)]
offset_from(&self, other: &<Partial<I> as Stream>::Checkpoint) -> usize1901 fn offset_from(&self, other: &<Partial<I> as Stream>::Checkpoint) -> usize {
1902 self.checkpoint().offset_from(other)
1903 }
1904 }
1905
1906 impl<I> Offset for Checkpoint<I>
1907 where
1908 I: Offset,
1909 {
1910 #[inline(always)]
offset_from(&self, start: &Self) -> usize1911 fn offset_from(&self, start: &Self) -> usize {
1912 self.0.offset_from(&start.0)
1913 }
1914 }
1915
1916 /// Helper trait for types that can be viewed as a byte slice
1917 pub trait AsBytes {
1918 /// Casts the input type to a byte slice
as_bytes(&self) -> &[u8]1919 fn as_bytes(&self) -> &[u8];
1920 }
1921
1922 impl<'a> AsBytes for &'a [u8] {
1923 #[inline(always)]
as_bytes(&self) -> &[u8]1924 fn as_bytes(&self) -> &[u8] {
1925 self
1926 }
1927 }
1928
1929 impl<'a> AsBytes for &'a Bytes {
1930 #[inline(always)]
as_bytes(&self) -> &[u8]1931 fn as_bytes(&self) -> &[u8] {
1932 (*self).as_bytes()
1933 }
1934 }
1935
1936 impl<I> AsBytes for Located<I>
1937 where
1938 I: AsBytes,
1939 {
1940 #[inline(always)]
as_bytes(&self) -> &[u8]1941 fn as_bytes(&self) -> &[u8] {
1942 self.input.as_bytes()
1943 }
1944 }
1945
1946 #[cfg(feature = "unstable-recover")]
1947 impl<I, E> AsBytes for Recoverable<I, E>
1948 where
1949 I: Stream,
1950 I: AsBytes,
1951 {
1952 #[inline(always)]
as_bytes(&self) -> &[u8]1953 fn as_bytes(&self) -> &[u8] {
1954 self.input.as_bytes()
1955 }
1956 }
1957
1958 impl<I, S> AsBytes for Stateful<I, S>
1959 where
1960 I: AsBytes,
1961 {
1962 #[inline(always)]
as_bytes(&self) -> &[u8]1963 fn as_bytes(&self) -> &[u8] {
1964 self.input.as_bytes()
1965 }
1966 }
1967
1968 impl<I> AsBytes for Partial<I>
1969 where
1970 I: AsBytes,
1971 {
1972 #[inline(always)]
as_bytes(&self) -> &[u8]1973 fn as_bytes(&self) -> &[u8] {
1974 self.input.as_bytes()
1975 }
1976 }
1977
1978 /// Helper trait for types that can be viewed as a byte slice
1979 pub trait AsBStr {
1980 /// Casts the input type to a byte slice
as_bstr(&self) -> &[u8]1981 fn as_bstr(&self) -> &[u8];
1982 }
1983
1984 impl<'a> AsBStr for &'a [u8] {
1985 #[inline(always)]
as_bstr(&self) -> &[u8]1986 fn as_bstr(&self) -> &[u8] {
1987 self
1988 }
1989 }
1990
1991 impl<'a> AsBStr for &'a BStr {
1992 #[inline(always)]
as_bstr(&self) -> &[u8]1993 fn as_bstr(&self) -> &[u8] {
1994 (*self).as_bytes()
1995 }
1996 }
1997
1998 impl<'a> AsBStr for &'a str {
1999 #[inline(always)]
as_bstr(&self) -> &[u8]2000 fn as_bstr(&self) -> &[u8] {
2001 (*self).as_bytes()
2002 }
2003 }
2004
2005 impl<I> AsBStr for Located<I>
2006 where
2007 I: AsBStr,
2008 {
2009 #[inline(always)]
as_bstr(&self) -> &[u8]2010 fn as_bstr(&self) -> &[u8] {
2011 self.input.as_bstr()
2012 }
2013 }
2014
2015 #[cfg(feature = "unstable-recover")]
2016 impl<I, E> AsBStr for Recoverable<I, E>
2017 where
2018 I: Stream,
2019 I: AsBStr,
2020 {
2021 #[inline(always)]
as_bstr(&self) -> &[u8]2022 fn as_bstr(&self) -> &[u8] {
2023 self.input.as_bstr()
2024 }
2025 }
2026
2027 impl<I, S> AsBStr for Stateful<I, S>
2028 where
2029 I: AsBStr,
2030 {
2031 #[inline(always)]
as_bstr(&self) -> &[u8]2032 fn as_bstr(&self) -> &[u8] {
2033 self.input.as_bstr()
2034 }
2035 }
2036
2037 impl<I> AsBStr for Partial<I>
2038 where
2039 I: AsBStr,
2040 {
2041 #[inline(always)]
as_bstr(&self) -> &[u8]2042 fn as_bstr(&self) -> &[u8] {
2043 self.input.as_bstr()
2044 }
2045 }
2046
2047 /// Result of [`Compare::compare`]
2048 #[derive(Debug, Eq, PartialEq)]
2049 pub enum CompareResult {
2050 /// Comparison was successful
2051 Ok,
2052 /// We need more data to be sure
2053 Incomplete,
2054 /// Comparison failed
2055 Error,
2056 }
2057
2058 /// Abstracts comparison operations
2059 pub trait Compare<T> {
2060 /// Compares self to another value for equality
compare(&self, t: T) -> CompareResult2061 fn compare(&self, t: T) -> CompareResult;
2062 /// Compares self to another value for equality
2063 /// independently of the case.
2064 ///
2065 /// Warning: for `&str`, the comparison is done
2066 /// by lowercasing both strings and comparing
2067 /// the result. This is a temporary solution until
2068 /// a better one appears
2069 #[deprecated(since = "0.5.20", note = "Replaced with `compare(ascii::Caseless(_))`")]
compare_no_case(&self, t: T) -> CompareResult2070 fn compare_no_case(&self, t: T) -> CompareResult;
2071 }
2072
2073 impl<'a, 'b> Compare<&'b [u8]> for &'a [u8] {
2074 #[inline]
compare(&self, t: &'b [u8]) -> CompareResult2075 fn compare(&self, t: &'b [u8]) -> CompareResult {
2076 if t.iter().zip(*self).any(|(a, b)| a != b) {
2077 CompareResult::Error
2078 } else if self.len() < t.slice_len() {
2079 CompareResult::Incomplete
2080 } else {
2081 CompareResult::Ok
2082 }
2083 }
2084
2085 #[inline(always)]
2086 #[allow(deprecated)]
compare_no_case(&self, t: &'b [u8]) -> CompareResult2087 fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
2088 self.compare(AsciiCaseless(t))
2089 }
2090 }
2091
2092 impl<'a, 'b> Compare<AsciiCaseless<&'b [u8]>> for &'a [u8] {
2093 #[inline]
compare(&self, t: AsciiCaseless<&'b [u8]>) -> CompareResult2094 fn compare(&self, t: AsciiCaseless<&'b [u8]>) -> CompareResult {
2095 if t.0
2096 .iter()
2097 .zip(*self)
2098 .any(|(a, b)| !a.eq_ignore_ascii_case(b))
2099 {
2100 CompareResult::Error
2101 } else if self.len() < t.slice_len() {
2102 CompareResult::Incomplete
2103 } else {
2104 CompareResult::Ok
2105 }
2106 }
2107
2108 #[inline(always)]
2109 #[allow(deprecated)]
compare_no_case(&self, t: AsciiCaseless<&'b [u8]>) -> CompareResult2110 fn compare_no_case(&self, t: AsciiCaseless<&'b [u8]>) -> CompareResult {
2111 self.compare(t)
2112 }
2113 }
2114
2115 impl<'a, const LEN: usize> Compare<[u8; LEN]> for &'a [u8] {
2116 #[inline(always)]
compare(&self, t: [u8; LEN]) -> CompareResult2117 fn compare(&self, t: [u8; LEN]) -> CompareResult {
2118 self.compare(&t[..])
2119 }
2120
2121 #[inline(always)]
2122 #[allow(deprecated)]
compare_no_case(&self, t: [u8; LEN]) -> CompareResult2123 fn compare_no_case(&self, t: [u8; LEN]) -> CompareResult {
2124 self.compare_no_case(&t[..])
2125 }
2126 }
2127
2128 impl<'a, const LEN: usize> Compare<AsciiCaseless<[u8; LEN]>> for &'a [u8] {
2129 #[inline(always)]
compare(&self, t: AsciiCaseless<[u8; LEN]>) -> CompareResult2130 fn compare(&self, t: AsciiCaseless<[u8; LEN]>) -> CompareResult {
2131 self.compare(AsciiCaseless(&t.0[..]))
2132 }
2133
2134 #[inline(always)]
2135 #[allow(deprecated)]
compare_no_case(&self, t: AsciiCaseless<[u8; LEN]>) -> CompareResult2136 fn compare_no_case(&self, t: AsciiCaseless<[u8; LEN]>) -> CompareResult {
2137 self.compare_no_case(AsciiCaseless(&t.0[..]))
2138 }
2139 }
2140
2141 impl<'a, 'b, const LEN: usize> Compare<&'b [u8; LEN]> for &'a [u8] {
2142 #[inline(always)]
compare(&self, t: &'b [u8; LEN]) -> CompareResult2143 fn compare(&self, t: &'b [u8; LEN]) -> CompareResult {
2144 self.compare(&t[..])
2145 }
2146
2147 #[inline(always)]
2148 #[allow(deprecated)]
compare_no_case(&self, t: &'b [u8; LEN]) -> CompareResult2149 fn compare_no_case(&self, t: &'b [u8; LEN]) -> CompareResult {
2150 self.compare_no_case(&t[..])
2151 }
2152 }
2153
2154 impl<'a, 'b, const LEN: usize> Compare<AsciiCaseless<&'b [u8; LEN]>> for &'a [u8] {
2155 #[inline(always)]
compare(&self, t: AsciiCaseless<&'b [u8; LEN]>) -> CompareResult2156 fn compare(&self, t: AsciiCaseless<&'b [u8; LEN]>) -> CompareResult {
2157 self.compare(AsciiCaseless(&t.0[..]))
2158 }
2159
2160 #[inline(always)]
2161 #[allow(deprecated)]
compare_no_case(&self, t: AsciiCaseless<&'b [u8; LEN]>) -> CompareResult2162 fn compare_no_case(&self, t: AsciiCaseless<&'b [u8; LEN]>) -> CompareResult {
2163 self.compare_no_case(AsciiCaseless(&t.0[..]))
2164 }
2165 }
2166
2167 impl<'a, 'b> Compare<&'b str> for &'a [u8] {
2168 #[inline(always)]
compare(&self, t: &'b str) -> CompareResult2169 fn compare(&self, t: &'b str) -> CompareResult {
2170 self.compare(t.as_bytes())
2171 }
2172 #[inline(always)]
2173 #[allow(deprecated)]
compare_no_case(&self, t: &'b str) -> CompareResult2174 fn compare_no_case(&self, t: &'b str) -> CompareResult {
2175 self.compare_no_case(t.as_bytes())
2176 }
2177 }
2178
2179 impl<'a, 'b> Compare<AsciiCaseless<&'b str>> for &'a [u8] {
2180 #[inline(always)]
compare(&self, t: AsciiCaseless<&'b str>) -> CompareResult2181 fn compare(&self, t: AsciiCaseless<&'b str>) -> CompareResult {
2182 self.compare(AsciiCaseless(t.0.as_bytes()))
2183 }
2184 #[inline(always)]
2185 #[allow(deprecated)]
compare_no_case(&self, t: AsciiCaseless<&'b str>) -> CompareResult2186 fn compare_no_case(&self, t: AsciiCaseless<&'b str>) -> CompareResult {
2187 self.compare_no_case(AsciiCaseless(t.0.as_bytes()))
2188 }
2189 }
2190
2191 impl<'a> Compare<char> for &'a [u8] {
2192 #[inline(always)]
compare(&self, t: char) -> CompareResult2193 fn compare(&self, t: char) -> CompareResult {
2194 self.compare(t.encode_utf8(&mut [0; 4]).as_bytes())
2195 }
2196
2197 #[inline(always)]
2198 #[allow(deprecated)]
compare_no_case(&self, t: char) -> CompareResult2199 fn compare_no_case(&self, t: char) -> CompareResult {
2200 self.compare_no_case(t.encode_utf8(&mut [0; 4]).as_bytes())
2201 }
2202 }
2203
2204 impl<'a> Compare<AsciiCaseless<char>> for &'a [u8] {
2205 #[inline]
compare(&self, t: AsciiCaseless<char>) -> CompareResult2206 fn compare(&self, t: AsciiCaseless<char>) -> CompareResult {
2207 self.compare(AsciiCaseless(t.0.encode_utf8(&mut [0; 4]).as_bytes()))
2208 }
2209
2210 #[inline(always)]
2211 #[allow(deprecated)]
compare_no_case(&self, t: AsciiCaseless<char>) -> CompareResult2212 fn compare_no_case(&self, t: AsciiCaseless<char>) -> CompareResult {
2213 self.compare_no_case(AsciiCaseless(t.0.encode_utf8(&mut [0; 4]).as_bytes()))
2214 }
2215 }
2216
2217 impl<'a, 'b> Compare<&'b str> for &'a str {
2218 #[inline(always)]
compare(&self, t: &'b str) -> CompareResult2219 fn compare(&self, t: &'b str) -> CompareResult {
2220 self.as_bytes().compare(t.as_bytes())
2221 }
2222
2223 #[inline]
2224 #[allow(deprecated)]
compare_no_case(&self, t: &'b str) -> CompareResult2225 fn compare_no_case(&self, t: &'b str) -> CompareResult {
2226 self.compare(AsciiCaseless(t))
2227 }
2228 }
2229
2230 impl<'a, 'b> Compare<AsciiCaseless<&'b str>> for &'a str {
2231 #[inline(always)]
compare(&self, t: AsciiCaseless<&'b str>) -> CompareResult2232 fn compare(&self, t: AsciiCaseless<&'b str>) -> CompareResult {
2233 self.as_bytes().compare(t.as_bytes())
2234 }
2235
2236 #[inline(always)]
2237 #[allow(deprecated)]
compare_no_case(&self, t: AsciiCaseless<&'b str>) -> CompareResult2238 fn compare_no_case(&self, t: AsciiCaseless<&'b str>) -> CompareResult {
2239 self.compare(t)
2240 }
2241 }
2242
2243 impl<'a> Compare<char> for &'a str {
2244 #[inline(always)]
compare(&self, t: char) -> CompareResult2245 fn compare(&self, t: char) -> CompareResult {
2246 self.compare(t.encode_utf8(&mut [0; 4]).as_bytes())
2247 }
2248
2249 #[inline(always)]
2250 #[allow(deprecated)]
compare_no_case(&self, t: char) -> CompareResult2251 fn compare_no_case(&self, t: char) -> CompareResult {
2252 self.compare_no_case(t.encode_utf8(&mut [0; 4]).as_bytes())
2253 }
2254 }
2255
2256 impl<'a> Compare<AsciiCaseless<char>> for &'a str {
2257 #[inline]
compare(&self, t: AsciiCaseless<char>) -> CompareResult2258 fn compare(&self, t: AsciiCaseless<char>) -> CompareResult {
2259 self.compare(AsciiCaseless(t.0.encode_utf8(&mut [0; 4]).as_bytes()))
2260 }
2261
2262 #[inline(always)]
2263 #[allow(deprecated)]
compare_no_case(&self, t: AsciiCaseless<char>) -> CompareResult2264 fn compare_no_case(&self, t: AsciiCaseless<char>) -> CompareResult {
2265 self.compare_no_case(AsciiCaseless(t.0.encode_utf8(&mut [0; 4]).as_bytes()))
2266 }
2267 }
2268
2269 impl<'a, 'b> Compare<&'b [u8]> for &'a str {
2270 #[inline(always)]
compare(&self, t: &'b [u8]) -> CompareResult2271 fn compare(&self, t: &'b [u8]) -> CompareResult {
2272 AsBStr::as_bstr(self).compare(t)
2273 }
2274 #[inline(always)]
2275 #[allow(deprecated)]
compare_no_case(&self, t: &'b [u8]) -> CompareResult2276 fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
2277 AsBStr::as_bstr(self).compare_no_case(t)
2278 }
2279 }
2280
2281 impl<'a, 'b> Compare<AsciiCaseless<&'b [u8]>> for &'a str {
2282 #[inline(always)]
compare(&self, t: AsciiCaseless<&'b [u8]>) -> CompareResult2283 fn compare(&self, t: AsciiCaseless<&'b [u8]>) -> CompareResult {
2284 AsBStr::as_bstr(self).compare(t)
2285 }
2286 #[inline(always)]
2287 #[allow(deprecated)]
compare_no_case(&self, t: AsciiCaseless<&'b [u8]>) -> CompareResult2288 fn compare_no_case(&self, t: AsciiCaseless<&'b [u8]>) -> CompareResult {
2289 AsBStr::as_bstr(self).compare_no_case(t)
2290 }
2291 }
2292
2293 impl<'a, T> Compare<T> for &'a Bytes
2294 where
2295 &'a [u8]: Compare<T>,
2296 {
2297 #[inline(always)]
compare(&self, t: T) -> CompareResult2298 fn compare(&self, t: T) -> CompareResult {
2299 let bytes = (*self).as_bytes();
2300 bytes.compare(t)
2301 }
2302
2303 #[inline(always)]
2304 #[allow(deprecated)]
compare_no_case(&self, t: T) -> CompareResult2305 fn compare_no_case(&self, t: T) -> CompareResult {
2306 let bytes = (*self).as_bytes();
2307 bytes.compare_no_case(t)
2308 }
2309 }
2310
2311 impl<'a, T> Compare<T> for &'a BStr
2312 where
2313 &'a [u8]: Compare<T>,
2314 {
2315 #[inline(always)]
compare(&self, t: T) -> CompareResult2316 fn compare(&self, t: T) -> CompareResult {
2317 let bytes = (*self).as_bytes();
2318 bytes.compare(t)
2319 }
2320
2321 #[inline(always)]
2322 #[allow(deprecated)]
compare_no_case(&self, t: T) -> CompareResult2323 fn compare_no_case(&self, t: T) -> CompareResult {
2324 let bytes = (*self).as_bytes();
2325 bytes.compare_no_case(t)
2326 }
2327 }
2328
2329 impl<I, U> Compare<U> for Located<I>
2330 where
2331 I: Compare<U>,
2332 {
2333 #[inline(always)]
compare(&self, other: U) -> CompareResult2334 fn compare(&self, other: U) -> CompareResult {
2335 self.input.compare(other)
2336 }
2337
2338 #[inline(always)]
2339 #[allow(deprecated)]
compare_no_case(&self, other: U) -> CompareResult2340 fn compare_no_case(&self, other: U) -> CompareResult {
2341 self.input.compare_no_case(other)
2342 }
2343 }
2344
2345 #[cfg(feature = "unstable-recover")]
2346 impl<I, E, U> Compare<U> for Recoverable<I, E>
2347 where
2348 I: Stream,
2349 I: Compare<U>,
2350 {
2351 #[inline(always)]
compare(&self, other: U) -> CompareResult2352 fn compare(&self, other: U) -> CompareResult {
2353 self.input.compare(other)
2354 }
2355
2356 #[inline(always)]
2357 #[allow(deprecated)]
compare_no_case(&self, other: U) -> CompareResult2358 fn compare_no_case(&self, other: U) -> CompareResult {
2359 self.input.compare_no_case(other)
2360 }
2361 }
2362
2363 impl<I, S, U> Compare<U> for Stateful<I, S>
2364 where
2365 I: Compare<U>,
2366 {
2367 #[inline(always)]
compare(&self, other: U) -> CompareResult2368 fn compare(&self, other: U) -> CompareResult {
2369 self.input.compare(other)
2370 }
2371
2372 #[inline(always)]
2373 #[allow(deprecated)]
compare_no_case(&self, other: U) -> CompareResult2374 fn compare_no_case(&self, other: U) -> CompareResult {
2375 self.input.compare_no_case(other)
2376 }
2377 }
2378
2379 impl<I, T> Compare<T> for Partial<I>
2380 where
2381 I: Compare<T>,
2382 {
2383 #[inline(always)]
compare(&self, t: T) -> CompareResult2384 fn compare(&self, t: T) -> CompareResult {
2385 self.input.compare(t)
2386 }
2387
2388 #[inline(always)]
2389 #[allow(deprecated)]
compare_no_case(&self, t: T) -> CompareResult2390 fn compare_no_case(&self, t: T) -> CompareResult {
2391 self.input.compare_no_case(t)
2392 }
2393 }
2394
2395 /// Look for a slice in self
2396 pub trait FindSlice<T> {
2397 /// Returns the offset of the slice if it is found
find_slice(&self, substr: T) -> Option<usize>2398 fn find_slice(&self, substr: T) -> Option<usize>;
2399 }
2400
2401 impl<'i, 's> FindSlice<&'s [u8]> for &'i [u8] {
2402 #[inline(always)]
find_slice(&self, substr: &'s [u8]) -> Option<usize>2403 fn find_slice(&self, substr: &'s [u8]) -> Option<usize> {
2404 memmem(self, substr)
2405 }
2406 }
2407
2408 impl<'i, 's> FindSlice<(&'s [u8],)> for &'i [u8] {
2409 #[inline(always)]
find_slice(&self, substr: (&'s [u8],)) -> Option<usize>2410 fn find_slice(&self, substr: (&'s [u8],)) -> Option<usize> {
2411 memmem(self, substr.0)
2412 }
2413 }
2414
2415 impl<'i, 's> FindSlice<(&'s [u8], &'s [u8])> for &'i [u8] {
2416 #[inline(always)]
find_slice(&self, substr: (&'s [u8], &'s [u8])) -> Option<usize>2417 fn find_slice(&self, substr: (&'s [u8], &'s [u8])) -> Option<usize> {
2418 memmem2(self, substr)
2419 }
2420 }
2421
2422 impl<'i, 's> FindSlice<(&'s [u8], &'s [u8], &'s [u8])> for &'i [u8] {
2423 #[inline(always)]
find_slice(&self, substr: (&'s [u8], &'s [u8], &'s [u8])) -> Option<usize>2424 fn find_slice(&self, substr: (&'s [u8], &'s [u8], &'s [u8])) -> Option<usize> {
2425 memmem3(self, substr)
2426 }
2427 }
2428
2429 impl<'i> FindSlice<u8> for &'i [u8] {
2430 #[inline(always)]
find_slice(&self, substr: u8) -> Option<usize>2431 fn find_slice(&self, substr: u8) -> Option<usize> {
2432 memchr(substr, self)
2433 }
2434 }
2435
2436 impl<'i> FindSlice<(u8,)> for &'i [u8] {
2437 #[inline(always)]
find_slice(&self, substr: (u8,)) -> Option<usize>2438 fn find_slice(&self, substr: (u8,)) -> Option<usize> {
2439 memchr(substr.0, self)
2440 }
2441 }
2442
2443 impl<'i> FindSlice<(u8, u8)> for &'i [u8] {
2444 #[inline(always)]
find_slice(&self, substr: (u8, u8)) -> Option<usize>2445 fn find_slice(&self, substr: (u8, u8)) -> Option<usize> {
2446 memchr2(substr, self)
2447 }
2448 }
2449
2450 impl<'i> FindSlice<(u8, u8, u8)> for &'i [u8] {
2451 #[inline(always)]
find_slice(&self, substr: (u8, u8, u8)) -> Option<usize>2452 fn find_slice(&self, substr: (u8, u8, u8)) -> Option<usize> {
2453 memchr3(substr, self)
2454 }
2455 }
2456
2457 impl<'i, 's> FindSlice<&'s str> for &'i [u8] {
2458 #[inline(always)]
find_slice(&self, substr: &'s str) -> Option<usize>2459 fn find_slice(&self, substr: &'s str) -> Option<usize> {
2460 self.find_slice(substr.as_bytes())
2461 }
2462 }
2463
2464 impl<'i, 's> FindSlice<(&'s str,)> for &'i [u8] {
2465 #[inline(always)]
find_slice(&self, substr: (&'s str,)) -> Option<usize>2466 fn find_slice(&self, substr: (&'s str,)) -> Option<usize> {
2467 memmem(self, substr.0.as_bytes())
2468 }
2469 }
2470
2471 impl<'i, 's> FindSlice<(&'s str, &'s str)> for &'i [u8] {
2472 #[inline(always)]
find_slice(&self, substr: (&'s str, &'s str)) -> Option<usize>2473 fn find_slice(&self, substr: (&'s str, &'s str)) -> Option<usize> {
2474 memmem2(self, (substr.0.as_bytes(), substr.1.as_bytes()))
2475 }
2476 }
2477
2478 impl<'i, 's> FindSlice<(&'s str, &'s str, &'s str)> for &'i [u8] {
2479 #[inline(always)]
find_slice(&self, substr: (&'s str, &'s str, &'s str)) -> Option<usize>2480 fn find_slice(&self, substr: (&'s str, &'s str, &'s str)) -> Option<usize> {
2481 memmem3(
2482 self,
2483 (
2484 substr.0.as_bytes(),
2485 substr.1.as_bytes(),
2486 substr.2.as_bytes(),
2487 ),
2488 )
2489 }
2490 }
2491
2492 impl<'i, 's> FindSlice<&'s str> for &'i str {
2493 #[inline(always)]
find_slice(&self, substr: &'s str) -> Option<usize>2494 fn find_slice(&self, substr: &'s str) -> Option<usize> {
2495 self.as_bytes().find_slice(substr.as_bytes())
2496 }
2497 }
2498
2499 impl<'i, 's> FindSlice<(&'s str,)> for &'i str {
2500 #[inline(always)]
find_slice(&self, substr: (&'s str,)) -> Option<usize>2501 fn find_slice(&self, substr: (&'s str,)) -> Option<usize> {
2502 self.as_bytes().find_slice(substr)
2503 }
2504 }
2505
2506 impl<'i, 's> FindSlice<(&'s str, &'s str)> for &'i str {
2507 #[inline(always)]
find_slice(&self, substr: (&'s str, &'s str)) -> Option<usize>2508 fn find_slice(&self, substr: (&'s str, &'s str)) -> Option<usize> {
2509 self.as_bytes().find_slice(substr)
2510 }
2511 }
2512
2513 impl<'i, 's> FindSlice<(&'s str, &'s str, &'s str)> for &'i str {
2514 #[inline(always)]
find_slice(&self, substr: (&'s str, &'s str, &'s str)) -> Option<usize>2515 fn find_slice(&self, substr: (&'s str, &'s str, &'s str)) -> Option<usize> {
2516 self.as_bytes().find_slice(substr)
2517 }
2518 }
2519
2520 impl<'i> FindSlice<char> for &'i str {
2521 #[inline(always)]
find_slice(&self, substr: char) -> Option<usize>2522 fn find_slice(&self, substr: char) -> Option<usize> {
2523 let mut b = [0; 4];
2524 let substr = substr.encode_utf8(&mut b);
2525 self.find_slice(&*substr)
2526 }
2527 }
2528
2529 impl<'i> FindSlice<(char,)> for &'i str {
2530 #[inline(always)]
find_slice(&self, substr: (char,)) -> Option<usize>2531 fn find_slice(&self, substr: (char,)) -> Option<usize> {
2532 let mut b = [0; 4];
2533 let substr0 = substr.0.encode_utf8(&mut b);
2534 self.find_slice((&*substr0,))
2535 }
2536 }
2537
2538 impl<'i> FindSlice<(char, char)> for &'i str {
2539 #[inline(always)]
find_slice(&self, substr: (char, char)) -> Option<usize>2540 fn find_slice(&self, substr: (char, char)) -> Option<usize> {
2541 let mut b = [0; 4];
2542 let substr0 = substr.0.encode_utf8(&mut b);
2543 let mut b = [0; 4];
2544 let substr1 = substr.1.encode_utf8(&mut b);
2545 self.find_slice((&*substr0, &*substr1))
2546 }
2547 }
2548
2549 impl<'i> FindSlice<(char, char, char)> for &'i str {
2550 #[inline(always)]
find_slice(&self, substr: (char, char, char)) -> Option<usize>2551 fn find_slice(&self, substr: (char, char, char)) -> Option<usize> {
2552 let mut b = [0; 4];
2553 let substr0 = substr.0.encode_utf8(&mut b);
2554 let mut b = [0; 4];
2555 let substr1 = substr.1.encode_utf8(&mut b);
2556 let mut b = [0; 4];
2557 let substr2 = substr.2.encode_utf8(&mut b);
2558 self.find_slice((&*substr0, &*substr1, &*substr2))
2559 }
2560 }
2561
2562 impl<'i> FindSlice<u8> for &'i str {
2563 #[inline(always)]
find_slice(&self, substr: u8) -> Option<usize>2564 fn find_slice(&self, substr: u8) -> Option<usize> {
2565 self.find_slice(substr.as_char())
2566 }
2567 }
2568
2569 impl<'i> FindSlice<(u8,)> for &'i str {
2570 #[inline(always)]
find_slice(&self, substr: (u8,)) -> Option<usize>2571 fn find_slice(&self, substr: (u8,)) -> Option<usize> {
2572 self.find_slice((substr.0.as_char(),))
2573 }
2574 }
2575
2576 impl<'i> FindSlice<(u8, u8)> for &'i str {
2577 #[inline(always)]
find_slice(&self, substr: (u8, u8)) -> Option<usize>2578 fn find_slice(&self, substr: (u8, u8)) -> Option<usize> {
2579 self.find_slice((substr.0.as_char(), substr.1.as_char()))
2580 }
2581 }
2582
2583 impl<'i> FindSlice<(u8, u8, u8)> for &'i str {
2584 #[inline(always)]
find_slice(&self, substr: (u8, u8, u8)) -> Option<usize>2585 fn find_slice(&self, substr: (u8, u8, u8)) -> Option<usize> {
2586 self.find_slice((substr.0.as_char(), substr.1.as_char(), substr.2.as_char()))
2587 }
2588 }
2589
2590 impl<'i, S> FindSlice<S> for &'i Bytes
2591 where
2592 &'i [u8]: FindSlice<S>,
2593 {
2594 #[inline(always)]
find_slice(&self, substr: S) -> Option<usize>2595 fn find_slice(&self, substr: S) -> Option<usize> {
2596 let bytes = (*self).as_bytes();
2597 let offset = bytes.find_slice(substr);
2598 offset
2599 }
2600 }
2601
2602 impl<'i, S> FindSlice<S> for &'i BStr
2603 where
2604 &'i [u8]: FindSlice<S>,
2605 {
2606 #[inline(always)]
find_slice(&self, substr: S) -> Option<usize>2607 fn find_slice(&self, substr: S) -> Option<usize> {
2608 let bytes = (*self).as_bytes();
2609 let offset = bytes.find_slice(substr);
2610 offset
2611 }
2612 }
2613
2614 impl<I, T> FindSlice<T> for Located<I>
2615 where
2616 I: FindSlice<T>,
2617 {
2618 #[inline(always)]
find_slice(&self, substr: T) -> Option<usize>2619 fn find_slice(&self, substr: T) -> Option<usize> {
2620 self.input.find_slice(substr)
2621 }
2622 }
2623
2624 #[cfg(feature = "unstable-recover")]
2625 impl<I, E, T> FindSlice<T> for Recoverable<I, E>
2626 where
2627 I: Stream,
2628 I: FindSlice<T>,
2629 {
2630 #[inline(always)]
find_slice(&self, substr: T) -> Option<usize>2631 fn find_slice(&self, substr: T) -> Option<usize> {
2632 self.input.find_slice(substr)
2633 }
2634 }
2635
2636 impl<I, S, T> FindSlice<T> for Stateful<I, S>
2637 where
2638 I: FindSlice<T>,
2639 {
2640 #[inline(always)]
find_slice(&self, substr: T) -> Option<usize>2641 fn find_slice(&self, substr: T) -> Option<usize> {
2642 self.input.find_slice(substr)
2643 }
2644 }
2645
2646 impl<I, T> FindSlice<T> for Partial<I>
2647 where
2648 I: FindSlice<T>,
2649 {
2650 #[inline(always)]
find_slice(&self, substr: T) -> Option<usize>2651 fn find_slice(&self, substr: T) -> Option<usize> {
2652 self.input.find_slice(substr)
2653 }
2654 }
2655
2656 /// Used to integrate `str`'s `parse()` method
2657 pub trait ParseSlice<R> {
2658 /// Succeeds if `parse()` succeededThe
2659 ///
2660 /// The byte slice implementation will first convert it to a `&str`, then apply the `parse()`
2661 /// function
parse_slice(&self) -> Option<R>2662 fn parse_slice(&self) -> Option<R>;
2663 }
2664
2665 impl<'a, R: FromStr> ParseSlice<R> for &'a [u8] {
2666 #[inline(always)]
parse_slice(&self) -> Option<R>2667 fn parse_slice(&self) -> Option<R> {
2668 from_utf8(self).ok().and_then(|s| s.parse().ok())
2669 }
2670 }
2671
2672 impl<'a, R: FromStr> ParseSlice<R> for &'a str {
2673 #[inline(always)]
parse_slice(&self) -> Option<R>2674 fn parse_slice(&self) -> Option<R> {
2675 self.parse().ok()
2676 }
2677 }
2678
2679 /// Convert a `Stream` into an appropriate `Output` type
2680 pub trait UpdateSlice: Stream {
2681 /// Convert an `Output` type to be used as `Stream`
update_slice(self, inner: Self::Slice) -> Self2682 fn update_slice(self, inner: Self::Slice) -> Self;
2683 }
2684
2685 impl<'a, T> UpdateSlice for &'a [T]
2686 where
2687 T: Clone + crate::lib::std::fmt::Debug,
2688 {
2689 #[inline(always)]
update_slice(self, inner: Self::Slice) -> Self2690 fn update_slice(self, inner: Self::Slice) -> Self {
2691 inner
2692 }
2693 }
2694
2695 impl<'a> UpdateSlice for &'a str {
2696 #[inline(always)]
update_slice(self, inner: Self::Slice) -> Self2697 fn update_slice(self, inner: Self::Slice) -> Self {
2698 inner
2699 }
2700 }
2701
2702 impl<'a> UpdateSlice for &'a Bytes {
2703 #[inline(always)]
update_slice(self, inner: Self::Slice) -> Self2704 fn update_slice(self, inner: Self::Slice) -> Self {
2705 Bytes::new(inner)
2706 }
2707 }
2708
2709 impl<'a> UpdateSlice for &'a BStr {
2710 #[inline(always)]
update_slice(self, inner: Self::Slice) -> Self2711 fn update_slice(self, inner: Self::Slice) -> Self {
2712 BStr::new(inner)
2713 }
2714 }
2715
2716 impl<I> UpdateSlice for Located<I>
2717 where
2718 I: UpdateSlice,
2719 {
2720 #[inline(always)]
update_slice(mut self, inner: Self::Slice) -> Self2721 fn update_slice(mut self, inner: Self::Slice) -> Self {
2722 self.input = I::update_slice(self.input, inner);
2723 self
2724 }
2725 }
2726
2727 #[cfg(feature = "unstable-recover")]
2728 impl<I, E> UpdateSlice for Recoverable<I, E>
2729 where
2730 I: Stream,
2731 I: UpdateSlice,
2732 E: crate::lib::std::fmt::Debug,
2733 {
2734 #[inline(always)]
update_slice(mut self, inner: Self::Slice) -> Self2735 fn update_slice(mut self, inner: Self::Slice) -> Self {
2736 self.input = I::update_slice(self.input, inner);
2737 self
2738 }
2739 }
2740
2741 impl<I, S> UpdateSlice for Stateful<I, S>
2742 where
2743 I: UpdateSlice,
2744 S: Clone + crate::lib::std::fmt::Debug,
2745 {
2746 #[inline(always)]
update_slice(mut self, inner: Self::Slice) -> Self2747 fn update_slice(mut self, inner: Self::Slice) -> Self {
2748 self.input = I::update_slice(self.input, inner);
2749 self
2750 }
2751 }
2752
2753 impl<I> UpdateSlice for Partial<I>
2754 where
2755 I: UpdateSlice,
2756 {
2757 #[inline(always)]
update_slice(self, inner: Self::Slice) -> Self2758 fn update_slice(self, inner: Self::Slice) -> Self {
2759 Partial {
2760 input: I::update_slice(self.input, inner),
2761 partial: self.partial,
2762 }
2763 }
2764 }
2765
2766 /// Ensure checkpoint details are kept private
2767 #[derive(Copy, Clone, Debug)]
2768 pub struct Checkpoint<T>(T);
2769
2770 /// A range bounded inclusively for counting parses performed
2771 #[derive(PartialEq, Eq)]
2772 pub struct Range {
2773 pub(crate) start_inclusive: usize,
2774 pub(crate) end_inclusive: Option<usize>,
2775 }
2776
2777 impl Range {
2778 #[inline(always)]
raw(start_inclusive: usize, end_inclusive: Option<usize>) -> Self2779 fn raw(start_inclusive: usize, end_inclusive: Option<usize>) -> Self {
2780 Self {
2781 start_inclusive,
2782 end_inclusive,
2783 }
2784 }
2785 }
2786
2787 impl crate::lib::std::ops::RangeBounds<usize> for Range {
2788 #[inline(always)]
start_bound(&self) -> crate::lib::std::ops::Bound<&usize>2789 fn start_bound(&self) -> crate::lib::std::ops::Bound<&usize> {
2790 crate::lib::std::ops::Bound::Included(&self.start_inclusive)
2791 }
2792
2793 #[inline(always)]
end_bound(&self) -> crate::lib::std::ops::Bound<&usize>2794 fn end_bound(&self) -> crate::lib::std::ops::Bound<&usize> {
2795 if let Some(end_inclusive) = &self.end_inclusive {
2796 crate::lib::std::ops::Bound::Included(end_inclusive)
2797 } else {
2798 crate::lib::std::ops::Bound::Unbounded
2799 }
2800 }
2801 }
2802
2803 impl From<usize> for Range {
2804 #[inline(always)]
from(fixed: usize) -> Self2805 fn from(fixed: usize) -> Self {
2806 (fixed..=fixed).into()
2807 }
2808 }
2809
2810 impl From<crate::lib::std::ops::Range<usize>> for Range {
2811 #[inline(always)]
from(range: crate::lib::std::ops::Range<usize>) -> Self2812 fn from(range: crate::lib::std::ops::Range<usize>) -> Self {
2813 let start_inclusive = range.start;
2814 let end_inclusive = Some(range.end.saturating_sub(1));
2815 Self::raw(start_inclusive, end_inclusive)
2816 }
2817 }
2818
2819 impl From<crate::lib::std::ops::RangeFull> for Range {
2820 #[inline(always)]
from(_: crate::lib::std::ops::RangeFull) -> Self2821 fn from(_: crate::lib::std::ops::RangeFull) -> Self {
2822 let start_inclusive = 0;
2823 let end_inclusive = None;
2824 Self::raw(start_inclusive, end_inclusive)
2825 }
2826 }
2827
2828 impl From<crate::lib::std::ops::RangeFrom<usize>> for Range {
2829 #[inline(always)]
from(range: crate::lib::std::ops::RangeFrom<usize>) -> Self2830 fn from(range: crate::lib::std::ops::RangeFrom<usize>) -> Self {
2831 let start_inclusive = range.start;
2832 let end_inclusive = None;
2833 Self::raw(start_inclusive, end_inclusive)
2834 }
2835 }
2836
2837 impl From<crate::lib::std::ops::RangeTo<usize>> for Range {
2838 #[inline(always)]
from(range: crate::lib::std::ops::RangeTo<usize>) -> Self2839 fn from(range: crate::lib::std::ops::RangeTo<usize>) -> Self {
2840 let start_inclusive = 0;
2841 let end_inclusive = Some(range.end.saturating_sub(1));
2842 Self::raw(start_inclusive, end_inclusive)
2843 }
2844 }
2845
2846 impl From<crate::lib::std::ops::RangeInclusive<usize>> for Range {
2847 #[inline(always)]
from(range: crate::lib::std::ops::RangeInclusive<usize>) -> Self2848 fn from(range: crate::lib::std::ops::RangeInclusive<usize>) -> Self {
2849 let start_inclusive = *range.start();
2850 let end_inclusive = Some(*range.end());
2851 Self::raw(start_inclusive, end_inclusive)
2852 }
2853 }
2854
2855 impl From<crate::lib::std::ops::RangeToInclusive<usize>> for Range {
2856 #[inline(always)]
from(range: crate::lib::std::ops::RangeToInclusive<usize>) -> Self2857 fn from(range: crate::lib::std::ops::RangeToInclusive<usize>) -> Self {
2858 let start_inclusive = 0;
2859 let end_inclusive = Some(range.end);
2860 Self::raw(start_inclusive, end_inclusive)
2861 }
2862 }
2863
2864 impl crate::lib::std::fmt::Display for Range {
fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result2865 fn fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result {
2866 self.start_inclusive.fmt(f)?;
2867 match self.end_inclusive {
2868 Some(e) if e == self.start_inclusive => {}
2869 Some(e) => {
2870 "..=".fmt(f)?;
2871 e.fmt(f)?;
2872 }
2873 None => {
2874 "..".fmt(f)?;
2875 }
2876 }
2877 Ok(())
2878 }
2879 }
2880
2881 impl crate::lib::std::fmt::Debug for Range {
fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result2882 fn fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result {
2883 write!(f, "{self}")
2884 }
2885 }
2886
2887 /// Abstracts something which can extend an `Extend`.
2888 /// Used to build modified input slices in `escaped_transform`
2889 pub trait Accumulate<T>: Sized {
2890 /// Create a new `Extend` of the correct type
initial(capacity: Option<usize>) -> Self2891 fn initial(capacity: Option<usize>) -> Self;
2892 /// Accumulate the input into an accumulator
accumulate(&mut self, acc: T)2893 fn accumulate(&mut self, acc: T);
2894 }
2895
2896 impl<T> Accumulate<T> for () {
2897 #[inline(always)]
initial(_capacity: Option<usize>) -> Self2898 fn initial(_capacity: Option<usize>) -> Self {}
2899 #[inline(always)]
accumulate(&mut self, _acc: T)2900 fn accumulate(&mut self, _acc: T) {}
2901 }
2902
2903 impl<T> Accumulate<T> for usize {
2904 #[inline(always)]
initial(_capacity: Option<usize>) -> Self2905 fn initial(_capacity: Option<usize>) -> Self {
2906 0
2907 }
2908 #[inline(always)]
accumulate(&mut self, _acc: T)2909 fn accumulate(&mut self, _acc: T) {
2910 *self += 1;
2911 }
2912 }
2913
2914 #[cfg(feature = "alloc")]
2915 impl<T> Accumulate<T> for Vec<T> {
2916 #[inline(always)]
initial(capacity: Option<usize>) -> Self2917 fn initial(capacity: Option<usize>) -> Self {
2918 match capacity {
2919 Some(capacity) => Vec::with_capacity(clamp_capacity::<T>(capacity)),
2920 None => Vec::new(),
2921 }
2922 }
2923 #[inline(always)]
accumulate(&mut self, acc: T)2924 fn accumulate(&mut self, acc: T) {
2925 self.push(acc);
2926 }
2927 }
2928
2929 #[cfg(feature = "alloc")]
2930 impl<'i, T: Clone> Accumulate<&'i [T]> for Vec<T> {
2931 #[inline(always)]
initial(capacity: Option<usize>) -> Self2932 fn initial(capacity: Option<usize>) -> Self {
2933 match capacity {
2934 Some(capacity) => Vec::with_capacity(clamp_capacity::<T>(capacity)),
2935 None => Vec::new(),
2936 }
2937 }
2938 #[inline(always)]
accumulate(&mut self, acc: &'i [T])2939 fn accumulate(&mut self, acc: &'i [T]) {
2940 self.extend(acc.iter().cloned());
2941 }
2942 }
2943
2944 #[cfg(feature = "alloc")]
2945 impl Accumulate<char> for String {
2946 #[inline(always)]
initial(capacity: Option<usize>) -> Self2947 fn initial(capacity: Option<usize>) -> Self {
2948 match capacity {
2949 Some(capacity) => String::with_capacity(clamp_capacity::<char>(capacity)),
2950 None => String::new(),
2951 }
2952 }
2953 #[inline(always)]
accumulate(&mut self, acc: char)2954 fn accumulate(&mut self, acc: char) {
2955 self.push(acc);
2956 }
2957 }
2958
2959 #[cfg(feature = "alloc")]
2960 impl<'i> Accumulate<&'i str> for String {
2961 #[inline(always)]
initial(capacity: Option<usize>) -> Self2962 fn initial(capacity: Option<usize>) -> Self {
2963 match capacity {
2964 Some(capacity) => String::with_capacity(clamp_capacity::<char>(capacity)),
2965 None => String::new(),
2966 }
2967 }
2968 #[inline(always)]
accumulate(&mut self, acc: &'i str)2969 fn accumulate(&mut self, acc: &'i str) {
2970 self.push_str(acc);
2971 }
2972 }
2973
2974 #[cfg(feature = "alloc")]
2975 impl<K, V> Accumulate<(K, V)> for BTreeMap<K, V>
2976 where
2977 K: crate::lib::std::cmp::Ord,
2978 {
2979 #[inline(always)]
initial(_capacity: Option<usize>) -> Self2980 fn initial(_capacity: Option<usize>) -> Self {
2981 BTreeMap::new()
2982 }
2983 #[inline(always)]
accumulate(&mut self, (key, value): (K, V))2984 fn accumulate(&mut self, (key, value): (K, V)) {
2985 self.insert(key, value);
2986 }
2987 }
2988
2989 #[cfg(feature = "std")]
2990 impl<K, V, S> Accumulate<(K, V)> for HashMap<K, V, S>
2991 where
2992 K: crate::lib::std::cmp::Eq + crate::lib::std::hash::Hash,
2993 S: BuildHasher + Default,
2994 {
2995 #[inline(always)]
initial(capacity: Option<usize>) -> Self2996 fn initial(capacity: Option<usize>) -> Self {
2997 let h = S::default();
2998 match capacity {
2999 Some(capacity) => {
3000 HashMap::with_capacity_and_hasher(clamp_capacity::<(K, V)>(capacity), h)
3001 }
3002 None => HashMap::with_hasher(h),
3003 }
3004 }
3005 #[inline(always)]
accumulate(&mut self, (key, value): (K, V))3006 fn accumulate(&mut self, (key, value): (K, V)) {
3007 self.insert(key, value);
3008 }
3009 }
3010
3011 #[cfg(feature = "alloc")]
3012 impl<K> Accumulate<K> for BTreeSet<K>
3013 where
3014 K: crate::lib::std::cmp::Ord,
3015 {
3016 #[inline(always)]
initial(_capacity: Option<usize>) -> Self3017 fn initial(_capacity: Option<usize>) -> Self {
3018 BTreeSet::new()
3019 }
3020 #[inline(always)]
accumulate(&mut self, key: K)3021 fn accumulate(&mut self, key: K) {
3022 self.insert(key);
3023 }
3024 }
3025
3026 #[cfg(feature = "std")]
3027 impl<K, S> Accumulate<K> for HashSet<K, S>
3028 where
3029 K: crate::lib::std::cmp::Eq + crate::lib::std::hash::Hash,
3030 S: BuildHasher + Default,
3031 {
3032 #[inline(always)]
initial(capacity: Option<usize>) -> Self3033 fn initial(capacity: Option<usize>) -> Self {
3034 let h = S::default();
3035 match capacity {
3036 Some(capacity) => HashSet::with_capacity_and_hasher(clamp_capacity::<K>(capacity), h),
3037 None => HashSet::with_hasher(h),
3038 }
3039 }
3040 #[inline(always)]
accumulate(&mut self, key: K)3041 fn accumulate(&mut self, key: K) {
3042 self.insert(key);
3043 }
3044 }
3045
3046 #[cfg(feature = "alloc")]
3047 #[inline]
clamp_capacity<T>(capacity: usize) -> usize3048 pub(crate) fn clamp_capacity<T>(capacity: usize) -> usize {
3049 /// Don't pre-allocate more than 64KiB when calling `Vec::with_capacity`.
3050 ///
3051 /// Pre-allocating memory is a nice optimization but count fields can't
3052 /// always be trusted. We should clamp initial capacities to some reasonable
3053 /// amount. This reduces the risk of a bogus count value triggering a panic
3054 /// due to an OOM error.
3055 ///
3056 /// This does not affect correctness. `winnow` will always read the full number
3057 /// of elements regardless of the capacity cap.
3058 const MAX_INITIAL_CAPACITY_BYTES: usize = 65536;
3059
3060 let max_initial_capacity =
3061 MAX_INITIAL_CAPACITY_BYTES / crate::lib::std::mem::size_of::<T>().max(1);
3062 capacity.min(max_initial_capacity)
3063 }
3064
3065 /// Helper trait to convert numbers to usize.
3066 ///
3067 /// By default, usize implements `From<u8>` and `From<u16>` but not
3068 /// `From<u32>` and `From<u64>` because that would be invalid on some
3069 /// platforms. This trait implements the conversion for platforms
3070 /// with 32 and 64 bits pointer platforms
3071 pub trait ToUsize {
3072 /// converts self to usize
to_usize(&self) -> usize3073 fn to_usize(&self) -> usize;
3074 }
3075
3076 impl ToUsize for u8 {
3077 #[inline(always)]
to_usize(&self) -> usize3078 fn to_usize(&self) -> usize {
3079 *self as usize
3080 }
3081 }
3082
3083 impl ToUsize for u16 {
3084 #[inline(always)]
to_usize(&self) -> usize3085 fn to_usize(&self) -> usize {
3086 *self as usize
3087 }
3088 }
3089
3090 impl ToUsize for usize {
3091 #[inline(always)]
to_usize(&self) -> usize3092 fn to_usize(&self) -> usize {
3093 *self
3094 }
3095 }
3096
3097 #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
3098 impl ToUsize for u32 {
3099 #[inline(always)]
to_usize(&self) -> usize3100 fn to_usize(&self) -> usize {
3101 *self as usize
3102 }
3103 }
3104
3105 #[cfg(target_pointer_width = "64")]
3106 impl ToUsize for u64 {
3107 #[inline(always)]
to_usize(&self) -> usize3108 fn to_usize(&self) -> usize {
3109 *self as usize
3110 }
3111 }
3112
3113 /// Transforms a token into a char for basic string parsing
3114 #[allow(clippy::len_without_is_empty)]
3115 #[allow(clippy::wrong_self_convention)]
3116 pub trait AsChar {
3117 /// Makes a char from self
3118 ///
3119 /// # Example
3120 ///
3121 /// ```
3122 /// use winnow::stream::AsChar as _;
3123 ///
3124 /// assert_eq!('a'.as_char(), 'a');
3125 /// assert_eq!(u8::MAX.as_char(), std::char::from_u32(u8::MAX as u32).unwrap());
3126 /// ```
as_char(self) -> char3127 fn as_char(self) -> char;
3128
3129 /// Tests that self is an alphabetic character
3130 ///
3131 /// **Warning:** for `&str` it recognizes alphabetic
3132 /// characters outside of the 52 ASCII letters
is_alpha(self) -> bool3133 fn is_alpha(self) -> bool;
3134
3135 /// Tests that self is an alphabetic character
3136 /// or a decimal digit
is_alphanum(self) -> bool3137 fn is_alphanum(self) -> bool;
3138 /// Tests that self is a decimal digit
is_dec_digit(self) -> bool3139 fn is_dec_digit(self) -> bool;
3140 /// Tests that self is an hex digit
is_hex_digit(self) -> bool3141 fn is_hex_digit(self) -> bool;
3142 /// Tests that self is an octal digit
is_oct_digit(self) -> bool3143 fn is_oct_digit(self) -> bool;
3144 /// Gets the len in bytes for self
len(self) -> usize3145 fn len(self) -> usize;
3146 /// Tests that self is ASCII space or tab
is_space(self) -> bool3147 fn is_space(self) -> bool;
3148 /// Tests if byte is ASCII newline: \n
is_newline(self) -> bool3149 fn is_newline(self) -> bool;
3150 }
3151
3152 impl AsChar for u8 {
3153 #[inline(always)]
as_char(self) -> char3154 fn as_char(self) -> char {
3155 self as char
3156 }
3157 #[inline]
is_alpha(self) -> bool3158 fn is_alpha(self) -> bool {
3159 matches!(self, 0x41..=0x5A | 0x61..=0x7A)
3160 }
3161 #[inline]
is_alphanum(self) -> bool3162 fn is_alphanum(self) -> bool {
3163 self.is_alpha() || self.is_dec_digit()
3164 }
3165 #[inline]
is_dec_digit(self) -> bool3166 fn is_dec_digit(self) -> bool {
3167 matches!(self, 0x30..=0x39)
3168 }
3169 #[inline]
is_hex_digit(self) -> bool3170 fn is_hex_digit(self) -> bool {
3171 matches!(self, 0x30..=0x39 | 0x41..=0x46 | 0x61..=0x66)
3172 }
3173 #[inline]
is_oct_digit(self) -> bool3174 fn is_oct_digit(self) -> bool {
3175 matches!(self, 0x30..=0x37)
3176 }
3177 #[inline]
len(self) -> usize3178 fn len(self) -> usize {
3179 1
3180 }
3181 #[inline]
is_space(self) -> bool3182 fn is_space(self) -> bool {
3183 self == b' ' || self == b'\t'
3184 }
3185 #[inline]
is_newline(self) -> bool3186 fn is_newline(self) -> bool {
3187 self == b'\n'
3188 }
3189 }
3190
3191 impl<'a> AsChar for &'a u8 {
3192 #[inline(always)]
as_char(self) -> char3193 fn as_char(self) -> char {
3194 *self as char
3195 }
3196 #[inline]
is_alpha(self) -> bool3197 fn is_alpha(self) -> bool {
3198 matches!(*self, 0x41..=0x5A | 0x61..=0x7A)
3199 }
3200 #[inline]
is_alphanum(self) -> bool3201 fn is_alphanum(self) -> bool {
3202 self.is_alpha() || self.is_dec_digit()
3203 }
3204 #[inline]
is_dec_digit(self) -> bool3205 fn is_dec_digit(self) -> bool {
3206 matches!(*self, 0x30..=0x39)
3207 }
3208 #[inline]
is_hex_digit(self) -> bool3209 fn is_hex_digit(self) -> bool {
3210 matches!(*self, 0x30..=0x39 | 0x41..=0x46 | 0x61..=0x66)
3211 }
3212 #[inline]
is_oct_digit(self) -> bool3213 fn is_oct_digit(self) -> bool {
3214 matches!(*self, 0x30..=0x37)
3215 }
3216 #[inline]
len(self) -> usize3217 fn len(self) -> usize {
3218 1
3219 }
3220 #[inline]
is_space(self) -> bool3221 fn is_space(self) -> bool {
3222 *self == b' ' || *self == b'\t'
3223 }
3224 #[inline]
is_newline(self) -> bool3225 fn is_newline(self) -> bool {
3226 *self == b'\n'
3227 }
3228 }
3229
3230 impl AsChar for char {
3231 #[inline(always)]
as_char(self) -> char3232 fn as_char(self) -> char {
3233 self
3234 }
3235 #[inline]
is_alpha(self) -> bool3236 fn is_alpha(self) -> bool {
3237 self.is_ascii_alphabetic()
3238 }
3239 #[inline]
is_alphanum(self) -> bool3240 fn is_alphanum(self) -> bool {
3241 self.is_alpha() || self.is_dec_digit()
3242 }
3243 #[inline]
is_dec_digit(self) -> bool3244 fn is_dec_digit(self) -> bool {
3245 self.is_ascii_digit()
3246 }
3247 #[inline]
is_hex_digit(self) -> bool3248 fn is_hex_digit(self) -> bool {
3249 self.is_ascii_hexdigit()
3250 }
3251 #[inline]
is_oct_digit(self) -> bool3252 fn is_oct_digit(self) -> bool {
3253 self.is_digit(8)
3254 }
3255 #[inline]
len(self) -> usize3256 fn len(self) -> usize {
3257 self.len_utf8()
3258 }
3259 #[inline]
is_space(self) -> bool3260 fn is_space(self) -> bool {
3261 self == ' ' || self == '\t'
3262 }
3263 #[inline]
is_newline(self) -> bool3264 fn is_newline(self) -> bool {
3265 self == '\n'
3266 }
3267 }
3268
3269 impl<'a> AsChar for &'a char {
3270 #[inline(always)]
as_char(self) -> char3271 fn as_char(self) -> char {
3272 *self
3273 }
3274 #[inline]
is_alpha(self) -> bool3275 fn is_alpha(self) -> bool {
3276 self.is_ascii_alphabetic()
3277 }
3278 #[inline]
is_alphanum(self) -> bool3279 fn is_alphanum(self) -> bool {
3280 self.is_alpha() || self.is_dec_digit()
3281 }
3282 #[inline]
is_dec_digit(self) -> bool3283 fn is_dec_digit(self) -> bool {
3284 self.is_ascii_digit()
3285 }
3286 #[inline]
is_hex_digit(self) -> bool3287 fn is_hex_digit(self) -> bool {
3288 self.is_ascii_hexdigit()
3289 }
3290 #[inline]
is_oct_digit(self) -> bool3291 fn is_oct_digit(self) -> bool {
3292 self.is_digit(8)
3293 }
3294 #[inline]
len(self) -> usize3295 fn len(self) -> usize {
3296 self.len_utf8()
3297 }
3298 #[inline]
is_space(self) -> bool3299 fn is_space(self) -> bool {
3300 *self == ' ' || *self == '\t'
3301 }
3302 #[inline]
is_newline(self) -> bool3303 fn is_newline(self) -> bool {
3304 *self == '\n'
3305 }
3306 }
3307
3308 /// Check if a token in in a set of possible tokens
3309 ///
3310 /// This is generally implemented on patterns that a token may match and supports `u8` and `char`
3311 /// tokens along with the following patterns
3312 /// - `b'c'` and `'c'`
3313 /// - `b""` and `""`
3314 /// - `|c| true`
3315 /// - `b'a'..=b'z'`, `'a'..='z'` (etc for each [range type][std::ops])
3316 /// - `(pattern1, pattern2, ...)`
3317 ///
3318 /// # Example
3319 ///
3320 /// For example, you could implement `hex_digit0` as:
3321 /// ```
3322 /// # use winnow::prelude::*;
3323 /// # use winnow::{error::ErrMode, error::ErrorKind, error::InputError};
3324 /// # use winnow::token::take_while;
3325 /// fn hex_digit1<'s>(input: &mut &'s str) -> PResult<&'s str, InputError<&'s str>> {
3326 /// take_while(1.., ('a'..='f', 'A'..='F', '0'..='9')).parse_next(input)
3327 /// }
3328 ///
3329 /// assert_eq!(hex_digit1.parse_peek("21cZ"), Ok(("Z", "21c")));
3330 /// assert_eq!(hex_digit1.parse_peek("H2"), Err(ErrMode::Backtrack(InputError::new("H2", ErrorKind::Slice))));
3331 /// assert_eq!(hex_digit1.parse_peek(""), Err(ErrMode::Backtrack(InputError::new("", ErrorKind::Slice))));
3332 /// ```
3333 pub trait ContainsToken<T> {
3334 /// Returns true if self contains the token
contains_token(&self, token: T) -> bool3335 fn contains_token(&self, token: T) -> bool;
3336 }
3337
3338 impl ContainsToken<u8> for u8 {
3339 #[inline(always)]
contains_token(&self, token: u8) -> bool3340 fn contains_token(&self, token: u8) -> bool {
3341 *self == token
3342 }
3343 }
3344
3345 impl<'a> ContainsToken<&'a u8> for u8 {
3346 #[inline(always)]
contains_token(&self, token: &u8) -> bool3347 fn contains_token(&self, token: &u8) -> bool {
3348 self.contains_token(*token)
3349 }
3350 }
3351
3352 impl ContainsToken<char> for u8 {
3353 #[inline(always)]
contains_token(&self, token: char) -> bool3354 fn contains_token(&self, token: char) -> bool {
3355 self.as_char() == token
3356 }
3357 }
3358
3359 impl<'a> ContainsToken<&'a char> for u8 {
3360 #[inline(always)]
contains_token(&self, token: &char) -> bool3361 fn contains_token(&self, token: &char) -> bool {
3362 self.contains_token(*token)
3363 }
3364 }
3365
3366 impl<C: AsChar> ContainsToken<C> for char {
3367 #[inline(always)]
contains_token(&self, token: C) -> bool3368 fn contains_token(&self, token: C) -> bool {
3369 *self == token.as_char()
3370 }
3371 }
3372
3373 impl<C, F: Fn(C) -> bool> ContainsToken<C> for F {
3374 #[inline(always)]
contains_token(&self, token: C) -> bool3375 fn contains_token(&self, token: C) -> bool {
3376 self(token)
3377 }
3378 }
3379
3380 impl<C1: AsChar, C2: AsChar + Clone> ContainsToken<C1> for crate::lib::std::ops::Range<C2> {
3381 #[inline(always)]
contains_token(&self, token: C1) -> bool3382 fn contains_token(&self, token: C1) -> bool {
3383 let start = self.start.clone().as_char();
3384 let end = self.end.clone().as_char();
3385 (start..end).contains(&token.as_char())
3386 }
3387 }
3388
3389 impl<C1: AsChar, C2: AsChar + Clone> ContainsToken<C1>
3390 for crate::lib::std::ops::RangeInclusive<C2>
3391 {
3392 #[inline(always)]
contains_token(&self, token: C1) -> bool3393 fn contains_token(&self, token: C1) -> bool {
3394 let start = self.start().clone().as_char();
3395 let end = self.end().clone().as_char();
3396 (start..=end).contains(&token.as_char())
3397 }
3398 }
3399
3400 impl<C1: AsChar, C2: AsChar + Clone> ContainsToken<C1> for crate::lib::std::ops::RangeFrom<C2> {
3401 #[inline(always)]
contains_token(&self, token: C1) -> bool3402 fn contains_token(&self, token: C1) -> bool {
3403 let start = self.start.clone().as_char();
3404 (start..).contains(&token.as_char())
3405 }
3406 }
3407
3408 impl<C1: AsChar, C2: AsChar + Clone> ContainsToken<C1> for crate::lib::std::ops::RangeTo<C2> {
3409 #[inline(always)]
contains_token(&self, token: C1) -> bool3410 fn contains_token(&self, token: C1) -> bool {
3411 let end = self.end.clone().as_char();
3412 (..end).contains(&token.as_char())
3413 }
3414 }
3415
3416 impl<C1: AsChar, C2: AsChar + Clone> ContainsToken<C1>
3417 for crate::lib::std::ops::RangeToInclusive<C2>
3418 {
3419 #[inline(always)]
contains_token(&self, token: C1) -> bool3420 fn contains_token(&self, token: C1) -> bool {
3421 let end = self.end.clone().as_char();
3422 (..=end).contains(&token.as_char())
3423 }
3424 }
3425
3426 impl<C1: AsChar> ContainsToken<C1> for crate::lib::std::ops::RangeFull {
3427 #[inline(always)]
contains_token(&self, _token: C1) -> bool3428 fn contains_token(&self, _token: C1) -> bool {
3429 true
3430 }
3431 }
3432
3433 impl<C: AsChar> ContainsToken<C> for &'_ [u8] {
3434 #[inline]
contains_token(&self, token: C) -> bool3435 fn contains_token(&self, token: C) -> bool {
3436 let token = token.as_char();
3437 self.iter().any(|t| t.as_char() == token)
3438 }
3439 }
3440
3441 impl<C: AsChar> ContainsToken<C> for &'_ [char] {
3442 #[inline]
contains_token(&self, token: C) -> bool3443 fn contains_token(&self, token: C) -> bool {
3444 let token = token.as_char();
3445 self.iter().any(|t| *t == token)
3446 }
3447 }
3448
3449 impl<const LEN: usize, C: AsChar> ContainsToken<C> for &'_ [u8; LEN] {
3450 #[inline]
contains_token(&self, token: C) -> bool3451 fn contains_token(&self, token: C) -> bool {
3452 let token = token.as_char();
3453 self.iter().any(|t| t.as_char() == token)
3454 }
3455 }
3456
3457 impl<const LEN: usize, C: AsChar> ContainsToken<C> for &'_ [char; LEN] {
3458 #[inline]
contains_token(&self, token: C) -> bool3459 fn contains_token(&self, token: C) -> bool {
3460 let token = token.as_char();
3461 self.iter().any(|t| *t == token)
3462 }
3463 }
3464
3465 impl<const LEN: usize, C: AsChar> ContainsToken<C> for [u8; LEN] {
3466 #[inline]
contains_token(&self, token: C) -> bool3467 fn contains_token(&self, token: C) -> bool {
3468 let token = token.as_char();
3469 self.iter().any(|t| t.as_char() == token)
3470 }
3471 }
3472
3473 impl<const LEN: usize, C: AsChar> ContainsToken<C> for [char; LEN] {
3474 #[inline]
contains_token(&self, token: C) -> bool3475 fn contains_token(&self, token: C) -> bool {
3476 let token = token.as_char();
3477 self.iter().any(|t| *t == token)
3478 }
3479 }
3480
3481 impl<T> ContainsToken<T> for () {
3482 #[inline(always)]
contains_token(&self, _token: T) -> bool3483 fn contains_token(&self, _token: T) -> bool {
3484 false
3485 }
3486 }
3487
3488 macro_rules! impl_contains_token_for_tuple {
3489 ($($haystack:ident),+) => (
3490 #[allow(non_snake_case)]
3491 impl<T, $($haystack),+> ContainsToken<T> for ($($haystack),+,)
3492 where
3493 T: Clone,
3494 $($haystack: ContainsToken<T>),+
3495 {
3496 #[inline]
3497 fn contains_token(&self, token: T) -> bool {
3498 let ($(ref $haystack),+,) = *self;
3499 $($haystack.contains_token(token.clone()) || )+ false
3500 }
3501 }
3502 )
3503 }
3504
3505 macro_rules! impl_contains_token_for_tuples {
3506 ($haystack1:ident, $($haystack:ident),+) => {
3507 impl_contains_token_for_tuples!(__impl $haystack1; $($haystack),+);
3508 };
3509 (__impl $($haystack:ident),+; $haystack1:ident $(,$haystack2:ident)*) => {
3510 impl_contains_token_for_tuple!($($haystack),+);
3511 impl_contains_token_for_tuples!(__impl $($haystack),+, $haystack1; $($haystack2),*);
3512 };
3513 (__impl $($haystack:ident),+;) => {
3514 impl_contains_token_for_tuple!($($haystack),+);
3515 }
3516 }
3517
3518 impl_contains_token_for_tuples!(
3519 F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21
3520 );
3521
3522 #[cfg(feature = "simd")]
3523 #[inline(always)]
memchr(token: u8, slice: &[u8]) -> Option<usize>3524 fn memchr(token: u8, slice: &[u8]) -> Option<usize> {
3525 memchr::memchr(token, slice)
3526 }
3527
3528 #[cfg(feature = "simd")]
3529 #[inline(always)]
memchr2(token: (u8, u8), slice: &[u8]) -> Option<usize>3530 fn memchr2(token: (u8, u8), slice: &[u8]) -> Option<usize> {
3531 memchr::memchr2(token.0, token.1, slice)
3532 }
3533
3534 #[cfg(feature = "simd")]
3535 #[inline(always)]
memchr3(token: (u8, u8, u8), slice: &[u8]) -> Option<usize>3536 fn memchr3(token: (u8, u8, u8), slice: &[u8]) -> Option<usize> {
3537 memchr::memchr3(token.0, token.1, token.2, slice)
3538 }
3539
3540 #[cfg(not(feature = "simd"))]
3541 #[inline(always)]
memchr(token: u8, slice: &[u8]) -> Option<usize>3542 fn memchr(token: u8, slice: &[u8]) -> Option<usize> {
3543 slice.iter().position(|t| *t == token)
3544 }
3545
3546 #[cfg(not(feature = "simd"))]
3547 #[inline(always)]
memchr2(token: (u8, u8), slice: &[u8]) -> Option<usize>3548 fn memchr2(token: (u8, u8), slice: &[u8]) -> Option<usize> {
3549 slice.iter().position(|t| *t == token.0 || *t == token.1)
3550 }
3551
3552 #[cfg(not(feature = "simd"))]
3553 #[inline(always)]
memchr3(token: (u8, u8, u8), slice: &[u8]) -> Option<usize>3554 fn memchr3(token: (u8, u8, u8), slice: &[u8]) -> Option<usize> {
3555 slice
3556 .iter()
3557 .position(|t| *t == token.0 || *t == token.1 || *t == token.2)
3558 }
3559
3560 #[inline(always)]
memmem(slice: &[u8], tag: &[u8]) -> Option<usize>3561 fn memmem(slice: &[u8], tag: &[u8]) -> Option<usize> {
3562 if tag.len() == 1 {
3563 memchr(tag[0], slice)
3564 } else {
3565 memmem_(slice, tag)
3566 }
3567 }
3568
3569 #[inline(always)]
memmem2(slice: &[u8], tag: (&[u8], &[u8])) -> Option<usize>3570 fn memmem2(slice: &[u8], tag: (&[u8], &[u8])) -> Option<usize> {
3571 if tag.0.len() == 1 && tag.1.len() == 1 {
3572 memchr2((tag.0[0], tag.1[0]), slice)
3573 } else {
3574 memmem2_(slice, tag)
3575 }
3576 }
3577
3578 #[inline(always)]
memmem3(slice: &[u8], tag: (&[u8], &[u8], &[u8])) -> Option<usize>3579 fn memmem3(slice: &[u8], tag: (&[u8], &[u8], &[u8])) -> Option<usize> {
3580 if tag.0.len() == 1 && tag.1.len() == 1 && tag.2.len() == 1 {
3581 memchr3((tag.0[0], tag.1[0], tag.2[0]), slice)
3582 } else {
3583 memmem3_(slice, tag)
3584 }
3585 }
3586
3587 #[cfg(feature = "simd")]
3588 #[inline(always)]
memmem_(slice: &[u8], tag: &[u8]) -> Option<usize>3589 fn memmem_(slice: &[u8], tag: &[u8]) -> Option<usize> {
3590 let &prefix = match tag.first() {
3591 Some(x) => x,
3592 None => return Some(0),
3593 };
3594 #[allow(clippy::manual_find)] // faster this way
3595 for i in memchr::memchr_iter(prefix, slice) {
3596 if slice[i..].starts_with(tag) {
3597 return Some(i);
3598 }
3599 }
3600 None
3601 }
3602
3603 #[cfg(feature = "simd")]
memmem2_(slice: &[u8], tag: (&[u8], &[u8])) -> Option<usize>3604 fn memmem2_(slice: &[u8], tag: (&[u8], &[u8])) -> Option<usize> {
3605 let prefix = match (tag.0.first(), tag.1.first()) {
3606 (Some(&a), Some(&b)) => (a, b),
3607 _ => return Some(0),
3608 };
3609 #[allow(clippy::manual_find)] // faster this way
3610 for i in memchr::memchr2_iter(prefix.0, prefix.1, slice) {
3611 let subslice = &slice[i..];
3612 if subslice.starts_with(tag.0) {
3613 return Some(i);
3614 }
3615 if subslice.starts_with(tag.1) {
3616 return Some(i);
3617 }
3618 }
3619 None
3620 }
3621
3622 #[cfg(feature = "simd")]
memmem3_(slice: &[u8], tag: (&[u8], &[u8], &[u8])) -> Option<usize>3623 fn memmem3_(slice: &[u8], tag: (&[u8], &[u8], &[u8])) -> Option<usize> {
3624 let prefix = match (tag.0.first(), tag.1.first(), tag.2.first()) {
3625 (Some(&a), Some(&b), Some(&c)) => (a, b, c),
3626 _ => return Some(0),
3627 };
3628 #[allow(clippy::manual_find)] // faster this way
3629 for i in memchr::memchr3_iter(prefix.0, prefix.1, prefix.2, slice) {
3630 let subslice = &slice[i..];
3631 if subslice.starts_with(tag.0) {
3632 return Some(i);
3633 }
3634 if subslice.starts_with(tag.1) {
3635 return Some(i);
3636 }
3637 if subslice.starts_with(tag.2) {
3638 return Some(i);
3639 }
3640 }
3641 None
3642 }
3643
3644 #[cfg(not(feature = "simd"))]
memmem_(slice: &[u8], tag: &[u8]) -> Option<usize>3645 fn memmem_(slice: &[u8], tag: &[u8]) -> Option<usize> {
3646 for i in 0..slice.len() {
3647 let subslice = &slice[i..];
3648 if subslice.starts_with(tag) {
3649 return Some(i);
3650 }
3651 }
3652 None
3653 }
3654
3655 #[cfg(not(feature = "simd"))]
memmem2_(slice: &[u8], tag: (&[u8], &[u8])) -> Option<usize>3656 fn memmem2_(slice: &[u8], tag: (&[u8], &[u8])) -> Option<usize> {
3657 for i in 0..slice.len() {
3658 let subslice = &slice[i..];
3659 if subslice.starts_with(tag.0) {
3660 return Some(i);
3661 }
3662 if subslice.starts_with(tag.1) {
3663 return Some(i);
3664 }
3665 }
3666 None
3667 }
3668
3669 #[cfg(not(feature = "simd"))]
memmem3_(slice: &[u8], tag: (&[u8], &[u8], &[u8])) -> Option<usize>3670 fn memmem3_(slice: &[u8], tag: (&[u8], &[u8], &[u8])) -> Option<usize> {
3671 for i in 0..slice.len() {
3672 let subslice = &slice[i..];
3673 if subslice.starts_with(tag.0) {
3674 return Some(i);
3675 }
3676 if subslice.starts_with(tag.1) {
3677 return Some(i);
3678 }
3679 if subslice.starts_with(tag.2) {
3680 return Some(i);
3681 }
3682 }
3683 None
3684 }
3685