use tokio::io::AsyncWrite; use tokio_test::{assert_ready, task}; use tokio_util::codec::{Encoder, FramedWrite};
use bytes::{BufMut, BytesMut}; use futures_sink::Sink; use std::collections::VecDeque; use std::io::{self, Write}; use std::pin::Pin; use std::task::Poll::{Pending, Ready}; use std::task::{Context, Poll};
macro_rules! mock {
($($x:expr,)*) => {{ letmut v = VecDeque::new();
v.extend(vec![$($x),*]);
Mock { calls: v }
}};
}
for i in0..=ITER { letmut b = BytesMut::with_capacity(4);
b.put_u32(i as u32);
// Append to the end match mock.calls.back_mut().unwrap() {
Ok(refmut data) => { // Write in 2kb chunks if data.len() < ITER {
data.extend_from_slice(&b[..]); continue;
} // else fall through and create a new buffer
}
_ => unreachable!(),
}
// Push a new new chunk
mock.calls.push_back(Ok(b[..].to_vec()));
} // 1 'wouldblock', 4 * 2KB buffers, 1 b-byte buffer
assert_eq!(mock.calls.len(), 6);
letmut task = task::spawn(()); letmut framed = FramedWrite::new(mock, U32Encoder);
task.enter(|cx, _| { // Send 8KB. This fills up FramedWrite2 buffer for i in0..ITER {
assert!(assert_ready!(pin!(framed).poll_ready(cx)).is_ok());
assert!(pin!(framed).start_send(i as u32).is_ok());
}
// Now we poll_ready which forces a flush. The mock pops the front message // and decides to block.
assert!(pin!(framed).poll_ready(cx).is_pending());
// We poll again, forcing another flush, which this time succeeds // The whole 8KB buffer is flushed
assert!(assert_ready!(pin!(framed).poll_ready(cx)).is_ok());
// Send more data. This matches the final message expected by the mock
assert!(pin!(framed).start_send(ITER as u32).is_ok());
// Flush the rest of the buffer
assert!(assert_ready!(pin!(framed).poll_flush(cx)).is_ok());
// Ensure the mock is empty
assert_eq!(0, framed.get_ref().calls.len());
})
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.