-
Notifications
You must be signed in to change notification settings - Fork 40
/
ptr_shrink.go
45 lines (38 loc) · 990 Bytes
/
ptr_shrink.go
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
package gen
import (
"reflect"
"github.com/leanovate/gopter"
)
type nilShrink struct {
done bool
}
func (s *nilShrink) Next() (interface{}, bool) {
if !s.done {
s.done = true
return nil, true
}
return nil, false
}
// PtrShrinker convert a value shrinker to a pointer to value shrinker
func PtrShrinker(elementShrinker gopter.Shrinker) gopter.Shrinker {
return func(v interface{}) gopter.Shrink {
if v == nil {
return gopter.NoShrink
}
elem := reflect.ValueOf(v).Elem()
if !elem.IsValid() || !elem.CanInterface() {
return gopter.NoShrink
}
rt := reflect.TypeOf(v)
elementShink := elementShrinker(reflect.ValueOf(v).Elem().Interface())
nilShrink := &nilShrink{}
return gopter.ConcatShrinks(
nilShrink.Next,
elementShink.Map(func(elem interface{}) interface{} {
slice := reflect.MakeSlice(reflect.SliceOf(rt.Elem()), 0, 1)
slice = reflect.Append(slice, reflect.ValueOf(elem))
return slice.Index(0).Addr().Interface()
}),
)
}
}