dupe_krill/lazyfile.rs
1use std::path::Path;
2use std::{fs, io};
3
4/// Open the file only if necessary.
5/// The file will be closed automatically when this object goes out of scope.
6pub struct LazyFile<'a> {
7 path: &'a Path,
8 file: Option<fs::File>,
9}
10
11impl<'a> LazyFile<'a> {
12 pub fn new(path: &'a Path) -> Self {
13 LazyFile { path, file: None }
14 }
15
16 /// Open the file (or reuse already-opened handle)
17 pub fn fd(&mut self) -> Result<&mut fs::File, io::Error> {
18 if let Some(ref mut fd) = self.file {
19 Ok(fd)
20 } else {
21 self.file = Some(fs::File::open(self.path)?);
22 if let Some(ref mut fd) = self.file {
23 Ok(fd)
24 } else {
25 unreachable!();
26 }
27 }
28 }
29}