1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
circular.go 2.15 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-08-26 20:30 . scheduler foreach
package queue
type ResetFunc func()
var _ Queue = (*Circular)(nil)
// Circular 环型队列
type Circular struct {
resetFunc ResetFunc
items []any
head int
tail int
size int
isFull bool
}
func NewCircular(size int, resetFunc ResetFunc) *Circular {
return &Circular{
resetFunc: resetFunc,
items: make([]any, size),
size: size,
}
}
func (cr *Circular) Add(it any) error {
if cr.size == 0 {
return ErrIsReleased
}
if cr.isFull {
return ErrIsFull
}
cr.items[cr.tail] = it
cr.tail++
if cr.tail == cr.size {
cr.tail = 0
}
if cr.tail == cr.head {
cr.isFull = true
}
return nil
}
func (cr *Circular) Push(it any) error {
return cr.Add(it)
}
func (cr *Circular) Pop() any {
if cr.Empty() {
return nil
}
w := cr.items[cr.head]
cr.items[cr.head] = nil
cr.head++
if cr.head == cr.size {
cr.head = 0
}
cr.isFull = false
return w
}
func (cr *Circular) Peek() any {
if cr.Empty() {
return nil
}
return cr.items[cr.head]
}
func (cr *Circular) Len() int {
if cr.size == 0 {
return 0
}
if cr.head == cr.tail {
if cr.isFull {
return cr.size
}
return 0
}
if cr.tail > cr.head {
return cr.tail - cr.head
}
return cr.size - cr.head + cr.tail
}
// Find return index -1 not found.
func (cr *Circular) Find(fn IndexFunc) (any, int) {
var (
cursor = -1
va any
)
for {
va, cursor = cr.Next(cursor)
if cursor == -1 {
break
}
if fn(va, cursor) {
return va, cursor
}
}
return nil, -1
}
func (cr *Circular) Foreach(fn IndexFunc) {
var (
cursor = -1
va any
)
for {
va, cursor = cr.Next(cursor)
if cursor == -1 {
break
}
if fn(va, cursor) {
return
}
}
}
func (cr *Circular) Empty() bool {
return cr.head == cr.tail && !cr.isFull
}
func (cr *Circular) Next(index int) (any, int) {
if cr.Empty() {
return nil, -1
}
if index < 0 {
index = cr.head
}
if index == cr.tail {
return nil, -1
}
w := cr.items[index]
index++
if index == cr.size {
index = 0
}
return w, index
}
func (cr *Circular) Reset() {
if cr.Empty() {
return
}
if cr.resetFunc != nil {
cr.resetFunc()
}
cr.items = make([]any, cr.size)
cr.head = 0
cr.tail = 0
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.22.6

搜索帮助