Debian Codegraph @

tests/framed_write.rs

raw symbols SCIP
1 use core::iter::Iterator;
2 use futures::io::{AsyncWrite, Cursor};
3 use futures::sink::SinkExt;
4 use futures::{executor, stream, stream::StreamExt};
5 use futures_codec::{BytesCodec, FramedWrite, LinesCodec, Bytes};
6 use std::pin::Pin;
7 use std::task::{Context, Poll};
8
9 // An iterator which outputs a single zero byte up to limit times
10 struct ZeroBytes {
11 pub count: usize,
12 pub limit: usize,
13 }
14 impl Iterator for ZeroBytes {
15 type Item = Bytes;
16 fn next(&mut self) -> Option<Self::Item> {
17 if self.count >= self.limit {
18 None
19 } else {
20 self.count += 1;
21 Some(Bytes::from_static(b"\0"))
22 }
23 }
24 }
25
26 // An AsyncWrite which is always ready and just consumes the data
27 struct AsyncWriteNull {
28 // number of poll_write calls
29 pub num_poll_write: usize,
30
31 // size of the last poll_write
32 pub last_write_size: usize,
33 }
34 impl AsyncWrite for AsyncWriteNull {
35 fn poll_write(
36 mut self: Pin<&mut Self>,
37 _cx: &mut Context<'_>,
38 buf: &[u8],
39 ) -> Poll<std::io::Result<usize>> {
40 self.num_poll_write += 1;
41 self.last_write_size = buf.len();
42 Poll::Ready(Ok(buf.len()))
43 }
44
45 fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
46 Poll::Ready(Ok(()))
47 }
48
49 fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
50 Poll::Ready(Ok(()))
51 }
52 }
53
54 #[test]
55 fn line_write() {
56 let curs = Cursor::new(vec![0u8; 16]);
57 let mut framer = FramedWrite::new(curs, LinesCodec {});
58 executor::block_on(framer.send("Hello\n".to_owned())).unwrap();
59 executor::block_on(framer.send("World\n".to_owned())).unwrap();
60 let (curs, _) = framer.release();
61 assert_eq!(&curs.get_ref()[0..12], b"Hello\nWorld\n");
62 assert_eq!(curs.position(), 12);
63 }
64
65 #[test]
66 fn line_write_to_eof() {
67 let mut buf = [0u8; 16];
68 let curs = Cursor::new(&mut buf[..]);
69 let mut framer = FramedWrite::new(curs, LinesCodec {});
70 let _err =
71 executor::block_on(framer.send("This will fill up the buffer\n".to_owned())).unwrap_err();
72 let (curs, _) = framer.release();
73 assert_eq!(curs.position(), 16);
74 assert_eq!(&curs.get_ref()[0..16], b"This will fill u");
75 }
76
77 #[test]
78 fn send_high_water_mark() {
79 // stream will output 999 bytes, 1 at at a time, and will always be ready
80 let mut stream = stream::iter(ZeroBytes {
81 count: 0,
82 limit: 999,
83 })
84 .map(Ok);
85
86 // sink will eat whatever it receives
87 let io = AsyncWriteNull {
88 num_poll_write: 0,
89 last_write_size: 0,
90 };
91
92 // expect two sends
93 let mut framer = FramedWrite::new(io, BytesCodec {});
94 framer.set_send_high_water_mark(500);
95 executor::block_on(framer.send_all(&mut stream)).unwrap();
96 let (io, _) = framer.release();
97 assert_eq!(io.num_poll_write, 2);
98 assert_eq!(io.last_write_size, 499);
99 }