...

Source file src/cuelabs.dev/go/oci/ociregistry/iter.go

Documentation: cuelabs.dev/go/oci/ociregistry

     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  type sliceIter[T any] struct {
    40  	i  int
    41  	xs []T
    42  }
    43  
    44  func SliceIter[T any](xs []T) Seq[T] {
    45  	return func(yield func(T, error) bool) {
    46  		for _, x := range xs {
    47  			if !yield(x, nil) {
    48  				return
    49  			}
    50  		}
    51  	}
    52  }
    53  
    54  // ErrorIter returns an iterator that has no
    55  // items and always returns the given error.
    56  func ErrorIter[T any](err error) Seq[T] {
    57  	return func(yield func(T, error) bool) {
    58  		yield(*new(T), err)
    59  	}
    60  }
    61  

View as plain text