-
Notifications
You must be signed in to change notification settings - Fork 52
/
queue.go
80 lines (69 loc) · 1.32 KB
/
queue.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
package limiter
import (
"errors"
"sync"
"time"
)
type circleQueue struct {
slice []int64
maxSize int
head int
tail int
sync.RWMutex
}
// newCircleQueue Initialize ring queue
func newCircleQueue(size int) *circleQueue {
var c circleQueue
c.maxSize = size + 1
c.slice = make([]int64, c.maxSize)
return &c
}
func (c *circleQueue) push(val int64) (err error) {
if c.isFull() {
return errors.New("queue is full")
}
c.slice[c.tail] = val
c.tail = (c.tail + 1) % c.maxSize
return
}
func (c *circleQueue) pop() (val int64, err error) {
if c.isEmpty() {
return 0, errors.New("queue is empty")
}
c.Lock()
defer c.Unlock()
val = c.slice[c.head]
c.head = (c.head + 1) % c.maxSize
return
}
func (c *circleQueue) isFull() bool {
return (c.tail+1)%c.maxSize == c.head
}
func (c *circleQueue) isEmpty() bool {
return c.tail == c.head
}
func (c *circleQueue) usedSize() int {
c.RLock()
defer c.RUnlock()
return (c.tail + c.maxSize - c.head) % c.maxSize
}
func (c *circleQueue) unUsedSize() int {
return c.maxSize - 1 - c.usedSize()
}
func (c *circleQueue) size() int {
return c.maxSize - 1
}
func (c *circleQueue) deleteExpired() {
now := time.Now().UnixNano()
size := c.usedSize()
if size == 0 {
return
}
for i := 0; i < size; i++ {
if now > c.slice[c.head] {
_, _ = c.pop()
} else {
return
}
}
}