Skip to main content

file_storage/op/file/read/
read_vec.rs

1use crate::Operation::Read;
2use crate::Reason::{FileNotFound, UnknownFileSystem};
3use crate::{Error, FilePath, LocalPath};
4
5impl FilePath {
6    //! Read Vec
7
8    /// Reads the file as a `Vec`.
9    ///
10    /// Returns `Ok(file_content)`.
11    /// Returns `Err(FileNotFound)` if the file did not exist.
12    pub fn read_as_vec(&self) -> Result<Vec<u8>, Error> {
13        if let Some(vec) = self.read_as_vec_if_exists()? {
14            Ok(vec)
15        } else {
16            Err(Error::new(self.clone(), Read, FileNotFound))
17        }
18    }
19
20    /// Reads the file as a `Vec` if it exists.
21    ///
22    /// Returns `Ok(Some(file_content))`.
23    /// Returns `Ok(None)` if the file did not exist.
24    pub fn read_as_vec_if_exists(&self) -> Result<Option<Vec<u8>>, Error> {
25        let mut target: Vec<u8> = Vec::default();
26        if let Some(content_len) = self.read_to_vec_if_exists(&mut target)? {
27            debug_assert_eq!(content_len, target.len());
28            Ok(Some(target))
29        } else {
30            Ok(None)
31        }
32    }
33
34    /// Reads the file to the `target` `Vec`.
35    ///
36    /// Returns `Ok(file_content_len)`.
37    /// Returns `Err(FileNotFound)` if the file did not exist.
38    pub fn read_to_vec(&self, target: &mut Vec<u8>) -> Result<usize, Error> {
39        if let Some(file_content_len) = self.read_to_vec_if_exists(target)? {
40            Ok(file_content_len)
41        } else {
42            Err(Error::new(self.clone(), Read, FileNotFound))
43        }
44    }
45
46    /// Reads the file to the `target` `Vec` if it exists.
47    ///
48    /// Returns `Ok(Some(file_content_len))`.
49    /// Returns `Ok(None)` if the file did not exist.
50    pub fn read_to_vec_if_exists(&self, target: &mut Vec<u8>) -> Result<Option<usize>, Error> {
51        if let Some(path) = LocalPath::from(self.path()) {
52            return path.read_to_vec_if_exists(target);
53        }
54
55        #[cfg(feature = "r2")]
56        if let Some(path) = crate::R2Path::from(self.path()) {
57            return path.read_to_vec_if_exists(target);
58        }
59
60        Err(Error::new(self.clone(), Read, UnknownFileSystem))
61    }
62}