1
1
use futures:: executor:: block_on;
2
- use futures:: io:: AsyncBufReadExt ;
3
- use std:: io:: Cursor ;
2
+ use futures:: future:: Future ;
3
+ use futures:: io:: { AsyncRead , AsyncBufRead , AsyncBufReadExt } ;
4
+ use futures:: task:: { Context , Poll } ;
5
+ use futures_test:: task:: noop_context;
6
+ use std:: cmp;
7
+ use std:: io:: { self , Cursor } ;
8
+ use std:: pin:: Pin ;
4
9
5
10
#[ test]
6
11
fn read_until ( ) {
@@ -20,3 +25,73 @@ fn read_until() {
20
25
assert_eq ! ( block_on( buf. read_until( b'3' , & mut v) ) . unwrap( ) , 0 ) ;
21
26
assert_eq ! ( v, [ ] ) ;
22
27
}
28
+
29
+ fn run < F : Future + Unpin > ( mut f : F ) -> F :: Output {
30
+ let mut cx = noop_context ( ) ;
31
+ loop {
32
+ if let Poll :: Ready ( x) = Pin :: new ( & mut f) . poll ( & mut cx) {
33
+ return x;
34
+ }
35
+ }
36
+ }
37
+
38
+ struct MaybePending < ' a > {
39
+ inner : & ' a [ u8 ] ,
40
+ ready : bool ,
41
+ }
42
+
43
+ impl < ' a > MaybePending < ' a > {
44
+ fn new ( inner : & ' a [ u8 ] ) -> Self {
45
+ Self { inner, ready : false }
46
+ }
47
+ }
48
+
49
+ impl AsyncRead for MaybePending < ' _ > {
50
+ fn poll_read ( self : Pin < & mut Self > , _: & mut Context < ' _ > , _: & mut [ u8 ] )
51
+ -> Poll < io:: Result < usize > >
52
+ {
53
+ unimplemented ! ( )
54
+ }
55
+ }
56
+
57
+ impl AsyncBufRead for MaybePending < ' _ > {
58
+ fn poll_fill_buf < ' a > ( mut self : Pin < & ' a mut Self > , _: & mut Context < ' _ > )
59
+ -> Poll < io:: Result < & ' a [ u8 ] > >
60
+ {
61
+ if self . ready {
62
+ self . ready = false ;
63
+ if self . inner . is_empty ( ) { return Poll :: Ready ( Ok ( & [ ] ) ) }
64
+ let len = cmp:: min ( 2 , self . inner . len ( ) ) ;
65
+ Poll :: Ready ( Ok ( & self . inner [ 0 ..len] ) )
66
+ } else {
67
+ self . ready = true ;
68
+ Poll :: Pending
69
+ }
70
+ }
71
+
72
+ fn consume ( mut self : Pin < & mut Self > , amt : usize ) {
73
+ self . inner = & self . inner [ amt..] ;
74
+ }
75
+ }
76
+
77
+ #[ test]
78
+ fn maybe_pending ( ) {
79
+ let mut buf = MaybePending :: new ( b"12" ) ;
80
+ let mut v = Vec :: new ( ) ;
81
+ assert_eq ! ( run( buf. read_until( b'3' , & mut v) ) . unwrap( ) , 2 ) ;
82
+ assert_eq ! ( v, b"12" ) ;
83
+
84
+ let mut buf = MaybePending :: new ( b"12333" ) ;
85
+ let mut v = Vec :: new ( ) ;
86
+ assert_eq ! ( run( buf. read_until( b'3' , & mut v) ) . unwrap( ) , 3 ) ;
87
+ assert_eq ! ( v, b"123" ) ;
88
+ v. clear ( ) ;
89
+ assert_eq ! ( run( buf. read_until( b'3' , & mut v) ) . unwrap( ) , 1 ) ;
90
+ assert_eq ! ( v, b"3" ) ;
91
+ v. clear ( ) ;
92
+ assert_eq ! ( run( buf. read_until( b'3' , & mut v) ) . unwrap( ) , 1 ) ;
93
+ assert_eq ! ( v, b"3" ) ;
94
+ v. clear ( ) ;
95
+ assert_eq ! ( run( buf. read_until( b'3' , & mut v) ) . unwrap( ) , 0 ) ;
96
+ assert_eq ! ( v, [ ] ) ;
97
+ }
0 commit comments