1 #![cfg(feature = "compat")]
2 #![cfg(not(target_os = "wasi"))] // WASI does not support all fs operations
3 #![warn(rust_2018_idioms)]
4
5 use futures_io::SeekFrom;
6 use futures_util::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
7 use tempfile::NamedTempFile;
8 use tokio::fs::OpenOptions;
9 use tokio_util::compat::TokioAsyncWriteCompatExt;
10
11 #[tokio::test]
compat_file_seek() -> futures_util::io::Result<()>12 async fn compat_file_seek() -> futures_util::io::Result<()> {
13 let temp_file = NamedTempFile::new()?;
14 let mut file = OpenOptions::new()
15 .read(true)
16 .write(true)
17 .create(true)
18 .truncate(true)
19 .open(temp_file)
20 .await?
21 .compat_write();
22
23 file.write_all(&[0, 1, 2, 3, 4, 5]).await?;
24 file.write_all(&[6, 7]).await?;
25
26 assert_eq!(file.stream_position().await?, 8);
27
28 // Modify elements at position 2.
29 assert_eq!(file.seek(SeekFrom::Start(2)).await?, 2);
30 file.write_all(&[8, 9]).await?;
31
32 file.flush().await?;
33
34 // Verify we still have 8 elements.
35 assert_eq!(file.seek(SeekFrom::End(0)).await?, 8);
36 // Seek back to the start of the file to read and verify contents.
37 file.seek(SeekFrom::Start(0)).await?;
38
39 let mut buf = Vec::new();
40 let num_bytes = file.read_to_end(&mut buf).await?;
41 assert_eq!(&buf[..num_bytes], &[0, 1, 8, 9, 4, 5, 6, 7]);
42
43 Ok(())
44 }
45