aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/frankban/quicktest/iter.go
blob: 28abd8a7684b9b3e9db03655027a3f9733fdb255 (plain) (blame)
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
// Licensed under the MIT license, see LICENSE file for details.

package quicktest

import (
	"fmt"
	"reflect"
)

// containerIter provides an interface for iterating over a container
// (map, slice or array).
type containerIter 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() reflect.Value
}

// newIter returns an iterator over x which must be a map, slice
// or array.
func newIter(x interface{}) (containerIter, error) {
	v := reflect.ValueOf(x)
	switch v.Kind() {
	case reflect.Map:
		return newMapIter(v), nil
	case reflect.Slice, reflect.Array:
		return &sliceIter{
			index: -1,
			v:     v,
		}, nil
	default:
		return nil, fmt.Errorf("map, slice or array required")
	}
}

// sliceIter implements containerIter for slices and arrays.
type sliceIter struct {
	v     reflect.Value
	index int
}

func (i *sliceIter) next() bool {
	i.index++
	return i.index < i.v.Len()
}

func (i *sliceIter) value() reflect.Value {
	return i.v.Index(i.index)
}

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