Skip to main content

malt_index/
source.rs

1//! The source lines of files, read once and cached by path: the lines collection of maxx.
2//!
3//! Lines are split on `\n`, a `\r` before it is removed, and a final newline does not
4//! start an extra empty line (maxx keeps that empty line). Text that is not UTF-8 is
5//! read as Latin-1, as the parser reads it.
6
7use std::collections::HashMap;
8use std::fs;
9use std::path::{Path, PathBuf};
10use std::sync::{Arc, Mutex, PoisonError};
11
12use crate::error::IndexError;
13use crate::live::decode;
14
15/// The lines of the files read so far. Shared by reference: `Sources` is `Send + Sync`.
16#[derive(Debug, Default)]
17pub struct Sources {
18    cache: Mutex<HashMap<PathBuf, Arc<Vec<String>>>>,
19}
20
21impl Sources {
22    /// An empty cache.
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// The lines of a file, read from disk on first use. A file that cannot be read is an
28    /// [`IndexError::Io`] and is not cached.
29    pub fn lines(&self, path: impl AsRef<Path>) -> Result<Arc<Vec<String>>, IndexError> {
30        let path = path.as_ref();
31        if let Some(lines) = self.locked().get(path) {
32            return Ok(Arc::clone(lines));
33        }
34        let bytes = fs::read(path).map_err(|e| IndexError::io(path, &e))?;
35        let lines = Arc::new(split_lines(&bytes));
36        self.locked().insert(path.to_path_buf(), Arc::clone(&lines));
37        Ok(lines)
38    }
39
40    /// Whether the lines of a file are cached (read by an earlier call).
41    pub fn is_cached(&self, path: impl AsRef<Path>) -> bool {
42        self.locked().contains_key(path.as_ref())
43    }
44
45    /// The cached paths, sorted.
46    pub fn cached_paths(&self) -> Vec<PathBuf> {
47        let mut paths: Vec<PathBuf> = self.locked().keys().cloned().collect();
48        paths.sort();
49        paths
50    }
51
52    fn locked(&self) -> std::sync::MutexGuard<'_, HashMap<PathBuf, Arc<Vec<String>>>> {
53        self.cache.lock().unwrap_or_else(PoisonError::into_inner)
54    }
55}
56
57/// The lines of some bytes, as [`Sources::lines`] reads them.
58pub fn split_lines(bytes: &[u8]) -> Vec<String> {
59    let text = decode(bytes);
60    if text.is_empty() {
61        return Vec::new();
62    }
63    let mut lines: Vec<String> = text
64        .split('\n')
65        .map(|line| line.strip_suffix('\r').unwrap_or(line).to_string())
66        .collect();
67    if text.ends_with('\n') {
68        lines.pop();
69    }
70    lines
71}
72
73#[cfg(test)]
74mod tests {
75    use super::split_lines;
76
77    #[test]
78    fn lines_drop_the_final_newline_and_the_carriage_return() {
79        assert_eq!(split_lines(b"a\r\nb\n"), ["a", "b"]);
80        assert_eq!(split_lines(b"a\n\nb"), ["a", "", "b"]);
81        assert!(split_lines(b"").is_empty());
82        assert_eq!(split_lines(b"\xe9t\xe9\n"), ["\u{e9}t\u{e9}"]);
83    }
84}