Skip to main content

tokio/fs/
write.rs

1use crate::{fs::asyncify, util::as_ref::OwnedBuf};
2
3use std::{io, path::Path};
4
5/// Creates a future that will open a file for writing and write the entire
6/// contents of `contents` to it.
7///
8/// This is the async equivalent of [`std::fs::write`][std].
9///
10/// This operation is implemented by running the equivalent blocking operation
11/// on a separate thread pool using [`spawn_blocking`].
12///
13/// [`spawn_blocking`]: crate::task::spawn_blocking
14/// [std]: fn@std::fs::write
15///
16/// # Examples
17///
18/// ```no_run
19/// use tokio::fs;
20///
21/// # async fn dox() -> std::io::Result<()> {
22/// fs::write("foo.txt", b"Hello world!").await?;
23/// # Ok(())
24/// # }
25/// ```
26pub async fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> io::Result<()> {
27    let path = path.as_ref();
28    let contents = crate::util::as_ref::upgrade(contents);
29
30    #[cfg(all(
31        tokio_unstable,
32        feature = "io-uring",
33        feature = "rt",
34        feature = "fs",
35        target_os = "linux"
36    ))]
37    {
38        let handle = crate::runtime::Handle::current();
39        let driver_handle = handle.inner.driver().io();
40        if driver_handle
41            .check_and_init(io_uring::opcode::Write::CODE)
42            .await?
43        {
44            return write_uring(path, contents).await;
45        }
46    }
47
48    write_spawn_blocking(path, contents).await
49}
50
51#[cfg(all(
52    tokio_unstable,
53    feature = "io-uring",
54    feature = "rt",
55    feature = "fs",
56    target_os = "linux"
57))]
58async fn write_uring(path: &Path, mut buf: OwnedBuf) -> io::Result<()> {
59    use crate::{fs::OpenOptions, runtime::driver::op::Op};
60    use std::os::fd::OwnedFd;
61
62    let file = OpenOptions::new()
63        .write(true)
64        .create(true)
65        .truncate(true)
66        .open(path)
67        .await?;
68
69    let mut fd: OwnedFd = file
70        .try_into_std()
71        .expect("unexpected in-flight operation detected")
72        .into();
73
74    let total: usize = buf.as_ref().len();
75    let mut buf_offset: usize = 0;
76    let mut file_offset: u64 = 0;
77    while buf_offset < total {
78        let (res, r_buf, r_fd) = Op::write_at(fd, buf, buf_offset, file_offset)?.await;
79
80        // A cancelled op returns no resources to continue with, so its error is
81        // terminal; otherwise an interrupted write retries from where it stopped.
82        let (Some(r_buf), Some(r_fd)) = (r_buf, r_fd) else {
83            return Err(res.expect_err("a cancelled op completes with an error"));
84        };
85
86        let n = match res {
87            Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
88            Ok(n) => n,
89            Err(e) if e.kind() == io::ErrorKind::Interrupted => 0,
90            Err(e) => return Err(e),
91        };
92
93        buf = r_buf;
94        fd = r_fd;
95        buf_offset += n as usize;
96        file_offset += n as u64;
97    }
98
99    Ok(())
100}
101
102async fn write_spawn_blocking(path: &Path, contents: OwnedBuf) -> io::Result<()> {
103    let path = path.to_owned();
104    asyncify(move || std::fs::write(path, contents)).await
105}