-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.go
91 lines (71 loc) · 1.77 KB
/
trie.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
package logstream
import (
"errors"
"sync"
"github.com/Workiva/go-datastructures/trie/ctrie"
"github.com/diy-cloud/logstream/v2/consumer"
"github.com/diy-cloud/logstream/v2/log/logbuffer"
"github.com/diy-cloud/logstream/v2/log/logbuffer/logring"
)
type Consumers struct {
list []consumer.Consumer
sync.Mutex
}
var bufferSize = 8
var bufferConstructor func(int) logbuffer.LogBuffer = logring.New
var trie = ctrie.New(nil)
var consumersMap = ctrie.New(nil)
type tempTrie struct{}
func (t tempTrie) SetBufferConstructor(f func(int) logbuffer.LogBuffer) {
bufferConstructor = f
}
func (t tempTrie) SetBufferSize(size int) {
if size < 1 {
size = 1
}
bufferSize = size
}
func (t tempTrie) RegisterTopic(topic string) error {
key := []byte(topic)
if _, ok := trie.Lookup(key); ok {
return errors.New("topic already registered")
}
trie.Insert(key, bufferConstructor(bufferSize))
consumers := Consumers{
list: make([]consumer.Consumer, 0),
}
consumersMap.Insert(key, &consumers)
return nil
}
func (t tempTrie) UnregisterTopic(topic string) error {
key := []byte(topic)
if _, ok := trie.Lookup(key); !ok {
return errors.New("topic not registered")
}
trie.Remove(key)
consumersMap.Remove(key)
return nil
}
func (t tempTrie) RegisterConsumer(topic string, csm consumer.Consumer) error {
key := []byte(topic)
if _, ok := trie.Lookup(key); !ok {
return errors.New("topic not registered")
}
consumers, ok := consumersMap.Lookup(key)
if !ok {
cs := Consumers{
list: make([]consumer.Consumer, 0),
}
consumersMap.Insert(key, &cs)
consumers, _ = consumersMap.Lookup(key)
}
cs, ok := consumers.(*Consumers)
if !ok {
return errors.New("consumers is not a Consumers")
}
cs.Lock()
cs.list = append(cs.list, csm)
cs.Unlock()
return nil
}
var Trie tempTrie