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

     1  package gen
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/leanovate/gopter"
     7  )
     8  
     9  // PtrOf generates either a pointer to a generated element or a nil pointer
    10  func PtrOf(elementGen gopter.Gen) gopter.Gen {
    11  	return func(genParams *gopter.GenParameters) *gopter.GenResult {
    12  		element := elementGen(genParams)
    13  		elementShrinker := element.Shrinker
    14  		elementSieve := element.Sieve
    15  		value, ok := element.Retrieve()
    16  		if !ok || genParams.NextBool() {
    17  			result := gopter.NewEmptyResult(reflect.PtrTo(element.ResultType))
    18  			result.Sieve = func(v interface{}) bool {
    19  				if elementSieve == nil {
    20  					return true
    21  				}
    22  				r := reflect.ValueOf(v)
    23  				return !r.IsValid() || r.IsNil() || elementSieve(r.Elem().Interface())
    24  			}
    25  			return result
    26  		}
    27  		// To get the right pointer type we have to create a slice with one element
    28  		slice := reflect.MakeSlice(reflect.SliceOf(element.ResultType), 0, 1)
    29  		slice = reflect.Append(slice, reflect.ValueOf(value))
    30  
    31  		result := gopter.NewGenResult(slice.Index(0).Addr().Interface(), PtrShrinker(elementShrinker))
    32  		result.Sieve = func(v interface{}) bool {
    33  			if elementSieve == nil {
    34  				return true
    35  			}
    36  			r := reflect.ValueOf(v)
    37  			return !r.IsValid() || r.IsNil() || elementSieve(r.Elem().Interface())
    38  		}
    39  		return result
    40  	}
    41  }