-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
86 lines (72 loc) · 1.42 KB
/
map.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
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
package location
import (
"github.com/alecthomas/participle/v2"
"strings"
"sync"
)
type Map interface {
GetLocation(n string) *Location
GetLocations() []*Location
SetLocation(l *Location) (Map, bool)
Merge(b Map) error
}
type basicMap struct {
mutex sync.Mutex
locations map[string]*Location
}
func NewMap() Map {
return newMap()
}
func newMap() *basicMap {
return &basicMap{
locations: make(map[string]*Location),
}
}
func (s *basicMap) GetLocation(n string) *Location {
if s == nil {
return nil
}
n = strings.ToLower(n)
s.mutex.Lock()
defer s.mutex.Unlock()
return s.locations[n]
}
func (s *basicMap) GetLocations() []*Location {
if s == nil {
return nil
}
s.mutex.Lock()
defer s.mutex.Unlock()
var r []*Location
for _, l := range s.locations {
r = append(r, l)
}
return r
}
func (s *basicMap) SetLocation(l *Location) (Map, bool) {
if l == nil {
return s, false
}
if s == nil {
return NewMap().SetLocation(l)
}
l.Name = strings.ToLower(l.Name)
s.mutex.Lock()
defer s.mutex.Unlock()
if _, exists := s.locations[l.Name]; exists {
return s, false
}
s.locations[l.Name] = l
return s, true
}
func (s *basicMap) Merge(b Map) error {
// Merge the state, dealing with id clashes
if b != nil {
for _, l := range b.GetLocations() {
if _, added := s.SetLocation(l); !added {
return participle.Errorf(l.Pos, "location %q already defined during merge", l.Name)
}
}
}
return nil
}