bigtools/utils/file/
reopen.rs

1use std::fs::File;
2use std::io::{self, Read, Seek};
3use std::path::PathBuf;
4
5/// A helper trait that for things that implement `Read`, `Seek`, and `Send`
6pub trait SeekableRead: Seek + Read {}
7impl<T> SeekableRead for T where T: Seek + Read {}
8
9/// Indicates something that can be *reopened*. Importantly, reopening should be independent
10/// with respect to seeks and reads from the original object.
11pub trait Reopen: Sized {
12    fn reopen(&self) -> io::Result<Self>;
13}
14
15pub struct ReopenableFile {
16    pub path: PathBuf,
17    pub file: File,
18}
19
20impl Reopen for ReopenableFile {
21    fn reopen(&self) -> io::Result<Self> {
22        Ok(ReopenableFile {
23            path: self.path.clone(),
24            file: File::open(&self.path)?,
25        })
26    }
27}
28
29impl Seek for ReopenableFile {
30    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
31        self.file.seek(pos)
32    }
33}
34
35impl Read for ReopenableFile {
36    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
37        self.file.read(buf)
38    }
39
40    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
41        self.file.read_vectored(bufs)
42    }
43
44    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
45        self.file.read_to_end(buf)
46    }
47
48    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
49        self.file.read_to_string(buf)
50    }
51
52    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
53        self.file.read_exact(buf)
54    }
55}