/
parameter_float.go
102 lines (81 loc) · 1.99 KB
/
parameter_float.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
102
package config
import (
"context"
"fmt"
"math"
"strconv"
)
const ParameterFloat = "float"
var (
paramFloatMax = func() float64 {
val, err := strconv.ParseFloat("+inf", 64)
if err != nil {
panic(err)
}
return val
}()
paramFloatMin = func() float64 {
val, err := strconv.ParseFloat("-inf", 64)
if err != nil {
panic(err)
}
return val
}()
)
type paramFloat struct {
baseParameter
min float64
max float64
}
func (p paramFloat) Type() string {
return ParameterFloat
}
func (p paramFloat) Validate(_ context.Context, value string) error {
parsed, err := strconv.ParseFloat(value, 64)
switch {
case err != nil:
return fmt.Errorf("cannot parse float: %w", err)
case math.IsInf(parsed, 0), math.IsNaN(parsed):
return fmt.Errorf("%s is unacceptable float", value)
case parsed < p.min:
return fmt.Errorf("value is less than minimum %v", p.min)
case parsed > p.max:
return fmt.Errorf("value is more than maximum %v", p.max)
}
return nil
}
func NewFloat(description string, required bool, spec map[string]string) (Parameter, error) {
rValue := paramFloat{
baseParameter: baseParameter{
required: required,
description: description,
specification: spec,
},
min: paramFloatMin,
max: paramFloatMax,
}
if strValue, ok := spec["min"]; ok {
value, err := strconv.ParseFloat(strValue, 64)
if err != nil {
return nil, fmt.Errorf("cannot parse 'min' %s as float: %w", strValue, err)
}
if math.IsNaN(value) {
return nil, fmt.Errorf("cannot use %s as min", strValue)
}
rValue.min = value
}
if strValue, ok := spec["max"]; ok {
value, err := strconv.ParseFloat(strValue, 64)
if err != nil {
return nil, fmt.Errorf("cannot parse 'max' %s as float: %w", strValue, err)
}
if math.IsNaN(value) {
return nil, fmt.Errorf("cannot use %s as max", strValue)
}
rValue.max = value
}
if rValue.min > rValue.max {
return nil, fmt.Errorf("'max' %s value should be bigger than 'min' %s", spec["max"], spec["min"])
}
return rValue, nil
}