Skip to content

Commit 253ab41

Browse files
authored
Merge pull request #2077 from CortexFoundation/dev
common: using `ParseUint` instead of `ParseInt`
2 parents 31652fe + a68ff57 commit 253ab41

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

common/types.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,7 @@ func (d *Decimal) UnmarshalJSON(input []byte) error {
456456
if !isString(input) {
457457
return &json.UnmarshalTypeError{Value: "non-string", Type: reflect.TypeOf(uint64(0))}
458458
}
459-
if i, err := strconv.ParseInt(string(input[1:len(input)-1]), 10, 64); err == nil {
459+
if i, err := strconv.ParseUint(string(input[1:len(input)-1]), 10, 64); err == nil {
460460
*d = Decimal(i)
461461
return nil
462462
} else {

common/types_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"database/sql/driver"
2222
"encoding/json"
2323
"fmt"
24+
"math"
2425
"math/big"
2526
"reflect"
2627
"strings"
@@ -598,3 +599,29 @@ func BenchmarkPrettyDuration(b *testing.B) {
598599
}
599600
b.Logf("Post %s", a)
600601
}
602+
603+
func TestDecimalUnmarshalJSON(t *testing.T) {
604+
// These should error
605+
for _, tc := range []string{``, `"`, `""`, `"-1"`} {
606+
if err := new(Decimal).UnmarshalJSON([]byte(tc)); err == nil {
607+
t.Errorf("input %s should cause error", tc)
608+
}
609+
}
610+
// These should succeed
611+
for _, tc := range []struct {
612+
input string
613+
want uint64
614+
}{
615+
{`"0"`, 0},
616+
{`"9223372036854775807"`, math.MaxInt64},
617+
{`"18446744073709551615"`, math.MaxUint64},
618+
} {
619+
have := new(Decimal)
620+
if err := have.UnmarshalJSON([]byte(tc.input)); err != nil {
621+
t.Errorf("input %q triggered error: %v", tc.input, err)
622+
}
623+
if uint64(*have) != tc.want {
624+
t.Errorf("input %q, have %d want %d", tc.input, *have, tc.want)
625+
}
626+
}
627+
}

0 commit comments

Comments
 (0)