Debian Codegraph @

proto/stream_map.go

raw
1 package proto
2
3 import (
4 "github.com/inconshreveable/muxado/proto/frame"
5 "sync"
6 )
7
8 const (
9 initMapCapacity = 128 // not too much extra memory wasted to avoid allocations
10 )
11
12 type StreamMap interface {
13 Get(frame.StreamId) (stream, bool)
14 Set(frame.StreamId, stream)
15 Delete(frame.StreamId)
16 Each(func(frame.StreamId, stream))
17 }
18
19 // ConcurrentStreamMap is a map of stream ids -> streams guarded by a read/write lock
20 type ConcurrentStreamMap struct {
21 sync.RWMutex
22 table map[frame.StreamId]stream
23 }
24
25 func (m *ConcurrentStreamMap) Get(id frame.StreamId) (s stream, ok bool) {
26 m.RLock()
27 s, ok = m.table[id]
28 m.RUnlock()
29 return
30 }
31
32 func (m *ConcurrentStreamMap) Set(id frame.StreamId, str stream) {
33 m.Lock()
34 m.table[id] = str
35 m.Unlock()
36 }
37
38 func (m *ConcurrentStreamMap) Delete(id frame.StreamId) {
39 m.Lock()
40 delete(m.table, id)
41 m.Unlock()
42 }
43
44 func (m *ConcurrentStreamMap) Each(fn func(frame.StreamId, stream)) {
45 m.Lock()
46 streams := make(map[frame.StreamId]stream, len(m.table))
47 for k, v := range m.table {
48 streams[k] = v
49 }
50 m.Unlock()
51
52 for id, str := range streams {
53 fn(id, str)
54 }
55 }
56
57 func NewConcurrentStreamMap() *ConcurrentStreamMap {
58 return &ConcurrentStreamMap{table: make(map[frame.StreamId]stream, initMapCapacity)}
59 }