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

     1  package gopter
     2  
     3  import "reflect"
     4  
     5  // GenResult contains the result of a generator.
     6  type GenResult struct {
     7  	Labels     []string
     8  	Shrinker   Shrinker
     9  	ResultType reflect.Type
    10  	Result     interface{}
    11  	Sieve      func(interface{}) bool
    12  }
    13  
    14  // NewGenResult creates a new generator result from for a concrete value and
    15  // shrinker.
    16  // Note: The concrete value "result" not be nil
    17  func NewGenResult(result interface{}, shrinker Shrinker) *GenResult {
    18  	return &GenResult{
    19  		Shrinker:   shrinker,
    20  		ResultType: reflect.TypeOf(result),
    21  		Result:     result,
    22  	}
    23  }
    24  
    25  // NewEmptyResult creates an empty generator result.
    26  // Unless the sieve does not explicitly allow it, empty (i.e. nil-valued)
    27  // results are considered invalid.
    28  func NewEmptyResult(resultType reflect.Type) *GenResult {
    29  	return &GenResult{
    30  		ResultType: resultType,
    31  		Shrinker:   NoShrinker,
    32  	}
    33  }
    34  
    35  // Retrieve gets the concrete generator result.
    36  // If the result is invalid or does not pass the sieve there is no concrete
    37  // value and the property using the generator should be undecided.
    38  func (r *GenResult) Retrieve() (interface{}, bool) {
    39  	if (r.Sieve == nil && r.Result != nil) || (r.Sieve != nil && r.Sieve(r.Result)) {
    40  		return r.Result, true
    41  	}
    42  	return nil, false
    43  }
    44  
    45  // RetrieveAsValue get the concrete generator result as reflect value.
    46  // If the result is invalid or does not pass the sieve there is no concrete
    47  // value and the property using the generator should be undecided.
    48  func (r *GenResult) RetrieveAsValue() (reflect.Value, bool) {
    49  	if r.Result != nil && (r.Sieve == nil || r.Sieve(r.Result)) {
    50  		return reflect.ValueOf(r.Result), true
    51  	} else if r.Result == nil && r.Sieve != nil && r.Sieve(r.Result) {
    52  		return reflect.Zero(r.ResultType), true
    53  	}
    54  	return reflect.Zero(r.ResultType), false
    55  }