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