/
handles.go
53 lines (45 loc) · 1.29 KB
/
handles.go
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
package dapserver
const startHandle = 1000
// handlesMap maps arbitrary values to unique sequential ids.
// This provides convenient abstraction of references, offering
// opacity and allowing simplification of complex identifiers.
// Based on
// https://github.com/microsoft/vscode-debugadapter-node/blob/master/adapter/src/handles.ts
type handlesMap struct {
nextHandle int
handleToVal map[int]interface{}
aliasToHandle map[string]int
}
func newHandlesMap() *handlesMap {
return &handlesMap{
nextHandle: startHandle,
handleToVal: make(map[int]interface{}),
aliasToHandle: make(map[string]int),
}
}
func (hs *handlesMap) reset() {
hs.nextHandle = startHandle
hs.handleToVal = make(map[int]interface{})
}
func (hs *handlesMap) create(alias string, value interface{}) int {
next := hs.nextHandle
hs.nextHandle++
hs.handleToVal[next] = value
hs.aliasToHandle[alias] = next
return next
}
func (hs *handlesMap) get(handle int) (interface{}, bool) {
v, ok := hs.handleToVal[handle]
return v, ok
}
func (hs *handlesMap) getByAlias(alias string) (interface{}, bool) {
handle, ok := hs.lookupHandle(alias)
if !ok {
return nil, false
}
return hs.get(handle)
}
func (hs *handlesMap) lookupHandle(alias string) (int, bool) {
handle, ok := hs.aliasToHandle[alias]
return handle, ok
}