-
Notifications
You must be signed in to change notification settings - Fork 1
/
where.go
72 lines (63 loc) · 1.55 KB
/
where.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
package glinq
import "sync/atomic"
type WhereEnumerableIterator[T any] struct {
iterator[T]
source IEnumerable[T]
pred func(T) bool
enumerator IEnumerator[T]
}
// func (me *WhereEnumerator[T]) GetEnumerator() IEnumerator[T] {
// return me
// }
func NewWhereIterator[T any](source IEnumerable[T], pred func(T) bool) *WhereEnumerableIterator[T] {
result := &WhereEnumerableIterator[T]{
source: source,
pred: pred,
}
result.child = result
return result
}
func Where[T any](source IEnumerable[T], pred func(T) bool) IEnumerable[T] {
return NewWhereIterator(source, pred)
}
func (me *WhereEnumerableIterator[T]) MoveNext() error {
switch me.state {
case 1:
me.enumerator = me.source.GetEnumerator()
me.state = 2
fallthrough
case 2:
for {
err := me.enumerator.MoveNext()
if err != nil {
return err
}
item := me.enumerator.Current()
if me.pred(item) {
me.current = item
return nil
}
}
}
return ErrInvalidState
}
func (me *WhereEnumerableIterator[T]) Clone() IEnumerator[T] {
result := NewWhereIterator(me.source, me.pred)
result.state = 1
return result
}
func (me *WhereEnumerableIterator[T]) Any() bool {
return me.Clone().MoveNext() == nil
}
func (me *WhereEnumerableIterator[T]) Count() int {
if atomic.CompareAndSwapInt32(&me.state, 0, 1) {
count := 0
for err := me.MoveNext(); err == nil; err = me.MoveNext() {
count++
}
return count
} else {
result := NewWhereIterator(me.source, me.pred)
return result.Count()
}
}