Debian Codegraph @

tests/test_framed_sink.rs

raw
1 #![allow(missing_docs)]
2
3 use std::{
4 collections::VecDeque,
5 io::{self, Write},
6 pin::Pin,
7 task::{
8 Context,
9 Poll::{self, Pending, Ready},
10 },
11 };
12
13 use actix_codec::*;
14 use bytes::{Buf as _, BufMut as _, BytesMut};
15 use futures_sink::Sink;
16 use tokio_test::{assert_ready, task};
17
18 macro_rules! bilateral {
19 ($($x:expr,)*) => {{
20 let mut v = VecDeque::new();
21 v.extend(vec![$($x),*]);
22 Bilateral { calls: v }
23 }};
24 }
25
26 #[derive(Debug)]
27 pub struct Bilateral {
28 pub calls: VecDeque<io::Result<Vec<u8>>>,
29 }
30
31 impl Write for Bilateral {
32 fn write(&mut self, src: &[u8]) -> io::Result<usize> {
33 match self.calls.pop_front() {
34 Some(Ok(data)) => {
35 assert!(src.len() >= data.len());
36 assert_eq!(&data[..], &src[..data.len()]);
37 Ok(data.len())
38 }
39 Some(Err(err)) => Err(err),
40 None => panic!("unexpected write; {src:?}"),
41 }
42 }
43
44 fn flush(&mut self) -> io::Result<()> {
45 Ok(())
46 }
47 }
48
49 impl AsyncWrite for Bilateral {
50 fn poll_write(
51 self: Pin<&mut Self>,
52 _cx: &mut Context<'_>,
53 buf: &[u8],
54 ) -> Poll<Result<usize, io::Error>> {
55 match Pin::get_mut(self).write(buf) {
56 Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Pending,
57 other => Ready(other),
58 }
59 }
60 fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
61 match Pin::get_mut(self).flush() {
62 Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Pending,
63 other => Ready(other),
64 }
65 }
66 fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
67 unimplemented!()
68 }
69 }
70
71 impl AsyncRead for Bilateral {
72 fn poll_read(
73 mut self: Pin<&mut Self>,
74 _: &mut Context<'_>,
75 buf: &mut ReadBuf<'_>,
76 ) -> Poll<Result<(), std::io::Error>> {
77 use io::ErrorKind::WouldBlock;
78
79 match self.calls.pop_front() {
80 Some(Ok(data)) => {
81 debug_assert!(buf.remaining() >= data.len());
82 buf.put_slice(&data);
83 Ready(Ok(()))
84 }
85 Some(Err(ref err)) if err.kind() == WouldBlock => Pending,
86 Some(Err(err)) => Ready(Err(err)),
87 None => Ready(Ok(())),
88 }
89 }
90 }
91
92 pub struct U32;
93
94 impl Encoder<u32> for U32 {
95 type Error = io::Error;
96
97 fn encode(&mut self, item: u32, dst: &mut BytesMut) -> io::Result<()> {
98 // Reserve space
99 dst.reserve(4);
100 dst.put_u32(item);
101 Ok(())
102 }
103 }
104
105 impl Decoder for U32 {
106 type Item = u32;
107 type Error = io::Error;
108
109 fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<u32>> {
110 if buf.len() < 4 {
111 return Ok(None);
112 }
113
114 let n = buf.split_to(4).get_u32();
115 Ok(Some(n))
116 }
117 }
118
119 #[test]
120 fn test_write_hits_highwater_mark() {
121 // see here for what this test is based on:
122 // https://github.com/tokio-rs/tokio/blob/75c07770bfbfea4e5fd914af819c741ed9c3fc36/tokio-util/tests/framed_write.rs#L69
123
124 const ITER: usize = 2 * 1024;
125
126 let mut bi = bilateral! {
127 Err(io::Error::new(io::ErrorKind::WouldBlock, "not ready")),
128 Ok(b"".to_vec()),
129 };
130
131 for i in 0..=ITER {
132 let mut b = BytesMut::with_capacity(4);
133 b.put_u32(i as u32);
134
135 // Append to the end
136 match bi.calls.back_mut().unwrap() {
137 Ok(ref mut data) => {
138 // Write in 2kb chunks
139 if data.len() < ITER {
140 data.extend_from_slice(&b[..]);
141 continue;
142 } // else fall through and create a new buffer
143 }
144 _ => unreachable!(),
145 }
146
147 // Push a new new chunk
148 bi.calls.push_back(Ok(b[..].to_vec()));
149 }
150
151 assert_eq!(bi.calls.len(), 6);
152 let mut framed = Framed::new(bi, U32);
153 // Send 8KB. This fills up FramedWrite2 buffer
154 let mut task = task::spawn(());
155 task.enter(|cx, _| {
156 // Send 8KB. This fills up Framed buffer
157 for i in 0..ITER {
158 {
159 #[allow(unused_mut)]
160 let mut framed = Pin::new(&mut framed);
161 assert!(assert_ready!(framed.poll_ready(cx)).is_ok());
162 }
163
164 #[allow(unused_mut)]
165 let mut framed = Pin::new(&mut framed);
166 // write the buffer
167 assert!(framed.start_send(i as u32).is_ok());
168 }
169
170 {
171 #[allow(unused_mut)]
172 let mut framed = Pin::new(&mut framed);
173
174 // Now we poll_ready which forces a flush. The bilateral pops the front message
175 // and decides to block.
176 assert!(framed.poll_ready(cx).is_pending());
177 }
178
179 {
180 #[allow(unused_mut)]
181 let mut framed = Pin::new(&mut framed);
182 // We poll again, forcing another flush, which this time succeeds
183 // The whole 8KB buffer is flushed
184 assert!(assert_ready!(framed.poll_ready(cx)).is_ok());
185 }
186
187 {
188 #[allow(unused_mut)]
189 let mut framed = Pin::new(&mut framed);
190 // Send more data. This matches the final message expected by the bilateral
191 assert!(framed.start_send(ITER as u32).is_ok());
192 }
193
194 {
195 #[allow(unused_mut)]
196 let mut framed = Pin::new(&mut framed);
197 // Flush the rest of the buffer
198 assert!(assert_ready!(framed.poll_flush(cx)).is_ok());
199 }
200
201 // Ensure the mock is empty
202 assert_eq!(0, Pin::new(&framed).get_ref().io_ref().calls.len());
203 });
204 }