-
Notifications
You must be signed in to change notification settings - Fork 7
/
value.go
70 lines (64 loc) · 1.73 KB
/
value.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package pack
import (
"encoding/json"
"math/rand"
"reflect"
"testing/quick"
"github.com/renproject/surge"
)
// A Value is a common interface for all values that are able to be marshaled to
// binary and JSON, and are able to express their type information.
type Value interface {
surge.Marshaler
json.Marshaler
Type() Type
}
// Generate a random value. This is helpful when implementing generators for
// other types. See https://golang.org/pkg/testing/quick/#Generator for more
// information.
func Generate(r *rand.Rand, size int, allowStruct, allowList bool) reflect.Value {
kind, _ := quick.Value(reflect.TypeOf(Kind(0)), r)
return GenerateFromKind(r, size, kind.Interface().(Kind), allowStruct, allowList)
}
// GenerateFromKind generates a random value given a Kind.
func GenerateFromKind(r *rand.Rand, size int, kind Kind, allowStruct, allowList bool) reflect.Value {
t := reflect.Type(nil)
switch kind {
case KindBool:
t = reflect.TypeOf(Bool(false))
case KindU8:
t = reflect.TypeOf(U8(0))
case KindU16:
t = reflect.TypeOf(U16(0))
case KindU32:
t = reflect.TypeOf(U32(0))
case KindU64:
t = reflect.TypeOf(U64(0))
case KindU128:
t = reflect.TypeOf(U128{})
case KindU256:
t = reflect.TypeOf(U256{})
case KindString:
t = reflect.TypeOf(String(""))
case KindBytes:
t = reflect.TypeOf(Bytes{})
case KindBytes32:
t = reflect.TypeOf(Bytes32{})
case KindBytes65:
t = reflect.TypeOf(Bytes65{})
case KindStruct:
if !allowStruct {
return Generate(r, size, allowStruct, allowList)
}
t = reflect.TypeOf(Struct{})
case KindList:
if !allowList {
return Generate(r, size, allowStruct, allowList)
}
t = reflect.TypeOf(List{})
default:
panic("non-exhaustive pattern")
}
v, _ := quick.Value(t, r)
return v
}