forked from MontFerret/ferret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
limit.go
62 lines (47 loc) · 1.19 KB
/
limit.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
package collections
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
)
type LimitIterator struct {
values Iterator
count int
offset int
currCount int
}
func NewLimitIterator(values Iterator, count, offset int) (*LimitIterator, error) {
if values == nil {
return nil, core.Error(core.ErrMissedArgument, "result")
}
return &LimitIterator{values, count, offset, 0}, nil
}
func (iterator *LimitIterator) Next(ctx context.Context, scope *core.Scope) (*core.Scope, error) {
if err := iterator.verifyOffset(ctx, scope); err != nil {
return nil, err
}
iterator.currCount++
if iterator.counter() <= iterator.count {
return iterator.values.Next(ctx, scope)
}
return nil, nil
}
func (iterator *LimitIterator) counter() int {
return iterator.currCount - iterator.offset
}
func (iterator *LimitIterator) verifyOffset(ctx context.Context, scope *core.Scope) error {
if iterator.offset == 0 {
return nil
}
for iterator.offset > iterator.currCount {
nextScope, err := iterator.values.Next(ctx, scope.Fork())
if err != nil {
return err
}
if nextScope == nil {
iterator.currCount = iterator.offset
return nil
}
iterator.currCount++
}
return nil
}