/
bounded.go
52 lines (45 loc) · 1.31 KB
/
bounded.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
package mailbox
import (
"github.com/AsynkronIT/protoactor-go/internal/queue/mpsc"
rbqueue "github.com/Workiva/go-datastructures/queue"
)
type boundedMailboxQueue struct {
userMailbox *rbqueue.RingBuffer
dropping bool
}
func (q *boundedMailboxQueue) Push(m interface{}) {
if q.dropping {
if q.userMailbox.Len() > 0 && q.userMailbox.Cap()-1 == q.userMailbox.Len() {
q.userMailbox.Get()
}
}
q.userMailbox.Put(m)
}
func (q *boundedMailboxQueue) Pop() interface{} {
if q.userMailbox.Len() > 0 {
m, _ := q.userMailbox.Get()
return m
}
return nil
}
// Bounded returns a producer which creates an bounded mailbox of the specified size
func Bounded(size int, mailboxStats ...Statistics) Producer {
return bounded(size, false, mailboxStats...)
}
// Bounded dropping returns a producer which creates an bounded mailbox of the specified size that drops front element on push
func BoundedDropping(size int, mailboxStats ...Statistics) Producer {
return bounded(size, true, mailboxStats...)
}
func bounded(size int, dropping bool, mailboxStats ...Statistics) Producer {
return func() Mailbox {
q := &boundedMailboxQueue{
userMailbox: rbqueue.NewRingBuffer(uint64(size)),
dropping: dropping,
}
return &defaultMailbox{
systemMailbox: mpsc.New(),
userMailbox: q,
mailboxStats: mailboxStats,
}
}
}