go-zero/core/collection/ring.go

53 lines
876 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package collection
import "sync"
// A Ring can be used as fixed size ring.
2020-07-26 17:09:05 +08:00
type Ring struct {
elements []any
2020-07-26 17:09:05 +08:00
index int
lock sync.RWMutex
2020-07-26 17:09:05 +08:00
}
// NewRing returns a Ring object with the given size n.
2020-07-26 17:09:05 +08:00
func NewRing(n int) *Ring {
2020-10-15 14:25:10 +08:00
if n < 1 {
panic("n should be greater than 0")
}
2020-07-26 17:09:05 +08:00
return &Ring{
elements: make([]any, n),
2020-07-26 17:09:05 +08:00
}
}
// Add adds v into r.
func (r *Ring) Add(v any) {
r.lock.Lock()
defer r.lock.Unlock()
2021-02-05 13:32:56 +08:00
2020-07-26 17:09:05 +08:00
r.elements[r.index%len(r.elements)] = v
r.index++
}
// Take takes all items from r.
func (r *Ring) Take() []any {
r.lock.RLock()
defer r.lock.RUnlock()
2020-07-26 17:09:05 +08:00
var size int
var start int
if r.index > len(r.elements) {
size = len(r.elements)
start = r.index % len(r.elements)
} else {
size = r.index
}
elements := make([]any, size)
2020-07-26 17:09:05 +08:00
for i := 0; i < size; i++ {
elements[i] = r.elements[(start+i)%len(r.elements)]
}
return elements
}