Skip to main content

coven_foundation/files/
file_reader.rs

1//! Open read-only handles for positioned reads.
2
3use super::{FileError, LeasePlace, LeasedFile, ObservationError};
4use std::{
5    fs::{File, Metadata},
6    io,
7    path::{Path, PathBuf},
8    time::SystemTime,
9};
10
11/// An open read-only file. Renaming or unlinking its path never redirects reads.
12/// Reads return what's on disk, as the platform's own positioned reads do.
13/// A user's original holds its place of the app's budget until the reader
14/// drops (ยง17.3); coven's own files hold none.
15pub struct FileReader {
16    file: ReaderFile,
17    path: PathBuf,
18    size: u64,
19}
20
21enum ReaderFile {
22    /// A user's original, in its place; the file closes before the place
23    /// goes back.
24    Original(LeasedFile<File>),
25    /// A file of coven's own.
26    Own(File),
27}
28
29impl std::ops::Deref for ReaderFile {
30    type Target = File;
31    fn deref(&self) -> &File {
32        match self {
33            Self::Original(file) => file,
34            Self::Own(file) => file,
35        }
36    }
37}
38
39impl FileReader {
40    /// Open a user original in `place` and check its size and modification
41    /// time, once: later reads return what's on disk.
42    pub(super) fn open_original(
43        place: LeasePlace,
44        path: &Path,
45        size: u64,
46        modified: SystemTime,
47    ) -> Result<Self, ObservationError> {
48        #[cfg(any(test, feature = "test-utils"))]
49        super::reached::reached(path);
50        let file =
51            place.open(path).map_err(|error| ObservationError::at("read file", path, error))?;
52        let metadata = regular_file(&file, path)?;
53        let opened = metadata
54            .modified()
55            .map_err(|source| FileError::at("read modification time", path, source))?;
56        if metadata.len() != size || opened != modified {
57            return Err(ObservationError::Changed(path.to_owned()));
58        }
59        Ok(Self { file: ReaderFile::Original(file), path: path.to_owned(), size })
60    }
61
62    pub(crate) fn open(path: &Path) -> Result<Self, ObservationError> {
63        #[cfg(any(test, feature = "test-utils"))]
64        super::reached::reached(path);
65        let file =
66            File::open(path).map_err(|error| ObservationError::at("read file", path, error))?;
67        let metadata = regular_file(&file, path)?;
68        Ok(Self { file: ReaderFile::Own(file), path: path.to_owned(), size: metadata.len() })
69    }
70
71    /// The size captured on this open handle.
72    pub fn size(&self) -> u64 {
73        self.size
74    }
75
76    /// Read exactly the requested bytes using the open file's positioned-read API.
77    /// A range beyond the captured size fails instead of returning a short read,
78    /// and a file found shorter than that range fails as changed.
79    pub fn read_at(&self, offset: u64, len: usize) -> Result<Vec<u8>, ObservationError> {
80        #[cfg(any(test, feature = "test-utils"))]
81        crate::test_work::file_range_read();
82        if offset.checked_add(len as u64).is_none_or(|end| end > self.size()) {
83            return Err(FileError::at(
84                "read file range",
85                &self.path,
86                io::Error::new(io::ErrorKind::InvalidInput, "range exceeds file size"),
87            )
88            .into());
89        }
90        let mut bytes = Vec::new();
91        bytes.try_reserve_exact(len).map_err(|source| {
92            FileError::at(
93                "allocate file range",
94                &self.path,
95                io::Error::new(io::ErrorKind::OutOfMemory, source),
96            )
97        })?;
98        bytes.resize(len, 0);
99        self.read_exact_at(offset, &mut bytes)?;
100        Ok(bytes)
101    }
102
103    fn read_exact_at(&self, mut offset: u64, mut bytes: &mut [u8]) -> Result<(), ObservationError> {
104        while !bytes.is_empty() {
105            #[cfg(unix)]
106            let count = {
107                use std::os::unix::fs::FileExt;
108                self.file.read_at(bytes, offset)
109            };
110            #[cfg(windows)]
111            let count = {
112                use std::os::windows::fs::FileExt;
113                self.file.seek_read(bytes, offset)
114            };
115            match count {
116                Ok(0) => return Err(ObservationError::Changed(self.path.clone())),
117                Ok(count) => {
118                    bytes = &mut bytes[count..];
119                    offset += count as u64;
120                }
121                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
122                Err(error) => return Err(ObservationError::at("read file", &self.path, error)),
123            }
124        }
125        Ok(())
126    }
127}
128
129/// The facts of an open file, which must be a regular one.
130fn regular_file(file: &File, path: &Path) -> Result<Metadata, ObservationError> {
131    let metadata =
132        file.metadata().map_err(|error| ObservationError::at("read file", path, error))?;
133    if !metadata.is_file() {
134        return Err(FileError::at(
135            "open file for ranges",
136            path,
137            io::Error::new(io::ErrorKind::InvalidInput, "a regular file is required"),
138        )
139        .into());
140    }
141    Ok(metadata)
142}
143
144#[cfg(test)]
145#[path = "file_reader_tests.rs"]
146mod tests;