stream_map.go 1.23 KB
Newer Older
Jeromy's avatar
Jeromy committed
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
package proto

import (
	"QmfEm573cZeq3LpgccZMpngV6dXbm5gfU23F5nNUuhSxxJ/muxado/proto/frame"
	"sync"
)

const (
	initMapCapacity = 128 // not too much extra memory wasted to avoid allocations
)

type StreamMap interface {
	Get(frame.StreamId) (stream, bool)
	Set(frame.StreamId, stream)
	Delete(frame.StreamId)
	Each(func(frame.StreamId, stream))
}

// ConcurrentStreamMap is a map of stream ids -> streams guarded by a read/write lock
type ConcurrentStreamMap struct {
	sync.RWMutex
	table map[frame.StreamId]stream
}

func (m *ConcurrentStreamMap) Get(id frame.StreamId) (s stream, ok bool) {
	m.RLock()
	s, ok = m.table[id]
	m.RUnlock()
	return
}

func (m *ConcurrentStreamMap) Set(id frame.StreamId, str stream) {
	m.Lock()
	m.table[id] = str
	m.Unlock()
}

func (m *ConcurrentStreamMap) Delete(id frame.StreamId) {
	m.Lock()
	delete(m.table, id)
	m.Unlock()
}

func (m *ConcurrentStreamMap) Each(fn func(frame.StreamId, stream)) {
	m.Lock()
	streams := make(map[frame.StreamId]stream, len(m.table))
	for k, v := range m.table {
		streams[k] = v
	}
	m.Unlock()

	for id, str := range streams {
		fn(id, str)
	}
}

func NewConcurrentStreamMap() *ConcurrentStreamMap {
	return &ConcurrentStreamMap{table: make(map[frame.StreamId]stream, initMapCapacity)}
}