Skip to main content

rust_analyzer/
mem_docs.rs

1//! In-memory document information.
2
3use std::mem;
4
5use rustc_hash::FxHashMap;
6use triomphe::Arc;
7use vfs::VfsPath;
8
9/// Holds the set of in-memory documents.
10///
11/// For these document, their true contents is maintained by the client. It
12/// might be different from what's on disk.
13#[derive(Default, Clone)]
14pub(crate) struct MemDocs {
15    mem_docs: Arc<FxHashMap<VfsPath, Arc<DocumentData>>>,
16    added_or_removed: bool,
17}
18
19impl MemDocs {
20    pub(crate) fn contains(&self, path: &VfsPath) -> bool {
21        self.mem_docs.contains_key(path)
22    }
23
24    pub(crate) fn insert(&mut self, path: VfsPath, data: DocumentData) -> Result<(), ()> {
25        self.added_or_removed = true;
26        match Arc::make_mut(&mut self.mem_docs).insert(path, Arc::new(data)) {
27            Some(_) => Err(()),
28            None => Ok(()),
29        }
30    }
31
32    pub(crate) fn remove(&mut self, path: &VfsPath) -> Result<(), ()> {
33        self.added_or_removed = true;
34        match Arc::make_mut(&mut self.mem_docs).remove(path) {
35            Some(_) => Ok(()),
36            None => Err(()),
37        }
38    }
39
40    pub(crate) fn get(&self, path: &VfsPath) -> Option<&DocumentData> {
41        self.mem_docs.get(path).map(Arc::as_ref)
42    }
43
44    pub(crate) fn get_mut(&mut self, path: &VfsPath) -> Option<&mut DocumentData> {
45        // NB: don't set `self.added_or_removed` here, as that purposefully only
46        // tracks changes to the key set.
47        Arc::make_mut(&mut self.mem_docs).get_mut(path).map(Arc::make_mut)
48    }
49
50    pub(crate) fn iter(&self) -> impl Iterator<Item = &VfsPath> {
51        self.mem_docs.keys()
52    }
53
54    pub(crate) fn take_changes(&mut self) -> bool {
55        mem::replace(&mut self.added_or_removed, false)
56    }
57}
58
59/// Information about a document that the Language Client
60/// knows about.
61/// Its lifetime is driven by the textDocument/didOpen and textDocument/didClose
62/// client notifications.
63#[derive(Debug, Clone)]
64pub(crate) struct DocumentData {
65    pub(crate) version: i32,
66    pub(crate) data: Vec<u8>,
67}
68
69impl DocumentData {
70    pub(crate) fn new(version: i32, data: Vec<u8>) -> Self {
71        DocumentData { version, data }
72    }
73}