Debian Codegraph @

tests/framed_read.rs

raw symbols SCIP
1 use futures::executor;
2 use futures::stream::StreamExt;
3 use futures::AsyncRead;
4 use futures_codec::{Decoder, FramedRead, LinesCodec, BytesMut};
5 use std::io;
6 use std::pin::Pin;
7 use std::task::{Context, Poll};
8
9 // Sends two lines at once, then nothing else forever
10 struct MockBurstySender {
11 sent: bool,
12 }
13 impl AsyncRead for MockBurstySender {
14 fn poll_read(
15 mut self: Pin<&mut Self>,
16 _cx: &mut Context<'_>,
17 buf: &mut [u8],
18 ) -> Poll<io::Result<usize>> {
19 const MESSAGES: &'static [u8] = b"one\ntwo\n";
20 if !self.sent && buf.len() >= MESSAGES.len() {
21 self.sent = true;
22 buf[0..MESSAGES.len()].clone_from_slice(MESSAGES);
23 Poll::Ready(Ok(MESSAGES.len()))
24 } else {
25 Poll::Pending
26 }
27 }
28 }
29
30 #[test]
31 fn line_read_multi() {
32 let io = MockBurstySender { sent: false };
33 let mut framed = FramedRead::new(io, LinesCodec {});
34 let one = executor::block_on(framed.next()).unwrap().unwrap();
35 assert_eq!(one, "one\n");
36 let two = executor::block_on(framed.next()).unwrap().unwrap();
37 assert_eq!(two, "two\n");
38 }
39
40 struct OneByteAtATime<'a> {
41 input: &'a [u8],
42 }
43 impl AsyncRead for OneByteAtATime<'_> {
44 fn poll_read(
45 mut self: Pin<&mut Self>,
46 _cx: &mut Context<'_>,
47 buf: &mut [u8],
48 ) -> Poll<io::Result<usize>> {
49 if self.input.is_empty() {
50 Poll::Ready(Ok(0))
51 } else {
52 buf[0] = self.input[0];
53 self.input = &self.input[1..];
54 Poll::Ready(Ok(1))
55 }
56 }
57 }
58
59 /// A decoder that only returns `a` characters from the input.
60 struct AllTheAs;
61
62 impl Decoder for AllTheAs {
63 type Item = char;
64 type Error = io::Error;
65
66 fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
67 while !src.is_empty() {
68 let buf = src.split_to(1);
69 let c = char::from(buf[0]);
70 if c == 'a' {
71 return Ok(Some(c));
72 }
73 }
74 Ok(None)
75 }
76 }
77
78 #[test]
79 fn read_few_messages() {
80 let string: &[u8] = b"aabbbabbbabbbabb";
81 let input = OneByteAtATime { input: string };
82 let mut framed = FramedRead::new(input, AllTheAs);
83 for _ in 0..5 {
84 let item = executor::block_on(framed.next()).unwrap().unwrap();
85 assert_eq!(item, 'a');
86 }
87 }