1 //! Partitions a list of files into disjoint subsets.
3 //! Files which do not belong to any explicitly configured `FileSet` belong to
4 //! the default `FileSet`.
7 use fst::{IntoStreamer, Streamer};
8 use rustc_hash::FxHashMap;
10 use crate::{AnchoredPath, FileId, Vfs, VfsPath};
12 /// A set of [`VfsPath`]s identified by [`FileId`]s.
13 #[derive(Default, Clone, Eq, PartialEq)]
15 files: FxHashMap<VfsPath, FileId>,
16 paths: FxHashMap<FileId, VfsPath>,
20 /// Returns the number of stored paths.
21 pub fn len(&self) -> usize {
25 /// Get the id of the file corresponding to `path`.
27 /// If either `path`'s [`anchor`](AnchoredPath::anchor) or the resolved path is not in
28 /// the set, returns [`None`].
29 pub fn resolve_path(&self, path: AnchoredPath<'_>) -> Option<FileId> {
30 let mut base = self.paths[&path.anchor].clone();
32 let path = base.join(path.path)?;
33 self.files.get(&path).copied()
36 /// Get the id corresponding to `path` if it exists in the set.
37 pub fn file_for_path(&self, path: &VfsPath) -> Option<&FileId> {
41 /// Get the path corresponding to `file` if it exists in the set.
42 pub fn path_for_file(&self, file: &FileId) -> Option<&VfsPath> {
46 /// Insert the `file_id, path` pair into the set.
49 /// Multiple [`FileId`] can be mapped to the same [`VfsPath`], and vice-versa.
50 pub fn insert(&mut self, file_id: FileId, path: VfsPath) {
51 self.files.insert(path.clone(), file_id);
52 self.paths.insert(file_id, path);
55 /// Iterate over this set's ids.
56 pub fn iter(&self) -> impl Iterator<Item = FileId> + '_ {
57 self.paths.keys().copied()
61 impl fmt::Debug for FileSet {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 f.debug_struct("FileSet").field("n_files", &self.files.len()).finish()
67 /// This contains path prefixes to partition a [`Vfs`] into [`FileSet`]s.
71 /// # use vfs::{file_set::FileSetConfigBuilder, VfsPath, Vfs};
72 /// let mut builder = FileSetConfigBuilder::default();
73 /// builder.add_file_set(vec![VfsPath::new_virtual_path("/src".to_string())]);
74 /// let config = builder.build();
75 /// let mut file_system = Vfs::default();
76 /// file_system.set_file_contents(VfsPath::new_virtual_path("/src/main.rs".to_string()), Some(vec![]));
77 /// file_system.set_file_contents(VfsPath::new_virtual_path("/src/lib.rs".to_string()), Some(vec![]));
78 /// file_system.set_file_contents(VfsPath::new_virtual_path("/build.rs".to_string()), Some(vec![]));
79 /// // contains the sets :
80 /// // { "/src/main.rs", "/src/lib.rs" }
82 /// let sets = config.partition(&file_system);
85 pub struct FileSetConfig {
86 /// Number of sets that `self` can partition a [`Vfs`] into.
88 /// This should be the number of sets in `self.map` + 1 for files that don't fit in any
91 /// Map from encoded paths to the set they belong to.
92 map: fst::Map<Vec<u8>>,
95 impl Default for FileSetConfig {
96 fn default() -> Self {
97 FileSetConfig::builder().build()
102 /// Returns a builder for `FileSetConfig`.
103 pub fn builder() -> FileSetConfigBuilder {
104 FileSetConfigBuilder::default()
107 /// Partition `vfs` into `FileSet`s.
109 /// Creates a new [`FileSet`] for every set of prefixes in `self`.
110 pub fn partition(&self, vfs: &Vfs) -> Vec<FileSet> {
111 let mut scratch_space = Vec::new();
112 let mut res = vec![FileSet::default(); self.len()];
113 for (file_id, path) in vfs.iter() {
114 let root = self.classify(path, &mut scratch_space);
115 res[root].insert(file_id, path.clone())
120 /// Number of sets that `self` can partition a [`Vfs`] into.
121 fn len(&self) -> usize {
125 /// Returns the set index for the given `path`.
127 /// `scratch_space` is used as a buffer and will be entirely replaced.
128 fn classify(&self, path: &VfsPath, scratch_space: &mut Vec<u8>) -> usize {
129 scratch_space.clear();
130 path.encode(scratch_space);
131 let automaton = PrefixOf::new(scratch_space.as_slice());
132 let mut longest_prefix = self.len() - 1;
133 let mut stream = self.map.search(automaton).into_stream();
134 while let Some((_, v)) = stream.next() {
135 longest_prefix = v as usize;
141 /// Builder for [`FileSetConfig`].
142 pub struct FileSetConfigBuilder {
143 roots: Vec<Vec<VfsPath>>,
146 impl Default for FileSetConfigBuilder {
147 fn default() -> Self {
148 FileSetConfigBuilder { roots: Vec::new() }
152 impl FileSetConfigBuilder {
153 /// Returns the number of sets currently held.
154 pub fn len(&self) -> usize {
158 /// Add a new set of paths prefixes.
159 pub fn add_file_set(&mut self, roots: Vec<VfsPath>) {
160 self.roots.push(roots)
163 /// Build the `FileSetConfig`.
164 pub fn build(self) -> FileSetConfig {
165 let n_file_sets = self.roots.len() + 1;
167 let mut entries = Vec::new();
168 for (i, paths) in self.roots.into_iter().enumerate() {
170 let mut buf = Vec::new();
172 entries.push((buf, i as u64));
176 entries.dedup_by(|(a, _), (b, _)| a == b);
177 fst::Map::from_iter(entries).unwrap()
179 FileSetConfig { n_file_sets, map }
183 /// Implements [`fst::Automaton`]
185 /// It will match if `prefix_of` is a prefix of the given data.
186 struct PrefixOf<'a> {
190 impl<'a> PrefixOf<'a> {
191 /// Creates a new `PrefixOf` from the given slice.
192 fn new(prefix_of: &'a [u8]) -> Self {
197 impl fst::Automaton for PrefixOf<'_> {
199 fn start(&self) -> usize {
202 fn is_match(&self, &state: &usize) -> bool {
205 fn can_match(&self, &state: &usize) -> bool {
208 fn accept(&self, &state: &usize, byte: u8) -> usize {
209 if self.prefix_of.get(state) == Some(&byte) {