1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/runtime/collections/unique.go

59 lines
962 B
Go
Raw Normal View History

package collections
import (
2018-10-28 07:45:26 +02:00
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
)
type (
UniqueIterator struct {
2018-10-28 07:45:26 +02:00
values Iterator
hashes map[uint64]bool
hashKey string
}
)
2018-10-28 07:45:26 +02:00
func NewUniqueIterator(values Iterator, hashKey string) (*UniqueIterator, error) {
if values == nil {
return nil, core.Error(core.ErrMissedArgument, "source")
}
return &UniqueIterator{
2018-10-28 07:45:26 +02:00
values: values,
hashes: make(map[uint64]bool),
hashKey: hashKey,
}, nil
}
2018-10-28 07:45:26 +02:00
func (iterator *UniqueIterator) Next(ctx context.Context, scope *core.Scope) (*core.Scope, error) {
for {
nextScope, err := iterator.values.Next(ctx, scope.Fork())
2018-10-28 07:45:26 +02:00
if err != nil {
return nil, err
}
2018-10-28 07:45:26 +02:00
if nextScope == nil {
return nil, nil
}
2018-10-28 07:45:26 +02:00
v, err := nextScope.GetVariable(iterator.hashKey)
if err != nil {
2018-10-28 07:45:26 +02:00
return nil, err
}
2018-10-28 07:45:26 +02:00
h := v.Hash()
_, exists := iterator.hashes[h]
if exists {
continue
}
iterator.hashes[h] = true
2018-10-28 07:45:26 +02:00
return nextScope, nil
}
}