~f4814n/frost

ref: ff15c3c08fea frost/mux.go -rw-r--r-- 1.6 KiB
ff15c3c0Fabian Geiselhart Add screenshots 4 months ago
                                                                                
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package frost

import (
	"reflect"
	"sync"
)

type Mux struct {
	sync.Mutex

	currentID uint

	events chan interface{}

	rx map[uint]chan Event
	tx map[uint]chan Event
}

type registerEvent struct {
	rx chan Event
	tx chan Event
	id uint
}

type unregisterEvent struct {
	id uint
}

func NewMux() *Mux {
	return &Mux{
		currentID: 0,
		events:    make(chan interface{}, 100),
		rx:        make(map[uint]chan Event),
		tx:        make(map[uint]chan Event),
	}
}

func (m *Mux) Register() (id uint, rx, tx chan Event) {
	m.Lock()
	defer m.Unlock()

	rx = make(chan Event, 100)
	tx = make(chan Event, 100)

	m.currentID += 1
	m.events <- registerEvent{
		rx: tx,
		tx: rx,
		id: m.currentID,
	}

	return m.currentID, rx, tx
}

func (m *Mux) Unregister(id uint) {
	m.events <- unregisterEvent{
		id: id,
	}
}

func (m *Mux) Run() {
	cases := m.cases()
	for {
		chosen, recv, recvOk := reflect.Select(cases)
		if chosen == 0 {
			if !recvOk {
				return
			}
			switch event := recv.Interface().(type) {
			case registerEvent:
				m.rx[event.id] = event.rx
				m.tx[event.id] = event.tx

				cases = m.cases()
			case unregisterEvent:
				delete(m.tx, event.id)
				delete(m.rx, event.id)
				cases = m.cases()
			}
		} else {
			for _, ch := range m.tx {
				ch <- recv.Interface().(Event)
			}
		}
	}
}

func (m *Mux) Stop() {
	close(m.events)
}

func (m *Mux) cases() []reflect.SelectCase {
	cases := []reflect.SelectCase{
		{
			Dir:  reflect.SelectRecv,
			Chan: reflect.ValueOf(m.events),
		},
	}

	for _, ch := range m.rx {
		cases = append(cases, reflect.SelectCase{
			Dir:  reflect.SelectRecv,
			Chan: reflect.ValueOf(ch),
		})
	}

	return cases
}