-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrange.go
85 lines (73 loc) · 1.82 KB
/
range.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
81
82
83
84
85
package glinq
import (
"io"
"math"
"sync/atomic"
"golang.org/x/exp/constraints"
)
type (
RangeIterator[T constraints.Integer | constraints.Float] struct {
iterator[T]
start, end, step T
}
)
func NewRangeIterator[T constraints.Integer | constraints.Float](start, end, step T) *RangeIterator[T] {
result := &RangeIterator[T]{
start: start,
end: end,
step: step,
}
result.child = result
return result
}
func Range[T constraints.Integer | constraints.Float](start, end T) IEnumerable[T] {
return NewRangeIterator(start, end, T(1))
}
func RangeStep[T constraints.Integer | constraints.Float](start, end, step T) IEnumerable[T] {
return NewRangeIterator(start, end, step)
}
func (me *RangeIterator[T]) MoveNext() error {
switch me.state {
case 1:
me.current = me.start
me.state = 2
return nil
case 2:
me.current += me.step
if me.current >= me.end {
me.state = -1
return io.EOF
}
return nil
}
return ErrInvalidState
}
func (me *RangeIterator[T]) Count() int {
return int(math.Ceil(float64(me.end-me.start) / float64(me.step)))
}
func (me *RangeIterator[T]) Any() bool {
return me.end > me.start
}
func (me *RangeIterator[T]) Clone() IEnumerator[T] {
result := NewRangeIterator(me.start, me.end, me.step)
result.state = 1
return result
}
func (me *RangeIterator[T]) GetAt(pos int) (result T, err error) {
current := me.start + me.step*T(pos)
if current < me.end {
return current, nil
}
return result, io.ErrUnexpectedEOF
}
func (me *RangeIterator[T]) SeekOnce(pos int) error {
if atomic.CompareAndSwapInt32(&me.state, 1, 2) { // can only seek once
current := me.start + me.step*T(pos)
if current < me.end {
me.current = current
return nil
}
return io.ErrUnexpectedEOF
}
return ErrInvalidState
}