Skip to main content

file_storage/system/local/file/
read.rs

1use crate::system::{LocalPath, LocalReadOp};
2use crate::{Error, Operation};
3use std::io::ErrorKind::NotFound;
4use std::io::Read;
5
6impl<'a> LocalPath<'a> {
7    //! Read
8
9    /// See `FilePath::read_if_exists`.
10    pub fn read_if_exists(self) -> Result<Option<LocalReadOp>, Error> {
11        match std::fs::File::open(self.path.as_str()) {
12            Ok(file) => Ok(Some(LocalReadOp { file })),
13            Err(error) => {
14                if error.kind() == NotFound {
15                    Ok(None)
16                } else {
17                    Err(Error::from_source(
18                        self.path.clone(),
19                        Operation::Read,
20                        error,
21                    ))
22                }
23            }
24        }
25    }
26
27    /// See `FilePath::read_to_vec_if_exists`.
28    pub fn read_to_vec_if_exists(self, target: &mut Vec<u8>) -> Result<Option<usize>, Error> {
29        match std::fs::File::open(self.path.as_str()) {
30            Ok(mut file) => {
31                let file_size: u64 = file
32                    .metadata()
33                    .map_err(|e| Error::from_source(self.path.clone(), Operation::Read, e))?
34                    .len();
35                target.reserve(file_size as usize); // todo: truncates on 32-bit for files > 4GB
36                let read: usize = file
37                    .read_to_end(target)
38                    .map_err(|e| Error::from_source(self.path.clone(), Operation::Read, e))?;
39                Ok(Some(read))
40            }
41            Err(error) => {
42                if error.kind() == NotFound {
43                    Ok(None)
44                } else {
45                    Err(Error::from_source(
46                        self.path.clone(),
47                        Operation::Read,
48                        error,
49                    ))
50                }
51            }
52        }
53    }
54}