Skip to main content

file_storage/op/file/write/
write_with_headers.rs

1use crate::system::LocalPath;
2use crate::Operation;
3use crate::Reason::UnknownFileSystem;
4use crate::{Error, FilePath, Headers};
5use std::io::Write;
6
7impl FilePath {
8    //! Write With Headers
9
10    /// Writes the `data` to the file with the given `headers`, overwriting it if it already exists.
11    ///
12    /// Headers (e.g. `Content-Type`) are applied by backends that support object metadata, such as
13    /// Cloudflare R2. The local filesystem backend ignores them.
14    #[cfg_attr(not(feature = "r2"), allow(unused_variables))]
15    pub fn write_with_headers<D>(&self, data: D, headers: &Headers) -> Result<(), Error>
16    where
17        D: AsRef<[u8]>,
18    {
19        if let Some(path) = LocalPath::new(self.path()) {
20            return path.overwrite(data.as_ref());
21        }
22
23        #[cfg(feature = "r2")]
24        if let Some(path) = crate::R2Path::new(self.path()) {
25            return path.write_with_headers(data, headers);
26        }
27
28        Err(Error::new(self.clone(), Operation::Write, UnknownFileSystem))
29    }
30
31    /// Writes the `data` to the file with the given `headers` if the file does not already exist.
32    ///
33    /// Headers (e.g. `Content-Type`) are applied by backends that support object metadata, such as
34    /// Cloudflare R2. The local filesystem backend ignores them.
35    ///
36    /// Returns `Ok(true)` if the file was written.
37    /// Returns `Ok(false)` if the file already exists.
38    #[cfg_attr(not(feature = "r2"), allow(unused_variables))]
39    pub fn write_with_headers_if_not_exists<D>(
40        &self,
41        data: D,
42        headers: &Headers,
43    ) -> Result<bool, Error>
44    where
45        D: AsRef<[u8]>,
46    {
47        if let Some(path) = LocalPath::new(self.path()) {
48            return if let Some(mut write) = path.write_if_not_exists()? {
49                write
50                    .write_all(data.as_ref())
51                    .map_err(|e| Error::from_source(self.clone(), Operation::Write, e))?;
52                write
53                    .close()
54                    .map_err(|e| Error::from_source(self.clone(), Operation::Write, e))?;
55                Ok(true)
56            } else {
57                Ok(false)
58            };
59        }
60
61        #[cfg(feature = "r2")]
62        if let Some(path) = crate::R2Path::new(self.path()) {
63            return path.write_with_headers_if_not_exists(data, headers);
64        }
65
66        Err(Error::new(self.clone(), Operation::Write, UnknownFileSystem))
67    }
68}