aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_db/src/loc2id.rs
blob: 1d6761897e02272b4761067cb0be9666a555453d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use std::hash::Hash;

use parking_lot::Mutex;
use rustc_hash::FxHashMap;
use ra_arena::{Arena, ArenaId};

/// 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)]
struct Loc2IdMap<LOC, ID>
where
    ID: ArenaId + Clone,
    LOC: Clone + Eq + Hash,
{
    id2loc: Arena<ID, LOC>,
    loc2id: FxHashMap<LOC, ID>,
}

impl<LOC, ID> Default for Loc2IdMap<LOC, ID>
where
    ID: ArenaId + Clone,
    LOC: Clone + Eq + Hash,
{
    fn default() -> Self {
        Loc2IdMap {
            id2loc: Arena::default(),
            loc2id: FxHashMap::default(),
        }
    }
}

impl<LOC, ID> Loc2IdMap<LOC, ID>
where
    ID: ArenaId + Clone,
    LOC: Clone + Eq + Hash,
{
    pub fn len(&self) -> usize {
        self.id2loc.len()
    }

    pub fn loc2id(&mut self, loc: &LOC) -> ID {
        match self.loc2id.get(loc) {
            Some(id) => return id.clone(),
            None => (),
        }
        let id = self.id2loc.alloc(loc.clone());
        self.loc2id.insert(loc.clone(), id.clone());
        id
    }

    pub fn id2loc(&self, id: ID) -> LOC {
        self.id2loc[id].clone()
    }
}

#[derive(Debug)]
pub struct LocationIntener<LOC, ID>
where
    ID: ArenaId + Clone,
    LOC: Clone + Eq + Hash,
{
    map: Mutex<Loc2IdMap<LOC, ID>>,
}

impl<LOC, ID> Default for LocationIntener<LOC, ID>
where
    ID: ArenaId + Clone,
    LOC: Clone + Eq + Hash,
{
    fn default() -> Self {
        LocationIntener {
            map: Default::default(),
        }
    }
}

impl<LOC, ID> LocationIntener<LOC, ID>
where
    ID: ArenaId + Clone,
    LOC: Clone + Eq + Hash,
{
    pub fn len(&self) -> usize {
        self.map.lock().len()
    }
    pub fn loc2id(&self, loc: &LOC) -> ID {
        self.map.lock().loc2id(loc)
    }
    pub fn id2loc(&self, id: ID) -> LOC {
        self.map.lock().id2loc(id)
    }
}