-
Notifications
You must be signed in to change notification settings - Fork 0
/
unique.go
46 lines (37 loc) · 952 Bytes
/
unique.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
package server
import (
"context"
"sync"
"github.com/daichitakahashi/confort/internal/beacon/proto"
)
type uniqueValueServer struct {
proto.UnimplementedUniqueValueServiceServer
stores sync.Map
}
type valueStore struct {
m sync.Mutex
values map[string]bool
}
func (s *valueStore) tryStore(v string) bool {
s.m.Lock()
defer s.m.Unlock()
// lazy init
if s.values == nil {
s.values = map[string]bool{}
}
// check if value is existing
if s.values[v] {
return false
}
// set v as new unique value
s.values[v] = true
return true
}
func (u *uniqueValueServer) StoreUniqueValue(_ context.Context, req *proto.StoreUniqueValueRequest) (*proto.StoreUniqueValueResponse, error) {
v, _ := u.stores.LoadOrStore(req.GetStore(), &valueStore{})
store := v.(*valueStore)
return &proto.StoreUniqueValueResponse{
Succeeded: store.tryStore(req.GetValue()),
}, nil
}
var _ proto.UniqueValueServiceServer = (*uniqueValueServer)(nil)