| 1 |
// Licensed under the MIT license, see LICENSE file for details. |
| 2 |
|
| 3 |
package quicktest |
| 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 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() reflect.Value |
| 19 |
} |
| 20 |
|
| 21 |
// newIter returns an iterator over x which must be a map, slice |
| 22 |
// or array. |
| 23 |
func newIter(x interface{}) (containerIter, error) { |
| 24 |
v := reflect.ValueOf(x) |
| 25 |
switch v.Kind() { |
| 26 |
case reflect.Map: |
| 27 |
return newMapIter(v), nil |
| 28 |
case reflect.Slice, reflect.Array: |
| 29 |
return &sliceIter{ |
| 30 |
index: -1, |
| 31 |
v: v, |
| 32 |
}, nil |
| 33 |
default: |
| 34 |
return nil, fmt.Errorf("map, slice or array required") |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
// sliceIter implements containerIter for slices and arrays. |
| 39 |
type sliceIter struct { |
| 40 |
v reflect.Value |
| 41 |
index int |
| 42 |
} |
| 43 |
|
| 44 |
func (i *sliceIter) next() bool { |
| 45 |
i.index++ |
| 46 |
return i.index < i.v.Len() |
| 47 |
} |
| 48 |
|
| 49 |
func (i *sliceIter) value() reflect.Value { |
| 50 |
return i.v.Index(i.index) |
| 51 |
} |
| 52 |
|
| 53 |
func (i *sliceIter) key() string { |
| 54 |
return fmt.Sprintf("index %d", i.index) |
| 55 |
} |