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                // todo -- assumes 64 bit machines
36                target.reserve(file_size as usize);
37                let read: usize = file
38                    .read_to_end(target)
39                    .map_err(|e| Error::from_source(self.path.clone(), Operation::Read, e))?;
40                Ok(Some(read))
41            }
42            Err(error) => {
43                if error.kind() == NotFound {
44                    Ok(None)
45                } else {
46                    Err(Error::from_source(
47                        self.path.clone(),
48                        Operation::Read,
49                        error,
50                    ))
51                }
52            }
53        }
54    }
55}