dangerous 0.10.0

Safely and explicitly parse untrusted / dangerous data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
use core::convert::Infallible;

use crate::display::InputDisplay;
use crate::error::{
    with_context, CoreContext, CoreExpected, CoreOperation, ExpectedLength, ExpectedValid,
    ExpectedValue, External, Length, Value, WithChildContext, WithContext,
};
use crate::fmt::{Debug, Display, DisplayBase};
use crate::input::pattern::Pattern;
use crate::reader::Reader;

use super::{Bound, Bytes, MaybeString, Prefix, Span, String};

/// Implemented for immutable wrappers around bytes to be processed ([`Bytes`]/[`String`]).
///
/// It can only be created via [`dangerous::input()`] as so to clearly point out
/// where untrusted / dangerous input is consumed and takes the form of either
/// [`Bytes`] or [`String`].
///
/// It is used along with [`Reader`] to process the input.
///
/// # Formatting
///
/// `Input` implements support for pretty printing. See [`InputDisplay`] for
/// formatting options.
///
/// [`dangerous::input()`]: crate::input()
#[must_use = "input must be consumed"]
pub trait Input<'i>: Private<'i> {
    /// Returns the [`Input`] [`Bound`].
    fn bound(&self) -> Bound;

    /// Returns `self` as a bound `Input`.
    ///
    /// Bound `Input` carries the guarantee that it will not be extended in
    /// future passes and as a result will not produce [`RetryRequirement`]s.
    ///
    /// # Example
    ///
    /// ```
    /// use dangerous::{Input, Invalid, ToRetryRequirement};
    ///
    /// let error: Invalid = dangerous::input(b"1234")
    ///     .into_bound()
    ///     .read_partial(|r| r.take(5))
    ///     .unwrap_err();
    ///
    /// // If the input was not bound, this wouldn't be fatal.
    /// assert!(error.is_fatal());
    /// ```
    ///
    /// [`RetryRequirement`]: crate::error::RetryRequirement
    fn into_bound(self) -> Self;

    /// Consumes `self` into [`Bytes`].
    fn into_bytes(self) -> Bytes<'i>;

    /// Decodes the underlying byte slice into a UTF-8 [`String`].
    ///
    /// # Errors
    ///
    /// Returns [`ExpectedValid`] if the input could never be valid UTF-8 and
    /// [`ExpectedLength`] if a UTF-8 code point was cut short.
    fn into_string<E>(self) -> Result<String<'i>, E>
    where
        E: From<ExpectedValid<'i>>,
        E: From<ExpectedLength<'i>>;

    /// Consumes `self` into [`MaybeString`] returning `MaybeString::String` if
    /// the underlying bytes are known `UTF-8`.
    fn into_maybe_string(self) -> MaybeString<'i>;

    /// Returns an [`InputDisplay`] for formatting.
    fn display(&self) -> InputDisplay<'i>;

    ///////////////////////////////////////////////////////////////////////////
    // Provided methods

    /// Returns the underlying byte slice length.
    #[must_use]
    #[inline(always)]
    fn byte_len(&self) -> usize {
        self.as_dangerous_bytes().len()
    }

    /// Returns `true` if the underlying byte slice length is zero.
    #[must_use]
    #[inline(always)]
    fn is_empty(&self) -> bool {
        self.byte_len() == 0
    }

    /// Returns `true` if [`Self::bound()`] is [`Bound::StartEnd`].
    #[must_use]
    #[inline(always)]
    fn is_bound(&self) -> bool {
        self.bound() == Bound::StartEnd
    }

    /// Returns a [`Span`] from the start of `self` to the end.
    #[inline(always)]
    fn span(&self) -> Span {
        Span::from(self.as_dangerous_bytes())
    }

    /// Returns the `nth` token if any within the input.
    #[must_use]
    #[inline(always)]
    fn nth(&self, index: usize) -> Option<Self::Token> {
        self.clone().tokens().nth(index)
    }

    /// Returns the first token if any within the input.
    #[must_use]
    #[inline(always)]
    fn first(&self) -> Option<Self::Token> {
        self.clone().tokens().next()
    }

    /// Returns the last token if any within the input.
    #[must_use]
    #[inline(always)]
    fn last(&self) -> Option<Self::Token> {
        self.clone().tokens().next_back()
    }

    /// Create a reader with the expectation all of the input is read.
    ///
    /// # Errors
    ///
    /// Returns an error if either the provided function does, or there is
    /// trailing input.
    #[inline]
    fn read_all<F, T, E>(self, f: F) -> Result<T, E>
    where
        F: FnOnce(&mut Reader<'i, Self, E>) -> Result<T, E>,
        E: WithContext<'i>,
        E: From<ExpectedLength<'i>>,
    {
        let mut r = Reader::new(self.clone());
        match r.context(
            CoreContext::from_operation(CoreOperation::ReadAll, self.span()),
            f,
        ) {
            Ok(ok) if r.at_end() => Ok(ok),
            Ok(_) => Err(E::from(ExpectedLength {
                len: Length::Exactly(0),
                context: CoreContext {
                    span: r.take_remaining().span(),
                    operation: CoreOperation::ReadAll,
                    expected: CoreExpected::NoTrailingInput,
                },
                input: self.into_maybe_string(),
            })),
            Err(err) => Err(err),
        }
    }

    /// Create a reader to read a part of the input and return the rest.
    ///
    /// # Errors
    ///
    /// Returns an error if the provided function does.
    #[inline]
    fn read_partial<F, T, E>(self, f: F) -> Result<(T, Self), E>
    where
        F: FnOnce(&mut Reader<'i, Self, E>) -> Result<T, E>,
        E: WithContext<'i>,
    {
        let mut r = Reader::new(self.clone());
        match r.context(
            CoreContext::from_operation(CoreOperation::ReadPartial, self.span()),
            f,
        ) {
            Ok(ok) => Ok((ok, r.take_remaining())),
            Err(err) => Err(err),
        }
    }

    /// Create a reader to read a part of the input and return the rest
    /// without any errors.
    #[inline]
    fn read_infallible<F, T>(self, f: F) -> (T, Self)
    where
        F: FnOnce(&mut Reader<'i, Self, Infallible>) -> T,
    {
        let mut r = Reader::new(self);
        let ok = f(&mut r);
        (ok, r.take_remaining())
    }

    /// Tries to convert `self` into `T` with [`External`] error support.
    ///
    /// **Note**: it is the callers responsibility to ensure all of the input is
    /// handled. If the function may only consume a partial amount of input, use
    /// [`Reader::try_expect_external()`] instead.
    ///
    /// # Errors
    ///
    /// Returns [`ExpectedValid`] if the provided function returns an
    /// [`External`] error.
    #[inline]
    fn into_external<F, T, E, Ex>(self, expected: &'static str, f: F) -> Result<T, E>
    where
        F: FnOnce(Self) -> Result<T, Ex>,
        E: WithContext<'i>,
        E: From<ExpectedValid<'i>>,
        Ex: External<'i>,
    {
        f(self.clone()).map_err(|external| {
            self.map_external_error(external, expected, CoreOperation::IntoExternal)
        })
    }

    /// Returns `self` if it is not empty.
    ///
    /// # Errors
    ///
    /// Returns [`ExpectedLength`] if the input is empty.
    fn into_non_empty<E>(self) -> Result<Self, E>
    where
        E: From<ExpectedLength<'i>>,
    {
        if self.is_empty() {
            Err(E::from(ExpectedLength {
                len: Length::AtLeast(1),

                context: CoreContext {
                    span: self.span(),
                    operation: CoreOperation::IntoNonEmpty,
                    expected: CoreExpected::NonEmpty,
                },
                input: self.into_maybe_string(),
            }))
        } else {
            Ok(self)
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
// Private requirements for any `Input`

pub trait Private<'i>: Sized + Clone + DisplayBase + Debug + Display {
    /// Smallest unit that can be consumed.
    type Token: BytesLength + Copy + 'static;

    /// Iterator of tokens.
    type TokenIter: DoubleEndedIterator<Item = Self::Token>;

    /// Iterator of tokens and their associated byte indices.
    type TokenIndicesIter: DoubleEndedIterator<Item = (usize, Self::Token)>;

    /// Returns an empty `Input` pointing the end of `self`.
    fn end(self) -> Self;

    /// Returns a token iterator.
    fn tokens(self) -> Self::TokenIter;

    /// Returns a token indices iterator.
    fn tokens_indices(self) -> Self::TokenIndicesIter;

    // Return self with its end bound removed.
    fn into_unbound_end(self) -> Self;

    /// Verifies a token boundary.
    ///
    /// The start and end of the input (when `index == self.byte_len()`) are
    /// considered to be boundaries.
    ///
    /// Returns what was expected at that index.
    fn verify_token_boundary(&self, index: usize) -> Result<(), CoreExpected>;

    /// Split the input at the token index `mid`.
    ///
    /// Return `Some` if mid is a valid index, `None` if not.
    fn split_at_opt(self, mid: usize) -> Option<(Self, Self)>;

    /// Splits the input at the byte index `mid` without any validation.
    ///
    /// # Safety
    ///
    /// Caller must guarantee that it is valid to split the structure at `mid`.
    unsafe fn split_at_byte_unchecked(self, mid: usize) -> (Self, Self);
}

///////////////////////////////////////////////////////////////////////////////
// Private extensions to any `Input`

pub(crate) trait PrivateExt<'i>: Input<'i> {
    /// Returns the underlying byte slice of the input.
    #[inline(always)]
    fn as_dangerous_bytes(&self) -> &'i [u8] {
        self.clone().into_bytes().as_dangerous()
    }

    /// Splits the input into two at the token index `mid`.
    ///
    /// # Errors
    ///
    /// Returns an error if `mid > self.len()`.
    #[inline(always)]
    fn split_at<E>(self, mid: usize, operation: CoreOperation) -> Result<(Self, Self), E>
    where
        E: From<ExpectedLength<'i>>,
    {
        self.clone().split_at_opt(mid).ok_or_else(|| {
            E::from(ExpectedLength {
                len: Length::AtLeast(mid),

                context: CoreContext {
                    span: self.span(),
                    operation,
                    expected: CoreExpected::EnoughInputFor("split"),
                },
                input: self.into_maybe_string(),
            })
        })
    }

    /// Splits the input into two at the byte index `mid`.
    ///
    /// # Errors
    ///
    /// Returns [`ExpectedLength`] if `mid > self.len()` and [`ExpectedValid`]
    /// if `mid` is not a valid token boundary.
    #[inline(always)]
    fn split_at_byte<E>(self, mid: usize, operation: CoreOperation) -> Result<(Self, Self), E>
    where
        E: From<ExpectedValid<'i>>,
        E: From<ExpectedLength<'i>>,
    {
        if self.byte_len() < mid {
            Err(E::from(ExpectedLength {
                len: Length::AtLeast(mid),

                context: CoreContext {
                    span: self.span(),
                    operation,
                    expected: CoreExpected::EnoughInputFor("split"),
                },
                input: self.into_maybe_string(),
            }))
        } else {
            match self.verify_token_boundary(mid) {
                Ok(()) => {
                    // SAFETY: index `mid` has been checked to be a valid token
                    // boundary.
                    Ok(unsafe { self.split_at_byte_unchecked(mid) })
                }
                Err(expected) => Err(E::from(ExpectedValid {
                    retry_requirement: None,
                    context: CoreContext {
                        span: self.as_dangerous_bytes()[mid..mid].into(),
                        operation,
                        expected,
                    },
                    input: self.into_maybe_string(),
                })),
            }
        }
    }

    /// Splits the input into the first token and whatever remains.
    #[inline(always)]
    fn split_token_opt(self) -> Option<(Self::Token, Self)> {
        self.clone().tokens().next().map(|token| {
            // SAFETY: ByteLength guarantees a correct implementation for
            // returning the length of a token. The token iterator returned a
            // token for us, so we know we can split it off safely.
            let (_, tail) = unsafe { self.split_at_byte_unchecked(token.byte_len()) };
            (token, tail)
        })
    }

    /// Splits the input into the first token and whatever remains.
    ///
    /// # Errors
    ///
    /// Returns an error if the input is empty.
    #[inline(always)]
    fn split_token<E>(self, operation: CoreOperation) -> Result<(Self::Token, Self), E>
    where
        E: From<ExpectedLength<'i>>,
    {
        self.clone().split_token_opt().ok_or_else(|| {
            E::from(ExpectedLength {
                len: Length::AtLeast(1),

                context: CoreContext {
                    span: self.span(),
                    operation,
                    expected: CoreExpected::EnoughInputFor("token"),
                },
                input: self.into_maybe_string(),
            })
        })
    }

    /// Splits a prefix from the input if it is present.
    #[inline(always)]
    fn split_prefix_opt<P>(self, prefix: P) -> (Option<Self>, Self)
    where
        P: Prefix<Self>,
    {
        if prefix.is_prefix_of(&self) {
            // SAFETY: we just validated that prefix is within the input so its
            // length is a valid index.
            let (head, tail) = unsafe { self.split_at_byte_unchecked(prefix.byte_len()) };
            (Some(head), tail)
        } else {
            (None, self)
        }
    }

    /// Splits a prefix from the input if it is present.
    ///
    /// # Errors
    ///
    /// Returns an error if the input does not have the prefix.
    #[inline(always)]
    fn split_prefix<P, E>(self, prefix: P, operation: CoreOperation) -> Result<(Self, Self), E>
    where
        E: From<ExpectedValue<'i>>,
        P: Prefix<Self> + Into<Value<'i>>,
    {
        match self.clone().split_prefix_opt(&prefix) {
            (Some(head), tail) => Ok((head, tail)),
            (None, unmatched) => {
                let bytes = unmatched.as_dangerous_bytes();
                let prefix_len = prefix.byte_len();
                let actual = if bytes.len() > prefix_len {
                    &bytes[..prefix_len]
                } else {
                    &bytes
                };
                Err(E::from(ExpectedValue {
                    expected: prefix.into(),
                    context: CoreContext {
                        span: actual.into(),
                        operation,
                        expected: CoreExpected::ExactValue,
                    },
                    input: self.into_maybe_string(),
                }))
            }
        }
    }

    /// Splits at a pattern in the input if it is present.
    #[inline(always)]
    fn split_until_opt<P>(self, pattern: P) -> Option<(Self, Self)>
    where
        P: Pattern<Self>,
    {
        pattern.find_match(&self).map(|(index, _)| {
            // SAFETY: Pattern guarantees it returns valid indexes.
            unsafe { self.split_at_byte_unchecked(index) }
        })
    }

    /// Splits at a pattern in the input if it is present.
    #[inline(always)]
    fn split_until_consume_opt<P>(self, pattern: P) -> Option<(Self, Self)>
    where
        P: Pattern<Self>,
    {
        pattern.find_match(&self).map(|(index, len)| {
            // SAFETY: Pattern guarantees it returns valid indexes.
            let (head, tail) = unsafe { self.split_at_byte_unchecked(index) };
            let (_, tail) = unsafe { tail.split_at_byte_unchecked(len) };
            (head, tail)
        })
    }

    /// Splits the input up to when the pattern matches.
    #[inline(always)]
    fn split_until<P, E>(self, pattern: P, operation: CoreOperation) -> Result<(Self, Self), E>
    where
        E: From<ExpectedValue<'i>>,
        P: Pattern<Self> + Into<Value<'i>> + Copy,
    {
        self.clone().split_until_opt(pattern).ok_or_else(|| {
            E::from(ExpectedValue {
                expected: pattern.into(),
                context: CoreContext {
                    span: self.span(),
                    operation,
                    expected: CoreExpected::PatternMatch,
                },
                input: self.into_maybe_string(),
            })
        })
    }

    /// Splits at a pattern in the input if it is present.
    ///
    /// # Errors
    ///
    /// Returns an error if the input does not have the pattern.
    #[inline(always)]
    fn split_until_consume<P, E>(
        self,
        pattern: P,
        operation: CoreOperation,
    ) -> Result<(Self, Self), E>
    where
        E: From<ExpectedValue<'i>>,
        P: Pattern<Self> + Into<Value<'i>> + Copy,
    {
        self.clone()
            .split_until_consume_opt(pattern)
            .ok_or_else(|| {
                E::from(ExpectedValue {
                    expected: pattern.into(),
                    context: CoreContext {
                        span: self.span(),
                        operation,
                        expected: CoreExpected::PatternMatch,
                    },
                    input: self.into_maybe_string(),
                })
            })
    }

    /// Splits the input up to when the provided function returns `false`.
    #[inline(always)]
    fn split_while_opt<P>(self, pattern: P) -> Option<(Self, Self)>
    where
        P: Pattern<Self>,
    {
        pattern.find_reject(&self).map(|i| {
            // SAFETY: Pattern guarantees it returns valid indexes.
            unsafe { self.split_at_byte_unchecked(i) }
        })
    }

    /// Tries to split the input up to when the provided function returns
    /// `false`.
    ///
    /// # Errors
    ///
    /// Returns an error from the provided function if it fails.
    #[inline(always)]
    fn try_split_while<F, E>(self, mut f: F, operation: CoreOperation) -> Result<(Self, Self), E>
    where
        E: WithContext<'i>,
        F: FnMut(Self::Token) -> Result<bool, E>,
    {
        // For each token, lets make sure it matches the predicate.
        for (i, token) in self.clone().tokens_indices() {
            // Check if the token doesn't match the predicate.
            let should_continue = with_context(
                CoreContext::from_operation(operation, self.span()),
                self.clone(),
                || f(token),
            )?;
            if !should_continue {
                // Split the input up to, but not including the token.
                // `i` derived from the token iterator is always a valid index
                // for the input.
                let (head, tail) = unsafe { self.split_at_byte_unchecked(i) };
                // Return the split input parts.
                return Ok((head, tail));
            }
        }
        Ok((self.clone(), self.end()))
    }

    /// Splits the input at what was read, the input that was consumed and what
    /// input was remaining.
    #[inline(always)]
    fn split_consumed<F, T, E>(self, f: F) -> (T, Self, Self)
    where
        F: FnOnce(&mut Reader<'i, Self, E>) -> T,
    {
        let mut reader = Reader::new(self.clone());
        // Consume input.
        let value = f(&mut reader);
        // We take the remaining input.
        let tail = reader.take_remaining();
        // For the head, we take what we consumed.
        let mid = self.byte_len() - tail.byte_len();
        // SAFETY: we take mid as the difference between the parent slice and
        // the remaining slice left over from the reader. This means the index
        // can only ever be valid.
        let (head, _) = unsafe { self.split_at_byte_unchecked(mid) };
        // We derive the bound constraint from self. If the tail start is
        // undetermined this means the last bit of input consumed could be
        // longer if there was more available and as such makes the end of input
        // we return unbounded.
        if tail.bound() == Bound::None {
            (value, head.into_unbound_end(), tail)
        } else {
            (value, head, tail)
        }
    }

    /// Tries to split the input at what was read and what was remaining.
    ///
    /// # Errors
    ///
    /// Returns an error from the provided function if it fails.
    #[inline(always)]
    fn try_split_consumed<F, T, E>(
        self,
        f: F,
        operation: CoreOperation,
    ) -> Result<(T, Self, Self), E>
    where
        E: WithContext<'i>,
        F: FnOnce(&mut Reader<'i, Self, E>) -> Result<T, E>,
    {
        let mut reader = Reader::new(self.clone());
        // Consume input.
        let value = reader.context(CoreContext::from_operation(operation, self.span()), f)?;
        // We take the remaining input.
        let tail = reader.take_remaining();
        // For the head, we take what we consumed.
        let mid = self.byte_len() - tail.byte_len();
        // SAFETY: we take mid as the difference between the parent slice and
        // the remaining slice left over from the reader. This means the index
        // can only ever be valid.
        let (head, _) = unsafe { self.split_at_byte_unchecked(mid) };
        // We derive the bound constraint from self. If the tail start is
        // undetermined this means the last bit of input consumed could be
        // longer if there was more available and as such makes the end of input
        // we return unbounded.
        if tail.bound() == Bound::None {
            Ok((value, head.into_unbound_end(), tail))
        } else {
            Ok((value, head, tail))
        }
    }

    /// Splits the input from the value expected to be read.
    ///
    /// # Errors
    ///
    /// Returns an error if the expected value was not present.
    #[inline(always)]
    fn split_expect<F, T, E>(
        self,
        f: F,
        expected: &'static str,
        operation: CoreOperation,
    ) -> Result<(T, Self), E>
    where
        E: From<ExpectedValid<'i>>,
        F: FnOnce(&mut Reader<'i, Self, E>) -> Option<T>,
    {
        let mut reader = Reader::new(self.clone());
        if let Some(ok) = f(&mut reader) {
            Ok((ok, reader.take_remaining()))
        } else {
            let tail = reader.take_remaining();
            let span = self.as_dangerous_bytes()[..self.byte_len() - tail.byte_len()].into();
            Err(E::from(ExpectedValid {
                retry_requirement: None,
                context: CoreContext {
                    span,
                    expected: CoreExpected::Valid(expected),
                    operation,
                },
                input: self.into_maybe_string(),
            }))
        }
    }

    /// Tries to split the input from the value expected to be read.
    ///
    /// # Errors
    ///
    /// Returns an error from the provided function if it fails or if the
    /// expected value was not present.
    #[inline(always)]
    fn try_split_expect<F, T, E>(
        self,
        f: F,
        expected: &'static str,
        operation: CoreOperation,
    ) -> Result<(T, Self), E>
    where
        E: WithContext<'i>,
        E: From<ExpectedValid<'i>>,
        F: FnOnce(&mut Reader<'i, Self, E>) -> Result<Option<T>, E>,
    {
        let mut context = CoreContext {
            span: self.span(),
            expected: CoreExpected::Valid(expected),
            operation,
        };
        let mut reader = Reader::new(self.clone());
        match reader.context(context, f) {
            Ok(Some(ok)) => Ok((ok, reader.take_remaining())),
            Ok(None) => {
                let tail = reader.take_remaining();
                context.span =
                    self.as_dangerous_bytes()[..self.byte_len() - tail.byte_len()].into();
                Err(E::from(ExpectedValid {
                    retry_requirement: None,
                    context,
                    input: self.into_maybe_string(),
                }))
            }
            Err(err) => Err(err),
        }
    }

    /// Tries to split the input from a value expected with support for an
    /// external error.
    ///
    /// # Errors
    ///
    /// Returns [`ExpectedValid`] if:
    ///
    /// - the provided function returns an amount of input read not aligned to a
    ///   token boundary
    /// - the provided function returns an [`External`] error.
    ///
    /// Returns [`ExpectedLength`] if:
    ///
    /// - the provided function returns an amount of input read that is greater
    ///   than the actual length
    #[inline(always)]
    fn try_split_expect_external<F, T, E, Ex>(
        self,
        f: F,
        expected: &'static str,
        operation: CoreOperation,
    ) -> Result<(T, Self), E>
    where
        F: FnOnce(Self) -> Result<(usize, T), Ex>,
        E: WithContext<'i>,
        E: From<ExpectedValid<'i>>,
        E: From<ExpectedLength<'i>>,
        Ex: External<'i>,
    {
        match f(self.clone()) {
            Ok((read, ok)) => self
                .split_at_byte(read, operation)
                .map(|(_, remaining)| (ok, remaining)),
            Err(external) => Err(self.map_external_error(external, expected, operation)),
        }
    }

    fn map_external_error<E, Ex>(
        self,
        external: Ex,
        expected: &'static str,
        operation: CoreOperation,
    ) -> E
    where
        E: WithContext<'i>,
        E: From<ExpectedValid<'i>>,
        Ex: External<'i>,
    {
        let error = E::from(ExpectedValid {
            retry_requirement: external.retry_requirement(),
            context: CoreContext {
                span: external.span().unwrap_or_else(|| self.span()),
                expected: CoreExpected::Valid(expected),
                operation,
            },
            input: self.into_maybe_string(),
        });
        external
            .push_backtrace(WithChildContext::new(error))
            .unwrap()
    }
}

impl<'i, T> PrivateExt<'i> for T where T: Input<'i> {}

///////////////////////////////////////////////////////////////////////////////
// BytesLength

pub unsafe trait BytesLength: Copy {
    fn byte_len(self) -> usize;
}

unsafe impl<T> BytesLength for &T
where
    T: BytesLength,
{
    #[inline(always)]
    fn byte_len(self) -> usize {
        (*self).byte_len()
    }
}

unsafe impl BytesLength for u8 {
    #[inline(always)]
    fn byte_len(self) -> usize {
        1
    }
}

unsafe impl BytesLength for char {
    #[inline(always)]
    fn byte_len(self) -> usize {
        self.len_utf8()
    }
}

unsafe impl BytesLength for &[u8] {
    #[inline(always)]
    fn byte_len(self) -> usize {
        self.len()
    }
}

unsafe impl BytesLength for &str {
    #[inline(always)]
    fn byte_len(self) -> usize {
        self.as_bytes().len()
    }
}

unsafe impl<const N: usize> BytesLength for &[u8; N] {
    #[inline(always)]
    fn byte_len(self) -> usize {
        self.len()
    }
}

///////////////////////////////////////////////////////////////////////////////
// IntoInput

pub trait IntoInput<'i>: Copy {
    type Input: Input<'i>;

    fn into_input(self) -> Self::Input;
}

impl<'i, T> IntoInput<'i> for &T
where
    T: IntoInput<'i>,
{
    type Input = T::Input;

    #[inline(always)]
    fn into_input(self) -> Self::Input {
        (*self).into_input()
    }
}

impl<'i> IntoInput<'i> for &'i [u8] {
    type Input = Bytes<'i>;

    #[inline(always)]
    fn into_input(self) -> Self::Input {
        Bytes::new(self, Bound::Start)
    }
}

impl<'i> IntoInput<'i> for &'i str {
    type Input = String<'i>;

    #[inline(always)]
    fn into_input(self) -> Self::Input {
        String::new(self, Bound::Start)
    }
}

impl<'i, const N: usize> IntoInput<'i> for &'i [u8; N] {
    type Input = Bytes<'i>;

    #[inline(always)]
    fn into_input(self) -> Self::Input {
        Bytes::new(self, Bound::Start)
    }
}