fix: fixedpoint UnarshalJson on inf

This commit is contained in:
Raphanus Lo 2022-09-02 13:37:11 +08:00
parent 57d283726a
commit 750bdc82b5
2 changed files with 32 additions and 0 deletions

View File

@ -347,6 +347,7 @@ func NewFromString(input string) (Value, error) {
decimalCount := 0
// if is decimal, we don't need this
hasScientificNotion := false
hasIChar := false
scIndex := -1
for i, c := range input {
if hasDecimal {
@ -365,6 +366,10 @@ func NewFromString(input string) (Value, error) {
scIndex = i
break
}
if c == 'i' || c == 'I' {
hasIChar = true
break
}
}
if hasDecimal {
after := input[dotIndex+1:]
@ -395,6 +400,16 @@ func NewFromString(input string) (Value, error) {
return 0, err
}
return Value(int64(math.Trunc(v))), nil
} else if hasIChar {
if floatV, err := strconv.ParseFloat(input, 64); nil != err {
return 0, err
} else if math.IsInf(floatV, 1) {
return PosInf, nil
} else if math.IsInf(floatV, -1) {
return NegInf, nil
} else {
return 0, fmt.Errorf("fixedpoint.Value parse error, invalid input string %s", input)
}
} else {
v, err := strconv.ParseInt(input, 10, 64)
if err != nil {

View File

@ -138,6 +138,15 @@ func TestFromString(t *testing.T) {
assert.Equal(t, Zero, f)
f = MustNewFromString("")
assert.Equal(t, Zero, f)
for _, s := range []string{"inf", "Inf", "INF", "iNF"} {
f = MustNewFromString(s)
assert.Equal(t, PosInf, f)
f = MustNewFromString("+" + s)
assert.Equal(t, PosInf, f)
f = MustNewFromString("-" + s)
assert.Equal(t, NegInf, f)
}
}
func TestJson(t *testing.T) {
@ -177,6 +186,10 @@ func TestJson(t *testing.T) {
_ = json.Unmarshal([]byte("0.000062"), &q)
assert.Equal(t, "0.00006194", q.Sub(p).String())
assert.NoError(t, json.Unmarshal([]byte(`"inf"`), &p))
assert.NoError(t, json.Unmarshal([]byte(`"+Inf"`), &q))
assert.Equal(t, PosInf, p)
assert.Equal(t, p, q)
}
func TestYaml(t *testing.T) {
@ -216,6 +229,10 @@ func TestYaml(t *testing.T) {
_ = yaml.Unmarshal([]byte("0.000062"), &q)
assert.Equal(t, "0.00006194", q.Sub(p).String())
assert.NoError(t, json.Unmarshal([]byte(`"inf"`), &p))
assert.NoError(t, json.Unmarshal([]byte(`"+Inf"`), &q))
assert.Equal(t, PosInf, p)
assert.Equal(t, p, q)
}
func TestNumFractionalDigits(t *testing.T) {