github.com/leanovate/gopter@v0.2.9/gen/ptr_shrink.go (about)

     1  package gen
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/leanovate/gopter"
     7  )
     8  
     9  type nilShrink struct {
    10  	done bool
    11  }
    12  
    13  func (s *nilShrink) Next() (interface{}, bool) {
    14  	if !s.done {
    15  		s.done = true
    16  		return nil, true
    17  	}
    18  	return nil, false
    19  }
    20  
    21  // PtrShrinker convert a value shrinker to a pointer to value shrinker
    22  func PtrShrinker(elementShrinker gopter.Shrinker) gopter.Shrinker {
    23  	return func(v interface{}) gopter.Shrink {
    24  		if v == nil {
    25  			return gopter.NoShrink
    26  		}
    27  		elem := reflect.ValueOf(v).Elem()
    28  		if !elem.IsValid() || !elem.CanInterface() {
    29  			return gopter.NoShrink
    30  		}
    31  		rt := reflect.TypeOf(v)
    32  		elementShink := elementShrinker(reflect.ValueOf(v).Elem().Interface())
    33  
    34  		nilShrink := &nilShrink{}
    35  		return gopter.ConcatShrinks(
    36  			nilShrink.Next,
    37  			elementShink.Map(func(elem interface{}) interface{} {
    38  				slice := reflect.MakeSlice(reflect.SliceOf(rt.Elem()), 0, 1)
    39  				slice = reflect.Append(slice, reflect.ValueOf(elem))
    40  
    41  				return slice.Index(0).Addr().Interface()
    42  			}),
    43  		)
    44  	}
    45  }