File: stream_map.go

package info (click to toggle)
golang-github-inconshreveable-muxado 0.0~git20140312.0.f693c7e-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 256 kB
  • ctags: 374
  • sloc: makefile: 2
file content (59 lines) | stat: -rw-r--r-- 1,239 bytes parent folder | download | duplicates (3)
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 (
	"github.com/inconshreveable/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)}
}