Skip to content

Commit

Permalink
Merge pull request #2077 from CortexFoundation/dev
Browse files Browse the repository at this point in the history
common: using `ParseUint` instead of `ParseInt`
  • Loading branch information
ucwong committed Jun 25, 2024
2 parents 31652fe + a68ff57 commit 253ab41
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion common/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ func (d *Decimal) UnmarshalJSON(input []byte) error {
if !isString(input) {
return &json.UnmarshalTypeError{Value: "non-string", Type: reflect.TypeOf(uint64(0))}
}
if i, err := strconv.ParseInt(string(input[1:len(input)-1]), 10, 64); err == nil {
if i, err := strconv.ParseUint(string(input[1:len(input)-1]), 10, 64); err == nil {
*d = Decimal(i)
return nil
} else {
Expand Down
27 changes: 27 additions & 0 deletions common/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"database/sql/driver"
"encoding/json"
"fmt"
"math"
"math/big"
"reflect"
"strings"
Expand Down Expand Up @@ -598,3 +599,29 @@ func BenchmarkPrettyDuration(b *testing.B) {
}
b.Logf("Post %s", a)
}

func TestDecimalUnmarshalJSON(t *testing.T) {
// These should error
for _, tc := range []string{``, `"`, `""`, `"-1"`} {
if err := new(Decimal).UnmarshalJSON([]byte(tc)); err == nil {
t.Errorf("input %s should cause error", tc)
}
}
// These should succeed
for _, tc := range []struct {
input string
want uint64
}{
{`"0"`, 0},
{`"9223372036854775807"`, math.MaxInt64},
{`"18446744073709551615"`, math.MaxUint64},
} {
have := new(Decimal)
if err := have.UnmarshalJSON([]byte(tc.input)); err != nil {
t.Errorf("input %q triggered error: %v", tc.input, err)
}
if uint64(*have) != tc.want {
t.Errorf("input %q, have %d want %d", tc.input, *have, tc.want)
}
}
}

0 comments on commit 253ab41

Please sign in to comment.