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
#![doc = include_str!("../README.md")]
#![deny(missing_docs)]

use std::{
    future::Future,
    mem::ManuallyDrop,
    ops::{ControlFlow, Deref, DerefMut, Range},
    pin::Pin,
    task::{Context, Poll},
};

use futures::task::noop_waker_ref;

/// Data of input.
/// Buffer and current index.
#[derive(Debug, Default)]
pub struct Cursor<T> {
    /// Sequence of items, you may append items to this when you want.
    /// This crate loosely assumes that you don't remove items from this.
    pub buf: Vec<T>,
    /// Current `index` of the cursor.
    /// This crate assumes `index` <= `buf.len()`.
    pub index: usize,
}

impl<T> Cursor<T> {
    fn sanity_check(&self) -> bool {
        self.index <= self.buf.len()
    }
}

#[cfg(debug_assertions)]
#[repr(transparent)]
#[derive(Debug)]
/// You need to wrap [`Cursor`] with this to parse.
pub struct Input<T>(std::cell::RefCell<Cursor<T>>);

#[cfg(not(debug_assertions))]
#[repr(transparent)]
#[derive(Debug)]
/// Just a wrapper of Cursor.
/// This is used as input of parsers.
pub struct Input<T>(std::cell::UnsafeCell<Cursor<T>>);

impl<T> Input<T> {
    #[inline]
    /// Create a new [`Input`] from [`Cursor`].
    pub fn new(cursor: Cursor<T>) -> Self {
        #[cfg(debug_assertions)]
        {
            Self(std::cell::RefCell::new(cursor))
        }
        #[cfg(not(debug_assertions))]
        {
            Self(std::cell::UnsafeCell::new(cursor))
        }
    }

    #[inline]
    /// Get a reference of [`Cursor`].
    pub fn cursor(&self) -> impl Deref<Target = Cursor<T>> + '_ {
        #[cfg(debug_assertions)]
        {
            self.0.borrow()
        }
        #[cfg(not(debug_assertions))]
        unsafe {
            &*self.0.get()
        }
    }
    #[inline]
    /// Get a mutable reference of [`Cursor`].
    pub fn cursor_mut(&mut self) -> impl DerefMut<Target = Cursor<T>> + '_ {
        #[cfg(debug_assertions)]
        {
            self.0.borrow_mut()
        }
        #[cfg(not(debug_assertions))]
        unsafe {
            &mut *self.0.get()
        }
    }

    /// Don't call .await while holding a borrow of the cursor.
    #[inline]
    unsafe fn cursor_mut_unsafe(&self) -> impl DerefMut<Target = Cursor<T>> + '_ {
        #[cfg(debug_assertions)]
        {
            self.0.borrow_mut()
        }
        #[cfg(not(debug_assertions))]
        unsafe {
            &mut *self.0.get()
        }
    }

    /// Get the inner [`Cursor`].
    pub fn into_inner(self) -> Cursor<T> {
        self.0.into_inner()
    }

    #[inline]
    fn read(&self) -> impl Future<Output = ()> + '_ {
        struct Read<'a, T> {
            input: &'a Input<T>,
            start_len: usize,
        }

        impl<T> Future for Read<'_, T> {
            type Output = ();

            fn poll(
                self: std::pin::Pin<&mut Self>,
                _cx: &mut std::task::Context<'_>,
            ) -> std::task::Poll<Self::Output> {
                let c = self.input.cursor();
                if c.buf.len() > self.start_len {
                    std::task::Poll::Ready(())
                } else {
                    std::task::Poll::Pending
                }
            }
        }

        Read {
            input: self,
            start_len: self.cursor().buf.len(),
        }
    }

    #[inline]
    fn read_n(&self, at_least: usize) -> impl Future<Output = ()> + '_ {
        struct ReadAtLeast<'a, T> {
            input: &'a Input<T>,
            start_index: usize,
            at_least: usize,
        }

        impl<T> Future for ReadAtLeast<'_, T> {
            type Output = ();

            fn poll(
                self: std::pin::Pin<&mut Self>,
                _cx: &mut std::task::Context<'_>,
            ) -> std::task::Poll<Self::Output> {
                let c = self.input.cursor();
                if c.buf.len() >= self.start_index + self.at_least {
                    std::task::Poll::Ready(())
                } else {
                    std::task::Poll::Pending
                }
            }
        }

        ReadAtLeast {
            input: self,
            start_index: self.cursor().index,
            at_least,
        }
    }

    #[inline]
    /// Start parsing with a parser.
    /// Just a wrapper of [`Parsing::new`].
    pub fn start_parsing<'a, O, F, P>(&'a mut self, parser: P) -> Parsing<'a, T, O, F>
    where
        P: Parser<'a, T, O, F>,
        F: Future<Output = O> + 'a,
    {
        Parsing::new(self, parser)
    }

    #[inline]
    /// Start parsing with a parser.
    /// Just a wrapper of `ParsingInput::new(Box::new(self), parser)`.
    pub fn into_parsing<'a, O, F, P>(self, parser: P) -> ParsingInput<T, O, F>
    where
        T: 'a,
        P: Parser<'a, T, O, F>,
        F: Future<Output = O> + 'a,
    {
        ParsingInput::<T, O, F>::new(Box::new(self), parser)
    }
}

#[derive(Debug)]
/// A reference of Cursor for parsers.
/// This ensures you can't get &mut buf in parsers.
pub struct CursorRef<'a, T> {
    cursor: &'a mut Cursor<T>,
}

// you can't get &mut buf
impl<'a, T> CursorRef<'a, T> {
    #[inline]
    /// Get the current index.
    pub fn index(&self) -> usize {
        self.cursor.index
    }

    #[inline]
    /// Get the mutable reference of the current index.
    pub fn index_mut(&mut self) -> &mut usize {
        &mut self.cursor.index
    }

    #[inline]
    /// Utility function. Get the remaining items.
    pub fn remaining(&self) -> &[T] {
        &self.cursor.buf[self.cursor.index..]
    }

    #[inline]
    /// Get the buffer.
    pub fn buf(&self) -> &[T] {
        &self.cursor.buf
    }
}

#[repr(transparent)]
#[derive(Debug)]
/// A reference of Input.
/// This is used as input of parsers.
pub struct InputRef<'a, T>(&'a Input<T>);

impl<'a, T> InputRef<'a, T> {
    /// Do something with a mutable reference of Cursor.
    /// This crate is safe if you can't bring arguments to outside. I believe it is true.
    #[inline]
    pub fn scope_cursor_mut<O>(&mut self, jail: impl FnOnce(&mut CursorRef<T>) -> O) -> O {
        let mut cursor = unsafe { self.0.cursor_mut_unsafe() };
        debug_assert!(cursor.sanity_check());
        jail(&mut CursorRef {
            cursor: &mut cursor,
        })
    }

    /// Do something with a reference of Cursor.
    /// This crate is safe if you can't bring arguments to outside. I believe it is true.
    #[inline]
    pub fn scope_cursor<O>(&self, jail: impl FnOnce(&CursorRef<T>) -> O) -> O {
        let mut cursor = unsafe { self.0.cursor_mut_unsafe() };
        debug_assert!(cursor.sanity_check());
        jail(&CursorRef {
            cursor: &mut cursor,
        })
    }

    #[inline]
    /// Stop parsing until the buffer is extended.
    pub fn read(&mut self) -> impl Future<Output = ()> + '_ {
        self.0.read()
    }

    #[inline]
    /// Stop parsing until the buf.len() >= index + at_least.
    pub fn read_n(&mut self, at_least: usize) -> impl Future<Output = ()> + '_ {
        self.0.read_n(at_least)
    }
}

/// Parser trait
/// In this crate, a parser is defined as a function that takes an InputRef and returns a Future.
pub trait Parser<'a, T, O, F>: FnOnce(InputRef<'a, T>) -> F
where
    T: 'a,
    F: Future<Output = O> + 'a,
{
}

impl<'a, T, O, F, P> Parser<'a, T, O, F> for P
where
    T: 'a,
    P: FnOnce(InputRef<'a, T>) -> F,
    F: Future<Output = O> + 'a,
{
}

#[derive(Debug)]
/// Parsing state holds a reference of Input.
pub struct Parsing<'a, T, O, F> {
    input: &'a Input<T>,
    result: Option<O>,
    future: F,
}

impl<'a, T, O, F> Parsing<'a, T, O, F>
where
    F: Future<Output = O> + 'a,
{
    #[inline]
    /// Create a new Parsing from Input and a parser.
    pub fn new<P: Parser<'a, T, O, F>>(input: &'a mut Input<T>, parser: P) -> Self {
        // Dupe mutable ref
        Self {
            future: parser(InputRef(unsafe {
                std::mem::transmute::<&mut Input<T>, &Input<T>>(&mut *input)
            })),
            result: None,
            input,
        }
    }

    #[inline]
    /// Run the parser.
    /// Return true if the parser is done. You shouldn't call this anymore. It may leads to panic or never return.
    /// Return false if the parser is pending. You should add more items to the buffer.
    pub fn poll(&mut self) -> bool
    where
        F: Unpin,
    {
        let mut cx = Context::from_waker(noop_waker_ref());
        match Pin::new(&mut self.future).poll(&mut cx) {
            Poll::Ready(result) => {
                self.result = Some(result);
                true
            }
            Poll::Pending => false,
        }
    }
}

impl<'a, T, O, F> Parsing<'a, T, O, F> {
    #[inline]
    /// Get the reference of Cursor.
    pub fn cursor(&self) -> impl Deref<Target = Cursor<T>> + '_ {
        self.input.cursor()
    }

    #[inline]
    /// Get the mutable reference of Cursor.
    /// You can add items to the buffer.
    pub fn cursor_mut(&mut self) -> impl DerefMut<Target = Cursor<T>> + '_ {
        unsafe { self.input.cursor_mut_unsafe() }
    }

    #[inline]
    /// Get the result of the parser.
    /// Return Some(_) if the parser is done (= poll() returned true).
    /// Return None otherwise.
    pub fn into_result(self) -> Option<O> {
        self.result
    }
}

#[derive(Debug)]
/// Parsing state holds an Input.
pub struct ParsingInput<T, O, F> {
    // This makes input free to move.
    input: Box<Input<T>>,
    result: Option<O>,
    future: F,
}

impl<T, O, F> ParsingInput<T, O, F> {
    #[inline]
    /// Get the reference of Cursor.
    pub fn cursor(&self) -> impl Deref<Target = Cursor<T>> + '_ {
        self.input.cursor()
    }

    #[inline]
    /// Get the mutable reference of Cursor.
    pub fn cursor_mut(&mut self) -> impl DerefMut<Target = Cursor<T>> + '_ {
        self.input.cursor_mut()
    }

    #[inline]
    /// Get the result of the parser.
    pub fn result_mut(&mut self) -> Option<&mut O> {
        self.result.as_mut()
    }

    #[inline]
    /// Break the ParsingInput into Input.
    pub fn into_input(self) -> Box<Input<T>> {
        self.input
    }
}

impl<T, O, F> ParsingInput<T, O, F>
where
    F: Future<Output = O>,
{
    #[inline]
    /// Start parsing with a parser.
    pub fn new<'a, P: Parser<'a, T, O, F>>(input: Box<Input<T>>, parser: P) -> Self
    where
        T: 'a,
        F: 'a,
    {
        Self {
            future: parser(InputRef(unsafe {
                std::mem::transmute::<&Input<T>, &Input<T>>(input.as_ref())
            })),
            input,
            result: None,
        }
    }

    #[inline]
    /// Run the parser.
    /// Return true if the parser is done. You shouldn't call this anymore. It may leads to panic or never return.
    /// Return false if the parser is pending. You should add more items to the buffer.
    pub fn poll(&mut self) -> bool
    where
        F: Unpin,
    {
        let mut cx = Context::from_waker(noop_waker_ref());
        match Pin::new(&mut self.future).poll(&mut cx) {
            Poll::Ready(result) => {
                self.result = Some(result);
                true
            }
            Poll::Pending => false,
        }
    }
}

/// Anchoring the current index of the cursor.
/// Restore index when dropped.
pub struct Anchor<'a, 'b, T> {
    /// Reference of InputRef.
    pub iref: &'a mut InputRef<'b, T>,
    /// The index which is used to restore the cursor when drop.
    pub index: usize,
}

impl<'a, 'b, T> Anchor<'a, 'b, T> {
    #[inline]
    /// Create a new Anchor from InputRef.
    pub fn new(iref: &'a mut InputRef<'b, T>) -> Self {
        Self {
            index: iref.scope_cursor(|c| c.index()),
            iref,
        }
    }

    #[inline]
    /// Set the current index to the anchor.
    pub fn renew(&mut self) {
        self.index = self.iref.scope_cursor(|c| c.index());
    }

    #[inline]
    /// Forget the anchor.
    /// The current index of the cursor is unchanged.
    pub fn forget(self) -> &'a mut InputRef<'b, T> {
        let m = ManuallyDrop::new(self);

        (unsafe { std::ptr::read(&m.iref) }) as _
    }

    #[inline]
    /// Get the range of the start of the anchor to the current index.
    pub fn range(&self) -> Range<usize> {
        self.index..self.iref.scope_cursor(|c| c.index())
    }
}

impl<'a, 'b, T> Drop for Anchor<'a, 'b, T> {
    #[inline]
    fn drop(&mut self) {
        self.iref.scope_cursor_mut(|c| {
            *c.index_mut() = self.index;
        });
    }
}

impl<'a, 'b, T> Deref for Anchor<'a, 'b, T> {
    type Target = &'a mut InputRef<'b, T>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.iref
    }
}

impl<'a, 'b, T> DerefMut for Anchor<'a, 'b, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.iref
    }
}

/// Match a single item
/// Advance the cursor index if the item is matched.
pub async fn just<T>(input: &mut InputRef<'_, T>, t: T) -> Result<usize, ()>
where
    T: PartialEq,
{
    input.read_n(1).await;

    input.scope_cursor_mut(|cursor| {
        if cursor.remaining()[0] == t {
            let index = cursor.index();
            *cursor.index_mut() += 1;
            Ok(index)
        } else {
            Err(())
        }
    })
}

/// Match a sequence of items
/// Advance the cursor index if the sequence is matched.
pub async fn tag<T>(input: &mut InputRef<'_, T>, tag: &[T]) -> Result<Range<usize>, ()>
where
    T: PartialEq,
{
    let mut index = 0;
    loop {
        let flow = input.scope_cursor_mut(|cursor| {
            let remaining = cursor.remaining();
            let len = remaining.len();
            if len < tag.len() {
                if !tag[index..].starts_with(&remaining[index..]) {
                    return ControlFlow::Break(Err(()));
                }
                index = len;
                ControlFlow::Continue(())
            } else {
                ControlFlow::Break(if !tag[index..].starts_with(&remaining[..tag.len()]) {
                    Err(())
                } else {
                    *cursor.index_mut() += tag.len();
                    Ok(cursor.index()..cursor.index() + tag.len())
                })
            }
        });
        match flow {
            ControlFlow::Continue(()) => {
                input.read().await;
            }

            ControlFlow::Break(r) => {
                return r;
            }
        }
    }
}

/// Match zero or more items until cond is true.
/// Return the range of the matched items including zero range.
/// Advance the cursor index as much as matched.
pub async fn many0<T>(
    input: &mut InputRef<'_, T>,
    mut cond: impl FnMut(&T) -> bool,
) -> Range<usize> {
    let start = input.scope_cursor(|c| c.index());

    loop {
        if let Some(r) = input.scope_cursor_mut(|c| {
            for (i, item) in c.remaining().iter().enumerate() {
                if !cond(item) {
                    *c.index_mut() += i;
                    return Some(start..c.index());
                }
            }

            let len = c.buf().len();
            *c.index_mut() = len;
            None
        }) {
            return r;
        }

        input.read().await;
    }
}

/// Match one or more items until cond is true.
/// Return the range of the matched items including or Err for no match at all.
/// Advance the cursor index as much as matched.
pub async fn many1<T>(
    input: &mut InputRef<'_, T>,
    mut cond: impl FnMut(&T) -> bool,
) -> Result<Range<usize>, ()> {
    let start = input.scope_cursor(|c| c.index());

    loop {
        if let Some(r) = input.scope_cursor_mut(|c| {
            for (i, item) in c.remaining().iter().enumerate() {
                if !cond(item) {
                    *c.index_mut() += i;
                    return Some(start..c.index());
                }
            }

            let len = c.buf().len();
            *c.index_mut() = len;
            None
        }) {
            if r.start == r.end {
                return Err(());
            } else {
                return Ok(r);
            }
        }

        input.read().await;
    }
}

#[cfg(test)]
mod tests {
    use std::mem::take;

    use futures::FutureExt;

    use super::*;

    #[test]
    fn test_read() {
        let mut input = Input::new(Cursor {
            buf: vec![1, 2, 3],
            index: 0,
        });

        let mut p = input.start_parsing(|mut iref| {
            async move {
                iref.read().await;
            }
            .boxed_local()
        });

        assert!(!p.poll());
        p.cursor_mut().buf.push(4);
        assert!(p.poll());
    }

    #[test]
    fn test_get3() {
        let mut input = Input::new(Cursor {
            buf: Vec::new(),
            index: 0,
        });

        let mut p = input.start_parsing(|mut iref| {
            async move {
                iref.read_n(3).await;
            }
            .boxed_local()
        });

        assert!(!p.poll());
        p.cursor_mut().buf.push(1);
        assert!(!p.poll());
        p.cursor_mut().buf.push(2);
        assert!(!p.poll());
        p.cursor_mut().buf.push(3);
        assert!(p.poll());
    }

    #[test]
    fn test_many0() {
        let mut input = Input::new(Cursor {
            buf: Vec::new(),
            index: 0,
        });

        let mut p = input.start_parsing(|mut iref| {
            async move { many0(&mut iref, |x| *x % 2 == 0).await }.boxed_local()
        });

        p.cursor_mut().buf.push(0);
        assert!(!p.poll());

        p.cursor_mut().buf.push(2);
        assert!(!p.poll());

        p.cursor_mut().buf.push(4);
        assert!(!p.poll());

        p.cursor_mut().buf.push(1);
        assert!(p.poll());

        assert_eq!(p.into_result(), Some(0..3));
    }

    #[test]
    fn test_parsing() {
        let mut input = Input::new(Cursor {
            buf: Vec::new(),
            index: 0,
        });

        let mut parsing = input.start_parsing(move |mut iref: InputRef<u8>| {
            async move {
                let alpha0 = many0(&mut iref, |x: &u8| x.is_ascii_alphabetic()).await;
                dbg!(&alpha0);
                let digit = many0(&mut iref, |x: &u8| x.is_ascii_digit()).await;
                dbg!(&digit);
                let alpha2 = many0(&mut iref, |x: &u8| x.is_ascii_alphabetic()).await;

                (alpha0, digit, alpha2)
            }
            .boxed_local()
        });

        parsing.cursor_mut().buf.extend(b"abc");
        assert!(!parsing.poll());
        parsing.cursor_mut().buf.extend(b"123");
        assert!(!parsing.poll());

        // soundness test
        let c = take(parsing.cursor_mut().deref_mut());
        parsing.cursor_mut().index = c.index;
        parsing.cursor_mut().buf.clone_from(&c.buf);

        parsing.cursor_mut().buf.extend(b"abc");
        assert!(!parsing.poll());
        parsing.cursor_mut().buf.extend(b";");
        assert!(parsing.poll());
        assert_eq!(parsing.into_result(), Some((0..3, 3..6, 6..9)));
    }

    #[test]
    fn test_parsing_input() {
        let input = Input::new(Cursor {
            buf: Vec::new(),
            index: 0,
        });

        let parsing_input = input.into_parsing(|mut iref: InputRef<u8>| {
            async move {
                let alpha0 = many0(&mut iref, |x: &u8| x.is_ascii_alphabetic()).await;
                dbg!(&alpha0);
                let digit = many0(&mut iref, |x: &u8| x.is_ascii_digit()).await;
                dbg!(&digit);
                let alpha2 = many0(&mut iref, |x: &u8| x.is_ascii_alphabetic()).await;

                (alpha0, digit, alpha2)
            }
            .boxed_local()
        });

        // test move
        let mut parsing_input = parsing_input;

        parsing_input.cursor_mut().buf.extend(b"abc");
        assert!(!parsing_input.poll());
        parsing_input.cursor_mut().buf.extend(b"123");
        assert!(!parsing_input.poll());
        parsing_input.cursor_mut().buf.extend(b"abc");
        assert!(!parsing_input.poll());
        parsing_input.cursor_mut().buf.extend(b";");
        assert!(parsing_input.poll());
        assert_eq!(parsing_input.result_mut(), Some(&mut (0..3, 3..6, 6..9)));
    }

    #[test]
    fn test_anchor() {
        async fn parser(
            iref: &mut InputRef<'_, u8>,
        ) -> Result<(Range<usize>, Range<usize>, Range<usize>), ()> {
            let mut anchor = Anchor::new(iref);

            let alpha0 = many1(&mut anchor, |x: &u8| x.is_ascii_alphabetic()).await?;
            dbg!(&alpha0);
            let digit = many1(&mut anchor, |x: &u8| x.is_ascii_digit()).await?;
            dbg!(&digit);
            let alpha2 = many1(&mut anchor, |x: &u8| x.is_ascii_alphabetic()).await?;

            anchor.forget();

            Ok((alpha0, digit, alpha2))
        }

        let mut input = Input::new(Cursor {
            buf: Vec::new(),
            index: 0,
        });

        let mut parsing =
            input.start_parsing(|mut iref| async move { parser(&mut iref).await }.boxed_local());

        parsing.cursor_mut().buf.extend(b"abc");

        assert!(!parsing.poll());

        parsing.cursor_mut().buf.extend(b"123");

        assert!(!parsing.poll());

        parsing.cursor_mut().buf.extend(b";");

        assert!(parsing.poll());

        assert_eq!(parsing.into_result(), Some(Err(())));
        assert_eq!(input.cursor().index, 0);
    }

    #[test]
    fn test_early_return() {
        let mut input = Input::new(Cursor {
            buf: vec![1, 2, 3],
            index: 0,
        });

        let mut parsing = input.start_parsing(|mut iref| {
            async move { just(&mut iref, 1).await.is_ok() || just(&mut iref, 2).await.is_ok() }
                .boxed_local()
        });

        assert!(parsing.poll());

        assert_eq!(parsing.into_result(), Some(true));
        assert_eq!(input.cursor().index, 1);
    }

    #[test]
    fn test_tag() {
        {
            let mut input = Input::new(Cursor {
                buf: vec![1, 2, 3],
                index: 0,
            });

            let mut parsing = input.start_parsing(|mut iref| {
                async move { tag(&mut iref, &[1, 2, 4]).await.is_ok() }.boxed_local()
            });

            assert!(parsing.poll());

            assert_eq!(parsing.into_result(), Some(false));
            assert_eq!(input.cursor().index, 0);
        }

        {
            let mut input = Input::new(Cursor {
                buf: vec![1, 2, 3],
                index: 0,
            });

            let mut parsing = input.start_parsing(|mut iref| {
                async move { tag(&mut iref, &[1, 2, 3]).await.is_ok() }.boxed_local()
            });

            assert!(parsing.poll());

            assert_eq!(parsing.into_result(), Some(true));
            assert_eq!(input.cursor().index, 3);
        }
    }
}