file_storage/op/file/write/
write_data.rs1use crate::system::LocalPath;
2use crate::Operation;
3use crate::Reason::{FileAlreadyExists, UnknownFileSystem};
4use crate::{Error, FilePath};
5use std::io::Write;
6
7impl FilePath {
8 pub fn write_data<D>(&self, data: D) -> Result<(), Error>
15 where
16 D: AsRef<[u8]>,
17 {
18 if self.write_data_if_not_exists(data)? {
19 Ok(())
20 } else {
21 Err(Error::new(
22 self.clone(),
23 Operation::Write,
24 FileAlreadyExists,
25 ))
26 }
27 }
28
29 pub fn write_data_if_not_exists<D>(&self, data: D) -> Result<bool, Error>
34 where
35 D: AsRef<[u8]>,
36 {
37 if let Some(path) = LocalPath::new(self.path()) {
38 return if let Some(mut write) = path.write_if_not_exists()? {
39 write
40 .write_all(data.as_ref())
41 .map_err(|e| Error::from_source(self.clone(), Operation::Write, e))?;
42 write
43 .close()
44 .map_err(|e| Error::from_source(self.clone(), Operation::Write, e))?;
45 Ok(true)
46 } else {
47 Ok(false)
48 };
49 }
50
51 #[cfg(feature = "r2")]
52 if let Some(path) = crate::R2Path::new(self.path()) {
53 return path.write_data_if_not_exists(data);
54 }
55
56 Err(Error::new(
57 self.clone(),
58 Operation::Write,
59 UnknownFileSystem,
60 ))
61 }
62}