File: iter.go

package info (click to toggle)
golang-github-go-quicktest-qt 1.101.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 236 kB
  • sloc: makefile: 2
file content (69 lines) | stat: -rw-r--r-- 1,354 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Licensed under the MIT license, see LICENSE file for details.

package qt

import (
	"fmt"
	"reflect"
)

// containerIter provides an interface for iterating over a container
// (map, slice or array).
type containerIter[T any] interface {
	// next advances to the next item in the container.
	next() bool
	// key returns the current key as a string.
	key() string
	// value returns the current value.
	value() T
}

func newSliceIter[T any](slice []T) *sliceIter[T] {
	return &sliceIter[T]{
		slice: slice,
		index: -1,
	}
}

// sliceIter implements containerIter for slices and arrays.
type sliceIter[T any] struct {
	slice []T
	index int
}

func (i *sliceIter[T]) next() bool {
	i.index++
	return i.index < len(i.slice)
}

func (i *sliceIter[T]) value() T {
	return i.slice[i.index]
}

func (i *sliceIter[T]) key() string {
	return fmt.Sprintf("index %d", i.index)
}

func newMapIter[K comparable, V any](m map[K]V) containerIter[V] {
	return mapValueIter[V]{
		iter: reflect.ValueOf(m).MapRange(),
	}
}

// mapValueIter implements containerIter for maps.
type mapValueIter[T any] struct {
	iter *reflect.MapIter
	v    T
}

func (i mapValueIter[T]) next() bool {
	return i.iter.Next()
}

func (i mapValueIter[T]) key() string {
	return fmt.Sprintf("key %#v", i.iter.Key())
}

func (i mapValueIter[T]) value() T {
	return valueAs[T](i.iter.Value())
}