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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
use crate::*;
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use futures_core::{FusedStream, Stream};

/// Helpers for chaining [`OrderedStream`]s.
pub trait OrderedStreamExt: OrderedStream {
    /// Apply a closure to the data.
    ///
    /// This does not change the ordering.
    fn map<F, R>(self, f: F) -> Map<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Data) -> R,
    {
        Map { stream: self, f }
    }

    /// Apply a closure to the items that has access to the ordering data.
    fn map_item<F, R>(self, f: F) -> MapItem<Self, F>
    where
        Self: Sized,
        F: FnMut(&Self::Ordering, Self::Data) -> R,
    {
        MapItem { stream: self, f }
    }

    /// Apply a closure to the items that can change the type of the ordering value.
    ///
    /// A bidirectional mapping for ordering values is required in order to remap `before` values.
    /// It is the caller's responsibility to ensure that the items in the mapped stream still meet
    /// the ordering requirements that [`OrderedStream`] expects.
    fn map_ordering<NewOrdering, NewData, MapInto, MapFrom>(
        self,
        map_into: MapInto,
        map_from: MapFrom,
    ) -> MapOrdering<Self, MapInto, MapFrom>
    where
        Self: Sized,
        MapInto: FnMut(Self::Ordering, Self::Data) -> (NewOrdering, NewData),
        MapFrom: FnMut(&NewOrdering) -> Option<Self::Ordering>,
        NewOrdering: Ord,
    {
        MapOrdering {
            stream: self,
            map_into,
            map_from,
        }
    }

    fn filter<F>(self, filter: F) -> Filter<Self, F>
    where
        Self: Sized,
        F: FnMut(&Self::Data) -> bool,
    {
        Filter {
            stream: self,
            filter,
        }
    }

    fn filter_map<F, R>(self, filter: F) -> FilterMap<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Data) -> Option<R>,
    {
        FilterMap {
            stream: self,
            filter,
        }
    }

    /// Apply a closure that produces a [`Future`] to items, running the future on each item in
    /// sequence before processing the next.
    ///
    /// This has the side effect of buffering items that are not before the requested ordering
    /// point; you can use [`ready`](core::future::ready) as the closure to take advantage of this
    /// behavior if you don't want to buffer items yourself.
    fn then<F, Fut>(self, then: F) -> Then<Self, F, Fut>
    where
        Self: Sized,
        F: FnMut(Self::Data) -> Fut,
        Fut: Future,
    {
        Then {
            stream: self,
            then,
            future: ThenItem::Idle,
        }
    }

    /// Convert this into a [`Stream`], discarding the ordering information.
    fn into_stream(self) -> IntoStream<Self>
    where
        Self: Sized,
    {
        IntoStream { stream: self }
    }

    /// Convert this into a [`Stream`], keeping the ordering objects.
    fn into_tuple_stream(self) -> IntoTupleStream<Self>
    where
        Self: Sized,
    {
        IntoTupleStream { stream: self }
    }

    /// Convert this into a [`Stream`], keeping only the ordering objects.
    fn into_ordering(self) -> IntoOrdering<Self>
    where
        Self: Sized,
    {
        IntoOrdering { stream: self }
    }

    /// Return the next item in this stream.
    fn next(&mut self) -> Next<'_, Self>
    where
        Self: Unpin,
    {
        Next {
            stream: Pin::new(self),
        }
    }

    /// Return a [`PollResult`] corresponding to the next item in the stream.
    fn next_before<'a>(&'a mut self, before: Option<&'a Self::Ordering>) -> NextBefore<'a, Self>
    where
        Self: Unpin,
    {
        NextBefore {
            stream: Pin::new(self),
            before,
        }
    }

    fn peekable(self) -> Peekable<Self>
    where
        Self: Sized,
    {
        Peekable {
            stream: self,
            item: None,
            is_terminated: false,
        }
    }
}

impl<T: ?Sized + OrderedStream> OrderedStreamExt for T {}

pin_project_lite::pin_project! {
    /// An [`OrderedStream`] wrapper around a [`Stream`].
    ///
    /// This does not use any future or past knowledge of elements, and so is suitable if the
    /// stream rarely or never blocks.  Prefer using [`FromStream`] if you plan to filter or join
    /// this stream and want other streams to be able to make progress while this one blocks.
    #[derive(Debug)]
    pub struct FromStreamDirect<S, F> {
        #[pin]
        stream: S,
        split_item: F,
    }
}

impl<S, F> FromStreamDirect<S, F> {
    /// Create a new [`OrderedStream`] by applying a `split_item` closure to each element
    /// produced by the original stream.
    pub fn new<Ordering, Data>(stream: S, split_item: F) -> Self
    where
        S: Stream,
        F: FnMut(S::Item) -> (Ordering, Data),
        Ordering: Ord,
    {
        Self { stream, split_item }
    }

    /// Helper function to simplify the creation of a stream when you have a get_ordering function.
    pub fn with_ordering<Ordering>(
        stream: S,
        mut get_ordering: F,
    ) -> FromStreamDirect<S, impl FnMut(S::Item) -> (Ordering, S::Item)>
    where
        S: Stream,
        F: FnMut(&S::Item) -> Ordering,
        Ordering: Ord,
    {
        FromStreamDirect::new(stream, move |data| {
            let ordering = get_ordering(&data);
            (ordering, data)
        })
    }
}

impl<S, F, Ordering, Data> OrderedStream for FromStreamDirect<S, F>
where
    S: Stream,
    F: FnMut(S::Item) -> (Ordering, Data),
    Ordering: Ord,
{
    type Data = Data;
    type Ordering = Ordering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        _: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let this = self.project();
        let split_item = this.split_item;
        this.stream.poll_next(cx).map(|opt| match opt {
            None => PollResult::Terminated,
            Some(data) => {
                let (ordering, data) = split_item(data);
                PollResult::Item { data, ordering }
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

impl<S, F, Ordering, Data> FusedOrderedStream for FromStreamDirect<S, F>
where
    S: FusedStream,
    F: FnMut(S::Item) -> (Ordering, Data),
    Ordering: Ord,
{
    fn is_terminated(&self) -> bool {
        self.stream.is_terminated()
    }
}

pin_project_lite::pin_project! {
    /// An [`OrderedStream`] wrapper around a [`Stream`].
    ///
    /// Unlike [`FromStream`], the items in the [`Stream`] are themselves ordered with no
    /// additional data.
    #[derive(Debug)]
    pub struct FromSortedStream<S> {
        #[pin]
        pub stream: S,
    }
}

impl<S> FromSortedStream<S> {
    /// Create a new [`OrderedStream`] by applying a `split_item` closure to each element
    /// produced by the original stream.
    pub fn new(stream: S) -> Self
    where
        S: Stream,
        S::Item: Ord,
    {
        Self { stream }
    }
}

impl<S> OrderedStream for FromSortedStream<S>
where
    S: Stream,
    S::Item: Ord,
{
    type Data = ();
    type Ordering = S::Item;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        _: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let this = self.project();
        this.stream.poll_next(cx).map(|opt| match opt {
            None => PollResult::Terminated,
            Some(ordering) => PollResult::Item { data: (), ordering },
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

impl<S> FusedOrderedStream for FromSortedStream<S>
where
    S: FusedStream,
    S::Item: Ord,
{
    fn is_terminated(&self) -> bool {
        self.stream.is_terminated()
    }
}

pin_project_lite::pin_project! {
    /// An [`OrderedStream`] wrapper around a [`Stream`].
    ///
    /// This caches the last-used ordering point returned by the stream and uses it to produce
    /// NoneBefore results.  This makes it suitable for using to adapt streams that are filtered
    /// or mapped before joining.  It still relies on the original stream producing a later-ordered
    /// element to allow other streams to progress, however.
    #[derive(Debug)]
    pub struct FromStream<S, F, Ordering> {
        #[pin]
        stream: S,
        split_item: F,
        last: Option<Ordering>,
    }
}

impl<S, F, Ordering> FromStream<S, F, Ordering>
where
    S: Stream,
    Ordering: Ord + Clone,
{
    /// Create a new [`OrderedStream`] by applying a `split_item` closure to each element
    /// produced by the original stream.
    pub fn new<Data>(stream: S, split_item: F) -> Self
    where
        F: FnMut(S::Item) -> (Ordering, Data),
    {
        FromStream {
            stream,
            split_item,
            last: None,
        }
    }

    /// Helper function to simplify the creation of a stream when you have a get_ordering function.
    pub fn with_ordering(
        stream: S,
        mut get_ordering: F,
    ) -> FromStream<S, impl FnMut(S::Item) -> (Ordering, S::Item), Ordering>
    where
        F: FnMut(&S::Item) -> Ordering,
    {
        FromStream::new(stream, move |data| {
            let ordering = get_ordering(&data);
            (ordering, data)
        })
    }
}

impl<S, F, Ordering, Data> OrderedStream for FromStream<S, F, Ordering>
where
    S: Stream,
    F: FnMut(S::Item) -> (Ordering, Data),
    Ordering: Ord + Clone,
{
    type Data = Data;
    type Ordering = Ordering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Ordering, Data>> {
        let this = self.project();
        let split_item = this.split_item;
        let last = this.last;
        if let (Some(last), Some(before)) = (last.as_ref(), before) {
            if last >= before {
                return Poll::Ready(PollResult::NoneBefore);
            }
        }
        this.stream.poll_next(cx).map(|opt| match opt {
            None => PollResult::Terminated,
            Some(item) => {
                let (ordering, data) = split_item(item);
                *last = Some(ordering.clone());
                PollResult::Item { data, ordering }
            }
        })
    }

    fn position_hint(&self) -> Option<MaybeBorrowed<'_, Self::Ordering>> {
        self.last.as_ref().map(MaybeBorrowed::Borrowed)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

impl<S, F, Ordering, Data> FusedOrderedStream for FromStream<S, F, Ordering>
where
    S: FusedStream,
    F: FnMut(S::Item) -> (Ordering, Data),
    Ordering: Ord + Clone,
{
    fn is_terminated(&self) -> bool {
        self.stream.is_terminated()
    }
}

pin_project_lite::pin_project! {
    /// A [`Stream`] for the [`into_stream`](OrderedStreamExt::into_stream) function.
    #[derive(Debug)]
    pub struct IntoStream<S> {
        #[pin]
        stream: S,
    }
}

impl<S: OrderedStream> Stream for IntoStream<S> {
    type Item = S::Data;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.project()
            .stream
            .poll_next_before(cx, None)
            .map(|r| r.into_data())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

impl<S> FusedStream for IntoStream<S>
where
    S: FusedOrderedStream,
{
    fn is_terminated(&self) -> bool {
        self.stream.is_terminated()
    }
}

pin_project_lite::pin_project! {
    /// A [`Stream`] for the [`into_tuple_stream`](OrderedStreamExt::into_tuple_stream) function.
    #[derive(Debug)]
    pub struct IntoTupleStream<S> {
        #[pin]
        stream: S,
    }
}

impl<S: OrderedStream> Stream for IntoTupleStream<S> {
    type Item = (S::Ordering, S::Data);

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.project()
            .stream
            .poll_next_before(cx, None)
            .map(|r| r.into_tuple())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

impl<S> FusedStream for IntoTupleStream<S>
where
    S: FusedOrderedStream,
{
    fn is_terminated(&self) -> bool {
        self.stream.is_terminated()
    }
}

pin_project_lite::pin_project! {
    /// A [`Stream`] for the [`into_ordering`](OrderedStreamExt::into_ordering) function.
    #[derive(Debug)]
    pub struct IntoOrdering<S> {
        #[pin]
        stream: S,
    }
}

impl<S: OrderedStream> Stream for IntoOrdering<S> {
    type Item = S::Ordering;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.project()
            .stream
            .poll_next_before(cx, None)
            .map(|r| r.into_tuple().map(|t| t.0))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

impl<S> FusedStream for IntoOrdering<S>
where
    S: FusedOrderedStream,
{
    fn is_terminated(&self) -> bool {
        self.stream.is_terminated()
    }
}

pin_project_lite::pin_project! {
    /// An [`OrderedStream`] wrapper around an [`OrderedFuture`].
    #[derive(Debug)]
    pub struct FromFuture<F> {
        #[pin]
        future: Option<F>,
    }
}

impl<F: OrderedFuture> From<F> for FromFuture<F> {
    fn from(future: F) -> Self {
        Self {
            future: Some(future),
        }
    }
}

impl<F: OrderedFuture> OrderedStream for FromFuture<F> {
    type Data = F::Output;
    type Ordering = F::Ordering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let mut this = self.project();
        match this.future.as_mut().as_pin_mut() {
            Some(future) => match future.poll_before(cx, before) {
                Poll::Ready(Some((ordering, data))) => {
                    this.future.set(None);
                    Poll::Ready(PollResult::Item { data, ordering })
                }
                Poll::Ready(None) => Poll::Ready(PollResult::NoneBefore),
                Poll::Pending => Poll::Pending,
            },
            None => Poll::Ready(PollResult::Terminated),
        }
    }

    fn position_hint(&self) -> Option<MaybeBorrowed<'_, Self::Ordering>> {
        self.future.as_ref().and_then(|f| f.position_hint())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.future.is_some() {
            (1, Some(1))
        } else {
            (0, Some(0))
        }
    }
}

impl<F: OrderedFuture> FusedOrderedStream for FromFuture<F> {
    fn is_terminated(&self) -> bool {
        self.future.is_none()
    }
}

pin_project_lite::pin_project! {
    /// A stream for the [`map`](OrderedStreamExt::map) function.
    #[derive(Debug)]
    pub struct Map<S, F> {
        #[pin]
        stream: S,
        f: F,
    }
}

impl<S, F> Map<S, F> {
    /// Convert to source stream.
    pub fn into_inner(self) -> S {
        self.stream
    }
}

impl<S, F, R> OrderedStream for Map<S, F>
where
    S: OrderedStream,
    F: FnMut(S::Data) -> R,
{
    type Data = R;
    type Ordering = S::Ordering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let this = self.project();
        let f = this.f;
        this.stream
            .poll_next_before(cx, before)
            .map(|res| res.map_data(f))
    }

    fn position_hint(&self) -> Option<MaybeBorrowed<'_, Self::Ordering>> {
        self.stream.position_hint()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

pin_project_lite::pin_project! {
    /// A stream for the [`map_item`](OrderedStreamExt::map_item) function.
    #[derive(Debug)]
    pub struct MapItem<S, F> {
        #[pin]
        stream: S,
        f: F,
    }
}

impl<S, F, R> OrderedStream for MapItem<S, F>
where
    S: OrderedStream,
    F: FnMut(&S::Ordering, S::Data) -> R,
{
    type Data = R;
    type Ordering = S::Ordering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let this = self.project();
        let f = this.f;
        this.stream
            .poll_next_before(cx, before)
            .map(|res| match res {
                PollResult::Item { data, ordering } => {
                    let data = f(&ordering, data);
                    PollResult::Item { data, ordering }
                }
                PollResult::NoneBefore => PollResult::NoneBefore,
                PollResult::Terminated => PollResult::Terminated,
            })
    }

    fn position_hint(&self) -> Option<MaybeBorrowed<'_, Self::Ordering>> {
        self.stream.position_hint()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

pin_project_lite::pin_project! {
    /// A stream for the [`map_ordering`](OrderedStreamExt::map_ordering) function.
    #[derive(Debug)]
    pub struct MapOrdering<S, MapInto, MapFrom> {
        #[pin]
        stream: S,
        map_into: MapInto, map_from: MapFrom,
    }
}

impl<S, MapInto, MapFrom, NewOrdering, NewData> OrderedStream for MapOrdering<S, MapInto, MapFrom>
where
    S: OrderedStream,
    MapInto: FnMut(S::Ordering, S::Data) -> (NewOrdering, NewData),
    MapFrom: FnMut(&NewOrdering) -> Option<S::Ordering>,
    NewOrdering: Ord,
{
    type Data = NewData;
    type Ordering = NewOrdering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let this = self.project();
        let map_into = this.map_into;
        let before = before.and_then(this.map_from);
        this.stream
            .poll_next_before(cx, before.as_ref())
            .map(|res| match res {
                PollResult::Item { data, ordering } => {
                    let (ordering, data) = map_into(ordering, data);
                    PollResult::Item { data, ordering }
                }
                PollResult::NoneBefore => PollResult::NoneBefore,
                PollResult::Terminated => PollResult::Terminated,
            })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

pin_project_lite::pin_project! {
    /// A stream for the [`filter`](OrderedStreamExt::filter) function.
    #[derive(Debug)]
    pub struct Filter<S, F> {
        #[pin]
        stream: S,
        filter: F,
    }
}

impl<S, F> OrderedStream for Filter<S, F>
where
    S: OrderedStream,
    F: FnMut(&S::Data) -> bool,
{
    type Data = S::Data;
    type Ordering = S::Ordering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let mut this = self.project();
        loop {
            match this.stream.as_mut().poll_next_before(cx, before).into() {
                PollState::Pending => return Poll::Pending,
                PollState::Terminated => return Poll::Ready(PollResult::Terminated),
                PollState::NoneBefore => return Poll::Ready(PollResult::NoneBefore),
                PollState::Item(data, ordering) => {
                    if (this.filter)(&data) {
                        return Poll::Ready(PollResult::Item { data, ordering });
                    }
                }
            }
        }
    }

    fn position_hint(&self) -> Option<MaybeBorrowed<'_, Self::Ordering>> {
        self.stream.position_hint()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, self.stream.size_hint().1)
    }
}

pin_project_lite::pin_project! {
    /// A stream for the [`filter_map`](OrderedStreamExt::filter_map) function.
    #[derive(Debug)]
    pub struct FilterMap<S, F> {
        #[pin]
        stream: S,
        filter: F,
    }
}

impl<S, F, R> OrderedStream for FilterMap<S, F>
where
    S: OrderedStream,
    F: FnMut(S::Data) -> Option<R>,
{
    type Data = R;
    type Ordering = S::Ordering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let mut this = self.project();
        loop {
            match this.stream.as_mut().poll_next_before(cx, before).into() {
                PollState::Pending => return Poll::Pending,
                PollState::Terminated => return Poll::Ready(PollResult::Terminated),
                PollState::NoneBefore => return Poll::Ready(PollResult::NoneBefore),
                PollState::Item(data, ordering) => match (this.filter)(data) {
                    Some(data) => return Poll::Ready(PollResult::Item { data, ordering }),
                    None => continue,
                },
            }
        }
    }

    fn position_hint(&self) -> Option<MaybeBorrowed<'_, Self::Ordering>> {
        self.stream.position_hint()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, self.stream.size_hint().1)
    }
}

pin_project_lite::pin_project! {
    #[project = ThenProj]
    #[project_replace = ThenDone]
    #[derive(Debug)]
    enum ThenItem<Fut, T> {
        Running { #[pin] future: Fut, ordering: T },
        Idle,
    }
}

pin_project_lite::pin_project! {
    /// A stream for the [`then`](OrderedStreamExt::then) function.
    #[derive(Debug)]
    pub struct Then<S, F, Fut>
        where S: OrderedStream
    {
        #[pin]
        stream: S,
        then: F,
        #[pin]
        future: ThenItem<Fut, S::Ordering>,
    }
}

impl<S, F, Fut> OrderedStream for Then<S, F, Fut>
where
    S: OrderedStream,
    F: FnMut(S::Data) -> Fut,
    Fut: Future,
{
    type Data = Fut::Output;
    type Ordering = S::Ordering;

    fn poll_next_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&Self::Ordering>,
    ) -> Poll<PollResult<Self::Ordering, Self::Data>> {
        let mut this = self.project();
        loop {
            if let ThenProj::Running { future, ordering } = this.future.as_mut().project() {
                // Because we know the next ordering, we can answer questions about it now.
                if let Some(before) = before {
                    if *ordering >= *before {
                        return Poll::Ready(PollResult::NoneBefore);
                    }
                }

                if let Poll::Ready(data) = future.poll(cx) {
                    if let ThenDone::Running { ordering, .. } =
                        this.future.as_mut().project_replace(ThenItem::Idle)
                    {
                        return Poll::Ready(PollResult::Item { data, ordering });
                    }
                } else {
                    return Poll::Pending;
                }
            }
            match this.stream.as_mut().poll_next_before(cx, before).into() {
                PollState::Pending => return Poll::Pending,
                PollState::Terminated => return Poll::Ready(PollResult::Terminated),
                PollState::NoneBefore => return Poll::Ready(PollResult::NoneBefore),
                PollState::Item(data, ordering) => {
                    this.future.set(ThenItem::Running {
                        future: (this.then)(data),
                        ordering,
                    });
                }
            }
        }
    }

    fn position_hint(&self) -> Option<MaybeBorrowed<'_, Self::Ordering>> {
        match &self.future {
            ThenItem::Running { ordering, .. } => Some(MaybeBorrowed::Borrowed(ordering)),
            ThenItem::Idle => self.stream.position_hint(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let (min, max) = self.stream.size_hint();
        match self.future {
            ThenItem::Running { .. } => (min.saturating_add(1), max.and_then(|v| v.checked_add(1))),
            ThenItem::Idle => (min, max),
        }
    }
}

/// A future for the [`next`](OrderedStreamExt::next) function.
#[derive(Debug)]
pub struct Next<'a, S: ?Sized> {
    stream: Pin<&'a mut S>,
}

impl<'a, S: ?Sized> Unpin for Next<'a, S> {}

impl<'a, S> Future for Next<'a, S>
where
    S: OrderedStream + ?Sized,
{
    type Output = Option<S::Data>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Data>> {
        self.stream
            .as_mut()
            .poll_next_before(cx, None)
            .map(PollResult::into_data)
    }
}

/// A future for the [`next_before`](OrderedStreamExt::next_before) function.
#[derive(Debug)]
pub struct NextBefore<'a, S>
where
    S: OrderedStream + ?Sized,
{
    stream: Pin<&'a mut S>,
    before: Option<&'a S::Ordering>,
}

impl<'a, S: OrderedStream + ?Sized> Unpin for NextBefore<'a, S> {}

impl<'a, S> Future for NextBefore<'a, S>
where
    S: OrderedStream + ?Sized,
{
    type Output = PollResult<S::Ordering, S::Data>;

    fn poll(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<PollResult<S::Ordering, S::Data>> {
        let before = self.before;
        self.stream.as_mut().poll_next_before(cx, before)
    }
}

pin_project_lite::pin_project! {
    /// A stream for the [`peekable`](OrderedStreamExt::peekable) function.
    #[derive(Debug)]
    pub struct Peekable<S: OrderedStream> {
        #[pin]
        stream: S,
        is_terminated: bool,
        item: Option<(S::Ordering, S::Data)>,
    }
}

impl<S: OrderedStream> Peekable<S> {
    /// Convert into the source stream.
    ///
    /// This method returns the source stream along with any buffered item and its
    /// ordering.
    pub fn into_inner(self) -> (S, Option<(S::Data, S::Ordering)>) {
        (self.stream, self.item.map(|(o, d)| (d, o)))
    }

    /// The current item, without polling
    pub(crate) fn item(&self) -> Option<&(S::Ordering, S::Data)> {
        self.item.as_ref()
    }

    /// Peek on the next item in the stream
    pub fn poll_peek_before(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&S::Ordering>,
    ) -> Poll<PollResult<&S::Ordering, &mut S::Data>> {
        let mut this = self.project();
        if *this.is_terminated {
            return Poll::Ready(PollResult::Terminated);
        }
        let stream = this.stream.as_mut();
        if this.item.is_none() {
            match stream.poll_next_before(cx, before) {
                Poll::Ready(PollResult::Item { ordering, data }) => {
                    *this.item = Some((ordering, data));
                }
                Poll::Ready(PollResult::NoneBefore) => return Poll::Ready(PollResult::NoneBefore),
                Poll::Ready(PollResult::Terminated) => {
                    *this.is_terminated = true;
                    return Poll::Ready(PollResult::Terminated);
                }
                Poll::Pending => return Poll::Pending,
            }
        }
        let item = this.item.as_mut().unwrap();
        Poll::Ready(PollResult::Item {
            ordering: &item.0,
            data: &mut item.1,
        })
    }
}

impl<S: OrderedStream> OrderedStream for Peekable<S> {
    type Ordering = S::Ordering;
    type Data = S::Data;

    fn poll_next_before(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        before: Option<&S::Ordering>,
    ) -> Poll<PollResult<S::Ordering, S::Data>> {
        match self.as_mut().poll_peek_before(cx, before) {
            Poll::Ready(PollResult::Item { .. }) => {
                let (ordering, data) = self.project().item.take().unwrap();
                Poll::Ready(PollResult::Item { ordering, data })
            }
            Poll::Ready(PollResult::NoneBefore) => Poll::Ready(PollResult::NoneBefore),
            Poll::Ready(PollResult::Terminated) => Poll::Ready(PollResult::Terminated),
            Poll::Pending => Poll::Pending,
        }
    }

    fn position_hint(&self) -> Option<MaybeBorrowed<'_, Self::Ordering>> {
        match &self.item {
            Some((ordering, _)) => Some(MaybeBorrowed::Borrowed(ordering)),
            None => self.stream.position_hint(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let (min, max) = if self.is_terminated {
            (0, Some(0))
        } else {
            self.stream.size_hint()
        };
        if self.item.is_some() {
            (min.saturating_add(1), max.and_then(|v| v.checked_add(1)))
        } else {
            (min, max)
        }
    }
}

impl<S: OrderedStream> FusedOrderedStream for Peekable<S> {
    fn is_terminated(&self) -> bool {
        self.is_terminated
    }
}