| 1 |
// Licensed under the MIT license, see LICENSE file for details. |
| 2 |
|
| 3 |
package qt |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"reflect" |
| 8 |
) |
| 9 |
|
| 10 |
// containerIter provides an interface for iterating over a container |
| 11 |
// (map, slice or array). |
| 12 |
type containerIter[T any] interface { |
| 13 |
// next advances to the next item in the container. |
| 14 |
next() bool |
| 15 |
// key returns the current key as a string. |
| 16 |
key() string |
| 17 |
// value returns the current value. |
| 18 |
value() T |
| 19 |
} |
| 20 |
|
| 21 |
func newSliceIter[T any](slice []T) *sliceIter[T] { |
| 22 |
return &sliceIter[T]{ |
| 23 |
slice: slice, |
| 24 |
index: -1, |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
// sliceIter implements containerIter for slices and arrays. |
| 29 |
type sliceIter[T any] struct { |
| 30 |
slice []T |
| 31 |
index int |
| 32 |
} |
| 33 |
|
| 34 |
func (i *sliceIter[T]) next() bool { |
| 35 |
i.index++ |
| 36 |
return i.index < len(i.slice) |
| 37 |
} |
| 38 |
|
| 39 |
func (i *sliceIter[T]) value() T { |
| 40 |
return i.slice[i.index] |
| 41 |
} |
| 42 |
|
| 43 |
func (i *sliceIter[T]) key() string { |
| 44 |
return fmt.Sprintf("index %d", i.index) |
| 45 |
} |
| 46 |
|
| 47 |
func newMapIter[K comparable, V any](m map[K]V) containerIter[V] { |
| 48 |
return mapValueIter[V]{ |
| 49 |
iter: reflect.ValueOf(m).MapRange(), |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
// mapValueIter implements containerIter for maps. |
| 54 |
type mapValueIter[T any] struct { |
| 55 |
iter *reflect.MapIter |
| 56 |
v T |
| 57 |
} |
| 58 |
|
| 59 |
func (i mapValueIter[T]) next() bool { |
| 60 |
return i.iter.Next() |
| 61 |
} |
| 62 |
|
| 63 |
func (i mapValueIter[T]) key() string { |
| 64 |
return fmt.Sprintf("key %#v", i.iter.Key()) |
| 65 |
} |
| 66 |
|
| 67 |
func (i mapValueIter[T]) value() T { |
| 68 |
return valueAs[T](i.iter.Value()) |
| 69 |
} |