use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use cpp_parser::LineIndex;
use super::paths::{DiskFiles, FileId, FileProvider, normalize_path};
#[derive(Debug, Clone)]
pub struct VfsFile {
pub id: FileId,
pub path: PathBuf,
pub text: Arc<str>,
pub line_index: Arc<LineIndex>,
pub open: bool,
}
impl VfsFile {
pub fn offset_at(&self, line: usize, column: usize) -> Option<usize> {
self.line_index
.get_offset(line, column, &self.text)
.map(usize::from)
}
pub fn position_at(&self, offset: usize) -> Option<(usize, usize)> {
self.line_index.position_of(offset, &self.text)
}
}
#[derive(Debug, Default)]
struct Held {
files: Vec<Option<VfsFile>>,
by_path: HashMap<String, FileId>,
}
impl Held {
fn id_of(&self, path: &Path, case_insensitive: bool) -> Option<FileId> {
self.by_path
.get(&normalize_path(path, case_insensitive))
.copied()
}
fn get(&self, path: &Path, case_insensitive: bool) -> Option<&VfsFile> {
self.get_ref(self.id_of(path, case_insensitive)?)
}
fn get_ref(&self, id: FileId) -> Option<&VfsFile> {
self.files.get(id.index())?.as_ref()
}
fn id_for(&mut self, path: &Path, case_insensitive: bool) -> FileId {
match self.id_of(path, case_insensitive) {
Some(id) => id,
None => {
let id = FileId::new(self.files.len() as u32);
self.by_path
.insert(normalize_path(path, case_insensitive), id);
self.files.push(None);
id
}
}
}
fn insert(&mut self, path: &Path, text: &str, open: bool, case_insensitive: bool) {
let id = self.id_for(path, case_insensitive);
self.files[id.index()] = Some(VfsFile {
id,
path: path.to_path_buf(),
text: Arc::from(text),
line_index: Arc::new(LineIndex::parse(text)),
open,
});
}
fn close(&mut self, path: &Path, case_insensitive: bool) -> Option<VfsFile> {
let id = self.id_of(path, case_insensitive)?;
self.files.get_mut(id.index())?.take()
}
fn len(&self) -> usize {
self.files.iter().filter(|slot| slot.is_some()).count()
}
}
#[derive(Debug)]
pub struct Vfs<F: FileProvider = DiskFiles> {
files: F,
held: Held,
}
impl<F: FileProvider> Vfs<F> {
pub fn new(files: F) -> Self {
Vfs {
files,
held: Held::default(),
}
}
pub fn provider(&self) -> &F {
&self.files
}
pub fn load(&mut self, path: impl AsRef<Path>) -> Option<FileId> {
let path = path.as_ref();
let case_insensitive = self.files.is_case_insensitive();
if let Some(held) = self.held.get(path, case_insensitive) {
return Some(held.id);
}
let text = self.files.read(path)?;
let open = self.files.is_open_buffer(path);
self.held.insert(path, &text, open, case_insensitive);
self.held.id_of(path, case_insensitive)
}
pub fn file(&mut self, path: impl AsRef<Path>) -> Option<VfsFile> {
let id = self.load(path)?;
self.get(id)
}
pub fn held(&self, path: impl AsRef<Path>) -> Option<&VfsFile> {
let case_insensitive = self.files.is_case_insensitive();
self.held.get(path.as_ref(), case_insensitive)
}
pub fn get(&self, id: FileId) -> Option<VfsFile> {
self.held.get_ref(id).cloned()
}
pub fn get_ref(&self, id: FileId) -> Option<&VfsFile> {
self.held.get_ref(id)
}
pub fn insert(&mut self, path: impl AsRef<Path>, text: &str, open: bool) {
let case_insensitive = self.files.is_case_insensitive();
self.held
.insert(path.as_ref(), text, open, case_insensitive);
}
pub fn close(&mut self, path: impl AsRef<Path>) {
let case_insensitive = self.files.is_case_insensitive();
self.held.close(path.as_ref(), case_insensitive);
}
pub fn files(&self) -> impl Iterator<Item = &VfsFile> {
self.held.files.iter().filter_map(Option::as_ref)
}
pub fn paths(&self) -> Vec<PathBuf> {
self.files().map(|file| file.path.clone()).collect()
}
pub fn len(&self) -> usize {
self.held.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn id_bound(&self) -> usize {
self.held.files.len()
}
pub fn accounting(&self) -> (usize, usize, usize) {
let mut files = 0usize;
let mut text = 0usize;
let mut index = 0usize;
for file in self.files() {
files += 1;
text += file.text.len();
index += file.line_index.heap_bytes();
}
(files, text, index)
}
pub fn table(&self) -> &[Option<VfsFile>] {
&self.held.files
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::file::paths::MemoryFiles;
fn vfs() -> Vfs<MemoryFiles> {
Vfs::new(
MemoryFiles::new()
.with_file("/p/a.cpp", "int a;\nint b;\nint c;\n")
.with_file("/p/b.cpp", "void f() {}\n"),
)
}
#[test]
fn a_file_read_once_is_held_with_its_line_index() {
let mut vfs = vfs();
assert!(vfs.is_empty(), "nothing is held until something is read");
let file = vfs.file("/p/a.cpp").expect("the file reads");
assert_eq!(&*file.text, "int a;\nint b;\nint c;\n");
assert_eq!(vfs.len(), 1);
assert_eq!(file.offset_at(2, 4), Some(18));
assert_eq!(file.position_at(18), Some((2, 4)));
assert_eq!(file.offset_at(9, 0), None, "there is no line 9");
}
#[test]
fn the_line_index_follows_the_text_and_can_never_be_one_edit_behind() {
let mut vfs = vfs();
let first = vfs.file("/p/a.cpp").expect("the file reads");
let again = vfs.file("/p/a.cpp").expect("the file is held");
assert!(
Arc::ptr_eq(&first.text, &again.text),
"a file that did not change is not read twice"
);
vfs.insert("/p/a.cpp", "int a;\nint c;\n", true);
let changed = vfs.file("/p/a.cpp").expect("the edit is held");
assert!(changed.open, "the text came from a buffer");
assert_eq!(&*changed.text, "int a;\nint c;\n");
assert_eq!(
changed.offset_at(1, 4),
Some(11),
"the third line is the second line now"
);
assert_eq!(
changed.position_at(20),
None,
"and offset 20 is past the end"
);
}
#[test]
fn an_id_is_stable_across_a_close_and_never_reused() {
let mut vfs = vfs();
let first = vfs.file("/p/a.cpp").expect("the file reads");
let second = vfs.file("/p/b.cpp").expect("the file reads");
assert_eq!(first.id.index(), 0);
assert_eq!(second.id.index(), 1);
vfs.close("/p/a.cpp");
assert!(
vfs.held("/p/a.cpp").is_none(),
"a closed file is not held, and that is answerable"
);
assert_eq!(vfs.len(), 1, "and it is not counted as a file any more");
assert_eq!(vfs.id_bound(), 2, "but its id is still in the table");
let reopened = vfs.file("/p/a.cpp").expect("it reads again");
assert_eq!(
reopened.id, first.id,
"the same path keeps its id — the table has no reason to renumber it"
);
let third = vfs.file("/p/b.cpp").expect("still held");
assert_eq!(third.id, second.id);
}
#[test]
fn a_query_can_only_see_what_is_held() {
let mut vfs = vfs();
vfs.load("/p/a.cpp").expect("the file reads");
assert!(vfs.held("/p/a.cpp").is_some());
assert!(
vfs.held("/p/b.cpp").is_none(),
"nobody has read it, so nothing is known about it"
);
let held = vfs.held("/p/a.cpp").expect("held").id;
assert_eq!(
vfs.get(held).map(|file| file.path),
Some(PathBuf::from("/p/a.cpp"))
);
assert!(
vfs.get_ref(FileId::new(99)).is_none(),
"an id the table never handed out is not a file"
);
}
#[test]
fn a_path_that_is_not_there_is_not_an_entry() {
let mut vfs = vfs();
assert!(vfs.file("/p/missing.cpp").is_none());
assert!(vfs.is_empty(), "a failed read holds nothing");
}
#[test]
fn two_spellings_of_one_path_are_one_file() {
let mut vfs = Vfs::new(MemoryFiles::new().with_file("/p/sub/a.cpp", "int x;\n"));
let one = vfs.file("/p/sub/a.cpp").expect("the file reads");
let other = vfs.file("/p/sub/./a.cpp").expect("the same file");
assert_eq!(one.id, other.id, "the id is the file's, not the spelling's");
assert_eq!(vfs.len(), 1);
}
}