-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstream_map.go
More file actions
77 lines (66 loc) · 1.62 KB
/
stream_map.go
File metadata and controls
77 lines (66 loc) · 1.62 KB
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
package muxado
import (
"maps"
"sync"
"golang.ngrok.com/muxado/v2/frame"
)
const (
initMapCapacity = 128 // not too much extra memory wasted to avoid allocations
)
// streamMap is a map of stream ids -> streams guarded by a read/write lock
type streamMap struct {
sync.RWMutex
table map[frame.StreamId]streamPrivate
}
func (m *streamMap) Get(id frame.StreamId) (streamPrivate, bool) {
m.RLock()
defer m.RUnlock()
if m.table != nil {
s, ok := m.table[id]
return s, ok
}
return nil, false
}
// Set adds a stream to the map. It returns false if the stream could not be
// added due to the streamMap having been drained already.
func (m *streamMap) Set(id frame.StreamId, str streamPrivate) bool {
m.Lock()
defer m.Unlock()
if m.table == nil {
// already drained, let our caller know to give up
return false
}
m.table[id] = str
return true
}
func (m *streamMap) Delete(id frame.StreamId) {
m.Lock()
defer m.Unlock()
if m.table != nil {
delete(m.table, id)
}
}
func (m *streamMap) Each(fn func(frame.StreamId, streamPrivate)) {
m.RLock()
streams := maps.Clone(m.table)
m.RUnlock()
if streams == nil {
// already drained, do nothing
return
}
for id, str := range streams {
fn(id, str)
}
}
// Drain nils out the table under the write lock and returns all streams that
// were in the map. After Drain, Set will return false for any new streams.
func (m *streamMap) Drain() map[frame.StreamId]streamPrivate {
m.Lock()
defer m.Unlock()
streams := m.table
m.table = nil
return streams
}
func newStreamMap() *streamMap {
return &streamMap{table: make(map[frame.StreamId]streamPrivate, initMapCapacity)}
}