github.com/MontFerret/ferret@v0.18.0/pkg/runtime/collections/adapters.go (about) 1 package collections 2 3 import ( 4 "context" 5 6 "github.com/MontFerret/ferret/pkg/runtime/core" 7 ) 8 9 type ( 10 coreIterableAdapter struct { 11 valVar string 12 keyVar string 13 iterable core.Iterable 14 } 15 16 coreIteratorAdapter struct { 17 valVar string 18 keyVar string 19 iterator core.Iterator 20 } 21 ) 22 23 func FromCoreIterable(valVar, keyVar string, iterable core.Iterable) (Iterable, error) { 24 if valVar == "" { 25 return nil, core.Error(core.ErrMissedArgument, "value variable") 26 } 27 28 if iterable == nil { 29 return nil, core.Error(core.ErrMissedArgument, "iterable") 30 } 31 32 return &coreIterableAdapter{valVar, keyVar, iterable}, nil 33 } 34 35 func (c *coreIterableAdapter) Iterate(ctx context.Context, _ *core.Scope) (Iterator, error) { 36 iter, err := c.iterable.Iterate(ctx) 37 38 if err != nil { 39 return nil, err 40 } 41 42 return FromCoreIterator(c.valVar, c.keyVar, iter) 43 } 44 45 func FromCoreIterator(valVar, keyVar string, iterator core.Iterator) (Iterator, error) { 46 if valVar == "" { 47 return nil, core.Error(core.ErrMissedArgument, "value variable") 48 } 49 50 if iterator == nil { 51 return nil, core.Error(core.ErrMissedArgument, "iterator") 52 } 53 54 return &coreIteratorAdapter{valVar, keyVar, iterator}, nil 55 } 56 57 func (iterator *coreIteratorAdapter) Next(ctx context.Context, scope *core.Scope) (*core.Scope, error) { 58 val, key, err := iterator.iterator.Next(ctx) 59 60 if err != nil { 61 return nil, err 62 } 63 64 nextScope := scope.Fork() 65 66 if err := nextScope.SetVariable(iterator.valVar, val); err != nil { 67 return nil, err 68 } 69 70 if iterator.keyVar != "" { 71 if err := nextScope.SetVariable(iterator.keyVar, key); err != nil { 72 return nil, err 73 } 74 } 75 76 return nextScope, nil 77 }