Skip to main content

file_storage/op/file/read/
read.rs

1use crate::op::file::read::read_op::{ReadOp, ReadOpInner};
2use crate::system::LocalPath;
3use crate::{Error, FilePath, Operation, Reason};
4
5impl FilePath {
6    //! Read
7
8    /// Opens a read operation to the file.
9    pub fn read(&self) -> Result<ReadOp, Error> {
10        if let Some(read) = self.read_if_exists()? {
11            Ok(read)
12        } else {
13            Err(Error::new(
14                self.clone(),
15                Operation::Read,
16                Reason::FileNotFound,
17            ))
18        }
19    }
20
21    /// Opens a read operation to the file if it exists.
22    ///
23    /// Returns `Ok(None)` if the file does not exist.
24    pub fn read_if_exists(&self) -> Result<Option<ReadOp>, Error> {
25        if let Some(path) = LocalPath::from(self.path()) {
26            return path.read_if_exists().map(|op| {
27                op.map(|op| ReadOp {
28                    inner: ReadOpInner::Local(op),
29                })
30            });
31        }
32
33        #[cfg(feature = "r2")]
34        if let Some(path) = crate::R2Path::from(self.path()) {
35            return path.read_if_exists().map(|op| {
36                op.map(|op| ReadOp {
37                    inner: ReadOpInner::R2(op),
38                })
39            });
40        }
41
42        Err(Error::new(
43            self.clone(),
44            Operation::Read,
45            Reason::UnknownFileSystem,
46        ))
47    }
48}