Debian Codegraph @

third_party/rust/tokio-util/tests/io_sync_bridge.rs

raw
1 #![cfg(feature = "io-util")]
2
3 use std::error::Error;
4 use std::io::{Cursor, Read, Result as IoResult};
5 use tokio::io::AsyncRead;
6 use tokio_util::io::SyncIoBridge;
7
8 async fn test_reader_len(
9 r: impl AsyncRead + Unpin + Send + 'static,
10 expected_len: usize,
11 ) -> IoResult<()> {
12 let mut r = SyncIoBridge::new(r);
13 let res = tokio::task::spawn_blocking(move || {
14 let mut buf = Vec::new();
15 r.read_to_end(&mut buf)?;
16 Ok::<_, std::io::Error>(buf)
17 })
18 .await?;
19 assert_eq!(res?.len(), expected_len);
20 Ok(())
21 }
22
23 #[tokio::test]
24 async fn test_async_read_to_sync() -> Result<(), Box<dyn Error>> {
25 test_reader_len(tokio::io::empty(), 0).await?;
26 let buf = b"hello world";
27 test_reader_len(Cursor::new(buf), buf.len()).await?;
28 Ok(())
29 }
30
31 #[tokio::test]
32 async fn test_async_write_to_sync() -> Result<(), Box<dyn Error>> {
33 let mut dest = Vec::new();
34 let src = b"hello world";
35 let dest = tokio::task::spawn_blocking(move || -> Result<_, String> {
36 let mut w = SyncIoBridge::new(Cursor::new(&mut dest));
37 std::io::copy(&mut Cursor::new(src), &mut w).map_err(|e| e.to_string())?;
38 Ok(dest)
39 })
40 .await??;
41 assert_eq!(dest.as_slice(), src);
42 Ok(())
43 }