-
Notifications
You must be signed in to change notification settings - Fork 110
/
subtype.go
55 lines (48 loc) · 1.26 KB
/
subtype.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
// Package subtype contains a Service type that can be used to hold all resources of a certain subtype.
package subtype
import (
"sync"
"go.viam.com/rdk/resource"
)
// Service defines an service that holds and replaces resources.
type Service interface {
Resource(name string) interface{}
Replace(resources map[resource.Name]interface{}) error
}
type subtypeSvc struct {
mu sync.RWMutex
resources map[string]interface{}
}
// New creates a new subtype service, which holds and replaces resources belonging to that subtype.
func New(r map[resource.Name]interface{}) (Service, error) {
s := &subtypeSvc{}
if err := s.Replace(r); err != nil {
return nil, err
}
return s, nil
}
// Resource returns resource by name, if it exists.
func (s *subtypeSvc) Resource(name string) interface{} {
s.mu.RLock()
defer s.mu.RUnlock()
if resource, ok := s.resources[name]; ok {
return resource
}
return nil
}
// Replace replaces all resources with r.
func (s *subtypeSvc) Replace(r map[resource.Name]interface{}) error {
s.mu.Lock()
defer s.mu.Unlock()
resources := make(map[string]interface{}, len(r))
for n, v := range r {
switch {
case n.Name == "":
resources[n.String()] = v
default:
resources[n.ShortName()] = v
}
}
s.resources = resources
return nil
}