file_storage/op/file/write/
write_slice.rs

1use crate::LocalPath;
2use crate::Operation::Write;
3use crate::Reason::{FileAlreadyExists, UnknownFileSystem};
4use crate::{Error, FilePath};
5
6impl FilePath {
7    //! Write Data
8
9    /// Writes the `slice` to the file.
10    ///
11    /// Returns `Ok(())`.
12    /// Returns `Err(FileAlreadyExists)` if the file already exists.
13    pub fn write_slice<D>(&self, slice: D) -> Result<(), Error>
14    where
15        D: AsRef<[u8]>,
16    {
17        if self.write_slice_if_not_exists(slice)? {
18            Ok(())
19        } else {
20            Err(Error::new(self.clone(), Write, FileAlreadyExists))
21        }
22    }
23
24    /// Writes the `slice` to the file if the file does not already exist.
25    ///
26    /// Returns `Ok(true)` if the file was written.
27    /// Returns `Ok(false)` if the file already exists.
28    pub fn write_slice_if_not_exists<D>(&self, slice: D) -> Result<bool, Error>
29    where
30        D: AsRef<[u8]>,
31    {
32        if let Some(local) = LocalPath::from(self.path()) {
33            return local.write_slice_if_not_exists(slice);
34        }
35
36        #[cfg(feature = "r2")]
37        if let Some(path) = crate::R2Path::from(self.path()) {
38            return path.write_slice_if_not_exists(slice);
39        }
40
41        Err(Error::new(self.clone(), Write, UnknownFileSystem))
42    }
43}