1use 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#[derive(Debug, Default)]
17pub struct Sources {
18 cache: Mutex<HashMap<PathBuf, Arc<Vec<String>>>>,
19}
20
21impl Sources {
22 pub fn new() -> Self {
24 Self::default()
25 }
26
27 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 pub fn is_cached(&self, path: impl AsRef<Path>) -> bool {
42 self.locked().contains_key(path.as_ref())
43 }
44
45 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
57pub 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}