-
Notifications
You must be signed in to change notification settings - Fork 67
/
mapper.go
57 lines (51 loc) · 1.3 KB
/
mapper.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
54
55
56
57
package zed
import (
"sync"
)
type Mapper struct {
outputCtx *Context
mu sync.RWMutex
types []Type
}
func NewMapper(out *Context) *Mapper {
return &Mapper{outputCtx: out}
}
// Lookup tranlates Zed types by type ID from one context to another.
// The first context is implied by the argument to Lookup() and the output
// type context is explicitly determined by the argument to NewMapper().
// If a binding has not yet been entered, nil is returned and Enter()
// should be called to create the binding. There is a race here when two
// threads attempt to update the same ID, but it is safe because the
// outputContext will return the same the pointer so the second update
// does not change anything.
func (m *Mapper) Lookup(td int) Type {
m.mu.RLock()
defer m.mu.RUnlock()
if td < len(m.types) {
return m.types[td]
}
return nil
}
func (m *Mapper) Enter(id int, ext Type) (Type, error) {
typ, err := m.outputCtx.TranslateType(ext)
if err != nil {
return nil, err
}
if typ != nil {
m.EnterType(id, typ)
return typ, nil
}
return nil, nil
}
func (m *Mapper) EnterType(td int, typ Type) {
m.mu.Lock()
if td >= cap(m.types) {
new := make([]Type, td+1, td*2)
copy(new, m.types)
m.types = new
} else if td >= len(m.types) {
m.types = m.types[:td+1]
}
m.types[td] = typ
m.mu.Unlock()
}