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

63 lines
1.2 KiB
Go
Raw Normal View History

2018-09-18 22:42:38 +02:00
package collections
import (
2018-10-28 07:45:26 +02:00
"context"
2018-09-18 22:42:38 +02:00
"github.com/MontFerret/ferret/pkg/runtime/core"
)
type LimitIterator struct {
2018-10-28 07:45:26 +02:00
values Iterator
2018-09-18 22:42:38 +02:00
count int
offset int
currCount int
}
2018-10-28 07:45:26 +02:00
func NewLimitIterator(values Iterator, count, offset int) (*LimitIterator, error) {
if values == nil {
return nil, core.Error(core.ErrMissedArgument, "result")
2018-09-18 22:42:38 +02:00
}
2018-10-28 07:45:26 +02:00
return &LimitIterator{values, count, offset, 0}, nil
2018-09-18 22:42:38 +02:00
}
2018-10-28 07:45:26 +02:00
func (iterator *LimitIterator) Next(ctx context.Context, scope *core.Scope) (*core.Scope, error) {
if err := iterator.verifyOffset(ctx, scope); err != nil {
return nil, err
2018-09-18 22:42:38 +02:00
}
2018-10-28 07:45:26 +02:00
iterator.currCount++
2018-09-18 22:42:38 +02:00
2018-10-28 07:45:26 +02:00
if iterator.counter() <= iterator.count {
return iterator.values.Next(ctx, scope)
2018-09-18 22:42:38 +02:00
}
2018-10-28 07:45:26 +02:00
return nil, nil
2018-09-18 22:42:38 +02:00
}
2018-10-28 07:45:26 +02:00
func (iterator *LimitIterator) counter() int {
return iterator.currCount - iterator.offset
2018-09-18 22:42:38 +02:00
}
2018-10-28 07:45:26 +02:00
func (iterator *LimitIterator) verifyOffset(ctx context.Context, scope *core.Scope) error {
if iterator.offset == 0 {
return nil
2018-09-18 22:42:38 +02:00
}
2018-10-28 07:45:26 +02:00
for iterator.offset > iterator.currCount {
nextScope, err := iterator.values.Next(ctx, scope.Fork())
2018-09-18 22:42:38 +02:00
2018-10-28 07:45:26 +02:00
if err != nil {
return err
}
if nextScope == nil {
iterator.currCount = iterator.offset
return nil
}
iterator.currCount++
2018-09-18 22:42:38 +02:00
}
2018-10-28 07:45:26 +02:00
return nil
2018-09-18 22:42:38 +02:00
}