Skip to main content

file_storage/op/file/write/
write_data.rs

1use crate::Operation;
2use crate::Reason::FileAlreadyExists;
3use crate::{Error, FilePath};
4use std::io::Write;
5
6impl FilePath {
7    //! Write Data
8
9    /// Writes the `data` to the file.
10    ///
11    /// Returns `Ok(())`.
12    /// Returns `Err(FileAlreadyExists)` if the file already exists.
13    pub fn write_data<D>(&self, data: D) -> Result<(), Error>
14    where
15        D: AsRef<[u8]>,
16    {
17        if self.write_data_if_not_exists(data)? {
18            Ok(())
19        } else {
20            Err(Error::new(
21                self.clone(),
22                Operation::Write,
23                FileAlreadyExists,
24            ))
25        }
26    }
27
28    /// Writes the `data` to the file if the file does not already exist.
29    ///
30    /// Returns `Ok(true)` if the file was written.
31    /// Returns `Ok(false)` if the file already exists.
32    pub fn write_data_if_not_exists<D>(&self, data: D) -> Result<bool, Error>
33    where
34        D: AsRef<[u8]>,
35    {
36        #[cfg(feature = "r2")]
37        if let Some(path) = crate::R2Path::from(self.path()) {
38            return path.write_data_if_not_exists(data);
39        }
40
41        if let Some(mut write) = self.write_if_not_exists()? {
42            write
43                .write_all(data.as_ref())
44                .map_err(|e| Error::from_source(self.path().clone(), Operation::Write, e))?;
45            write
46                .close()
47                .map_err(|e| Error::from_source(self.path().clone(), Operation::Write, e))?;
48            Ok(true)
49        } else {
50            Ok(false)
51        }
52    }
53}