-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice_consumer.go
58 lines (48 loc) · 1.01 KB
/
slice_consumer.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
package slice
import "errors"
var (
ErrSliceEmpty = errors.New("slice empty")
)
// SliceConsumer 用于方便的从slice中按顺序消费数据,即把切片当做一个简单的队列
type SliceConsumer[T any] struct {
slice []T
index int
zero T
}
func NewSliceConsumer[T any](slice []T) *SliceConsumer[T] {
return &SliceConsumer[T]{
slice: slice,
index: 0,
}
}
func (x *SliceConsumer[T]) IsDone() bool {
return x.index >= len(x.slice)
}
func (x *SliceConsumer[T]) Peek() T {
if x.index >= len(x.slice) {
return x.zero
}
return x.slice[x.index]
}
func (x *SliceConsumer[T]) PeekE() (T, error) {
if x.index >= len(x.slice) {
return x.zero, ErrSliceEmpty
}
return x.slice[x.index], nil
}
func (x *SliceConsumer[T]) Take() T {
if x.index >= len(x.slice) {
return x.zero
}
result := x.slice[x.index]
x.index++
return result
}
func (x *SliceConsumer[T]) TakeE() (T, error) {
if x.index >= len(x.slice) {
return x.zero, ErrSliceEmpty
}
result := x.slice[x.index]
x.index++
return result, nil
}