| 1 | // Copyright 2023 CUE Labs AG |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package ociregistry |
| 16 | |
| 17 | // TODO(go1.23) when we can depend on Go 1.23, this should be: |
| 18 | // type Seq[T any] = iter.Seq2[T, error] |
| 19 | |
| 20 | // Seq defines the type of an iterator sequence returned from |
| 21 | // the iterator functions. In general, a non-nil |
| 22 | // error means that the item is the last in the sequence. |
| 23 | type Seq[T any] func(yield func(T, error) bool) |
| 24 | |
| 25 | func All[T any](it Seq[T]) (_ []T, _err error) { |
| 26 | xs := []T{} |
| 27 | // TODO(go1.23) for x, err := range it |
| 28 | it(func(x T, err error) bool { |
| 29 | if err != nil { |
| 30 | _err = err |
| 31 | return false |
| 32 | } |
| 33 | xs = append(xs, x) |
| 34 | return true |
| 35 | }) |
| 36 | return xs, _err |
| 37 | } |
| 38 | |
| 39 | func SliceSeq[T any](xs []T) Seq[T] { |
| 40 | return func(yield func(T, error) bool) { |
| 41 | for _, x := range xs { |
| 42 | if !yield(x, nil) { |
| 43 | return |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | // ErrorSeq returns an iterator that has no |
| 50 | // items and always returns the given error. |
| 51 | func ErrorSeq[T any](err error) Seq[T] { |
| 52 | return func(yield func(T, error) bool) { |
| 53 | yield(*new(T), err) |
| 54 | } |
| 55 | } |