forked from Monibuca/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring_av.go
91 lines (79 loc) · 1.54 KB
/
ring_av.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
package engine
import (
"container/ring"
"context"
"runtime"
"time"
)
type AVItem struct {
DataItem
canRead bool
}
type AVRing struct {
RingBuffer
poll time.Duration
}
func (r *AVRing) Init(ctx context.Context, n int) *AVRing {
r.Ring = ring.New(n)
r.Context = ctx
r.Size = n
for x := r.Ring; x.Value == nil; x = x.Next() {
x.Value = new(AVItem)
}
return r
}
func (r AVRing) Clone() *AVRing {
return &r
}
func (r AVRing) SubRing(rr *ring.Ring) *AVRing {
r.Ring = rr
return &r
}
func (r *AVRing) Write(value interface{}) {
last := r.Current()
last.Value = value
r.GetNext().canRead = false
last.canRead = true
}
func (r *AVRing) Step() {
last := r.Current()
r.GetNext().canRead = false
last.canRead = true
}
func (r *AVRing) wait() {
if r.poll == 0 {
runtime.Gosched()
} else {
time.Sleep(r.poll)
}
}
func (r *AVRing) CurrentValue() interface{} {
return r.Current().Value
}
func (r *AVRing) Current() *AVItem {
return r.Ring.Value.(*AVItem)
}
func (r *AVRing) NextValue() interface{} {
return r.Next().Value.(*AVItem).Value
}
func (r *AVRing) PreItem() *AVItem {
return r.Prev().Value.(*AVItem)
}
func (r *AVRing) GetNext() *AVItem {
r.MoveNext()
return r.Current()
}
func (r *AVRing) Read() (item *AVItem, value interface{}) {
current := r.Current()
for r.Err() == nil && !current.canRead {
r.wait()
}
return current, current.Value
}
func (r *AVRing) TryRead() (item *AVItem, value interface{}) {
current := r.Current()
if r.Err() == nil && !current.canRead {
return nil, nil
}
return current, current.Value
}