This repository was archived by the owner on Oct 10, 2023. It is now read-only.
forked from AFathi/live-webrtcsignaling
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtools.sentinellist.go
83 lines (73 loc) · 1.63 KB
/
tools.sentinellist.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
package main
import (
"errors"
"github.com/heytribe/live-webrtcsignaling/my"
)
/*
* SentinelList is a fifo list struct:
*
* +---+
* | |
* nil <- | O |-> nil s := new(SentinelList)
* +---+
*
* +---+ +---+
* | | | |
* X <->| O |<->| X |<-> 0 s.Init()
* +---+ +---+
*
* +---+ +---+ +---+
* | | | | | |
* X <->| O |<->| 1 |<->| X |<-> 0 s.Push(1)
* +---+ +---+ +---+
*
* +---+ +---+ +---+ +---+
* | | | | | | | |
* X <- | O |<->| 2 |<->| 1 |<->| X |<-> 0 s.Push(2)
* +---+ +---+ +---+ +---+
*
* +---+ +---+ +---+
* | | | | | |
* X <- | O |<->| 2 |<->| X |-> 0 s.Pop() // => 1
* +---+ +---+ +---+
*
* Pop() on empty list => err
*/
type SentinelList struct {
my.RWMutex
data interface{}
next *SentinelList
prev *SentinelList
}
func (l *SentinelList) Init() {
l.Lock()
defer l.Unlock()
last := new(SentinelList)
l.next = last
l.prev = last
last.next = l
last.prev = l
}
func (l *SentinelList) Push(data interface{}) {
l.Lock()
defer l.Unlock()
lElement := new(SentinelList)
lElement.data = data
lElement.prev = l
lElement.next = l.next
l.next.prev = lElement
l.next = lElement
}
func (l *SentinelList) Pop() (data interface{}, err error) {
l.Lock()
defer l.Unlock()
if l.prev == l.next {
err = errors.New("no data to pop")
return
}
lElement := l.prev.prev
lElement.next.prev = lElement.prev
lElement.prev.next = lElement.next
data = lElement.data
return
}