mirror of
https://github.com/rust-lang/rust-analyzer.git
synced 2025-09-28 12:54:58 +00:00
Add Loc2IdMap
This commit is contained in:
parent
f1d8558cd5
commit
cb22a799d6
6 changed files with 84 additions and 0 deletions
64
crates/ra_analysis/src/loc2id.rs
Normal file
64
crates/ra_analysis/src/loc2id.rs
Normal file
|
@ -0,0 +1,64 @@
|
|||
use std::hash::Hash;
|
||||
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
/// There are two principle ways to refer to things:
|
||||
/// - by their locatinon (module in foo/bar/baz.rs at line 42)
|
||||
/// - by their numeric id (module `ModuleId(42)`)
|
||||
///
|
||||
/// The first one is more powerful (you can actually find the thing in question
|
||||
/// by id), but the second one is so much more compact.
|
||||
///
|
||||
/// `Loc2IdMap` allows us to have a cake an eat it as well: by maintaining a
|
||||
/// bidirectional mapping between positional and numeric ids, we can use compact
|
||||
/// representation wich still allows us to get the actual item
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Loc2IdMap<L, ID>
|
||||
where
|
||||
ID: NumericId,
|
||||
L: Clone + Eq + Hash,
|
||||
{
|
||||
loc2id: FxHashMap<L, ID>,
|
||||
id2loc: FxHashMap<ID, L>,
|
||||
}
|
||||
|
||||
impl<L, ID> Default for Loc2IdMap<L, ID>
|
||||
where
|
||||
ID: NumericId,
|
||||
L: Clone + Eq + Hash,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Loc2IdMap {
|
||||
loc2id: FxHashMap::default(),
|
||||
id2loc: FxHashMap::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<L, ID> Loc2IdMap<L, ID>
|
||||
where
|
||||
ID: NumericId,
|
||||
L: Clone + Eq + Hash,
|
||||
{
|
||||
pub fn loc2id(&mut self, loc: &L) -> ID {
|
||||
match self.loc2id.get(loc) {
|
||||
Some(id) => return id.clone(),
|
||||
None => (),
|
||||
}
|
||||
let id = self.loc2id.len();
|
||||
assert!(id < u32::max_value() as usize);
|
||||
let id = ID::from_u32(id as u32);
|
||||
self.loc2id.insert(loc.clone(), id.clone());
|
||||
self.id2loc.insert(id.clone(), loc.clone());
|
||||
id
|
||||
}
|
||||
|
||||
pub fn id2loc(&self, id: &ID) -> L {
|
||||
self.id2loc[id].clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait NumericId: Clone + Eq + Hash {
|
||||
fn from_u32(id: u32) -> Self;
|
||||
fn to_u32(self) -> u32;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue