-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathannouncement_map.go
100 lines (90 loc) · 2.25 KB
/
announcement_map.go
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
package moqtransport
import (
"slices"
"sync"
)
type announcementMap struct {
lock sync.Mutex
pending []*announcement
announcements []*announcement
}
func newAnnouncementMap() *announcementMap {
return &announcementMap{
lock: sync.Mutex{},
pending: []*announcement{},
}
}
func findAnnouncement(as []*announcement, namespace []string) int {
return slices.IndexFunc(as, func(x *announcement) bool {
return slices.Equal(namespace, x.Namespace)
})
}
func (m *announcementMap) add(a *announcement) error {
m.lock.Lock()
defer m.lock.Unlock()
i := findAnnouncement(m.pending, a.Namespace)
if i >= 0 {
return errDuplicateAnnouncementNamespace
}
m.pending = append(m.pending, a)
return nil
}
func (m *announcementMap) confirmAndGet(namespace []string) (*announcement, error) {
m.lock.Lock()
defer m.lock.Unlock()
i := findAnnouncement(m.pending, namespace)
if i < 0 {
return nil, errUnknownAnnouncement
}
e := m.pending[i]
m.pending = slices.Delete(m.pending, i, i+1)
i = findAnnouncement(m.announcements, e.Namespace)
if i > 0 {
return nil, errDuplicateAnnouncementNamespace
}
m.announcements = append(m.announcements, e)
return e, nil
}
func (m *announcementMap) confirm(namespace []string) error {
m.lock.Lock()
defer m.lock.Unlock()
i := findAnnouncement(m.pending, namespace)
if i < 0 {
return errUnknownAnnouncement
}
e := m.pending[i]
m.pending = slices.Delete(m.pending, i, i+1)
i = findAnnouncement(m.announcements, e.Namespace)
if i > 0 {
return errDuplicateAnnouncementNamespace
}
m.announcements = append(m.announcements, e)
return nil
}
func (m *announcementMap) reject(namespace []string) (*announcement, bool) {
m.lock.Lock()
defer m.lock.Unlock()
i := findAnnouncement(m.pending, namespace)
if i < 0 {
return nil, false
}
e := m.pending[i]
m.pending = slices.Delete(m.pending, i, i+1)
return e, true
}
func (m *announcementMap) delete(namespace []string) bool {
m.lock.Lock()
defer m.lock.Unlock()
deleted := false
i := findAnnouncement(m.pending, namespace)
if i >= 0 {
m.pending = slices.Delete(m.pending, i, i+1)
deleted = true
}
i = findAnnouncement(m.announcements, namespace)
if i < 0 {
m.announcements = slices.Delete(m.announcements, i, i+1)
deleted = true
}
return deleted
}