forked from Knetic/govaluate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsanitizedParameters.go
101 lines (88 loc) · 1.95 KB
/
sanitizedParameters.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package govaluate
import (
"errors"
"fmt"
"reflect"
)
// sanitizedParameters is a wrapper for Parameters that does sanitization as
// parameters are accessed.
type sanitizedParameters struct {
orig Parameters
}
func (p sanitizedParameters) Get(key string) (interface{}, error) {
value, err := p.orig.Get(key)
if err != nil {
return nil, err
}
// make sure that the parameter is a valid type.
err = checkValidType(key, value)
if err != nil {
return nil, err
}
// should be converted to fixed point?
if isFixedPoint(value) {
return castFixedPoint(value), nil
}
return value, nil
}
func checkValidType(key string, value interface{}) error {
switch value.(type) {
case complex64:
errorMsg := fmt.Sprintf("Parameter '%s' is a complex64 integer, which is not evaluable", key)
return errors.New(errorMsg)
case complex128:
errorMsg := fmt.Sprintf("Parameter '%s' is a complex128 integer, which is not evaluable", key)
return errors.New(errorMsg)
}
if reflect.ValueOf(value).Kind() == reflect.Struct {
errorMsg := fmt.Sprintf("Parameter '%s' is a struct, which is not evaluable", key)
return errors.New(errorMsg)
}
return nil
}
func isFixedPoint(value interface{}) bool {
switch value.(type) {
case uint8:
return true
case uint16:
return true
case uint32:
return true
case uint64:
return true
case int8:
return true
case int16:
return true
case int32:
return true
case int64:
return true
case int:
return true
}
return false
}
func castFixedPoint(value interface{}) float64 {
switch value.(type) {
case uint8:
return float64(value.(uint8))
case uint16:
return float64(value.(uint16))
case uint32:
return float64(value.(uint32))
case uint64:
return float64(value.(uint64))
case int8:
return float64(value.(int8))
case int16:
return float64(value.(int16))
case int32:
return float64(value.(int32))
case int64:
return float64(value.(int64))
case int:
return float64(value.(int))
}
return 0.0
}