1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/runtime/collections/limit.go
2018-10-28 01:45:26 -04:00

63 lines
1.2 KiB
Go

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
}