/
property.go
146 lines (112 loc) · 2.54 KB
/
property.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package property
import "sync"
type Source interface {
Name() string
Source() any
ContainsProperty(name string) bool
Property(name string) (any, bool)
PropertyOrDefault(name string, defaultValue any) any
PropertyNames() []string
}
type Sources struct {
sources []Source
mu sync.RWMutex
}
func NewPropertySources() *Sources {
return &Sources{
sources: make([]Source, 0),
mu: sync.RWMutex{},
}
}
func (s *Sources) Contains(name string) bool {
defer s.mu.Unlock()
s.mu.Lock()
for _, source := range s.sources {
if source != nil && source.Name() == name {
return true
}
}
return false
}
func (s *Sources) Find(name string) (Source, bool) {
defer s.mu.Unlock()
s.mu.Lock()
for _, source := range s.sources {
if source != nil && source.Name() == name {
return source, true
}
}
return nil, false
}
func (s *Sources) AddFirst(source Source) {
defer s.mu.Unlock()
s.mu.Lock()
s.removeIfPresent(source)
if len(s.sources) == 0 {
s.sources = append(s.sources, source)
return
}
s.sources = append(s.sources[:1], s.sources[0:]...)
s.sources[0] = source
}
func (s *Sources) AddLast(source Source) {
defer s.mu.Unlock()
s.mu.Lock()
s.removeIfPresent(source)
s.sources = append(s.sources, source)
}
func (s *Sources) AddAtIndex(index int, source Source) {
defer s.mu.Unlock()
s.mu.Lock()
s.removeIfPresent(source)
if len(s.sources) == index {
s.mu.Unlock()
s.AddLast(source)
return
}
s.sources = append(s.sources[:index+1], s.sources[index:]...)
s.sources[index] = source
}
func (s *Sources) Remove(name string) Source {
source, index := s.findPropertySourceByName(name)
if index != -1 {
s.sources = append(s.sources[:index], s.sources[index+1:]...)
} else {
return nil
}
return source
}
func (s *Sources) Replace(name string, source Source) {
_, index := s.findPropertySourceByName(name)
if index != -1 {
s.sources[index] = source
}
}
func (s *Sources) Size() int {
return len(s.sources)
}
func (s *Sources) PrecendenceOf(source Source) int {
return 0
}
func (s *Sources) ToSlice() []Source {
sources := make([]Source, len(s.sources))
copy(sources, s.sources)
return sources
}
func (s *Sources) removeIfPresent(source Source) {
if source == nil {
return
}
_, index := s.findPropertySourceByName(source.Name())
if index != -1 {
s.sources = append(s.sources[:index], s.sources[index+1:]...)
}
}
func (s *Sources) findPropertySourceByName(name string) (Source, int) {
for index, source := range s.sources {
if source.Name() == name {
return source, index
}
}
return nil, -1
}