Skip to content

Commit

Permalink
fix normalizing numbers for 32-bit architecture
Browse files Browse the repository at this point in the history
  • Loading branch information
itchyny committed Jun 25, 2020
1 parent 6a205ef commit 6437200
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
4 changes: 3 additions & 1 deletion func.go
Original file line number Diff line number Diff line change
Expand Up @@ -1648,7 +1648,9 @@ func toInt(x interface{}) (int, bool) {
return int(x), true
case *big.Int:
if x.IsInt64() {
return int(x.Int64()), true
if i := x.Int64(); minInt <= i && i <= maxInt {
return int(i), true
}
}
if x.Sign() > 0 {
return maxInt, true
Expand Down
12 changes: 10 additions & 2 deletions normalize.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
func normalizeNumbers(v interface{}) interface{} {
switch v := v.(type) {
case json.Number:
if i, err := v.Int64(); err == nil {
if i, err := v.Int64(); err == nil && minInt <= i && i <= maxInt {
return int(i)
}
if strings.ContainsAny(string(v), ".eE") {
Expand All @@ -28,10 +28,15 @@ func normalizeNumbers(v interface{}) interface{} {
return math.MaxFloat64
case *big.Int:
if v.IsInt64() {
return int(v.Int64())
if i := v.Int64(); minInt <= i && i <= maxInt {
return int(i)
}
}
return v
case int64:
if v > int64(maxInt) {
return new(big.Int).SetUint64(uint64(v))
}
return int(v)
case int32:
return int(v)
Expand All @@ -50,6 +55,9 @@ func normalizeNumbers(v interface{}) interface{} {
}
return int(v)
case uint32:
if v > uint32(maxHalfInt) {
return new(big.Int).SetUint64(uint64(v))
}
return int(v)
case uint16:
return int(v)
Expand Down
11 changes: 7 additions & 4 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package gojq_test

import (
"context"
"encoding/json"
"fmt"
"log"
"math"
"math/big"
"testing"
"time"

Expand Down Expand Up @@ -60,15 +62,16 @@ func ExampleQuery_RunWithContext() {
// context deadline exceeded
}

func Test_Query_Run_numeric_types(t *testing.T) {
func TestQueryRun_NumericTypes(t *testing.T) {
query, err := gojq.Parse(".[] > 1")
if err != nil {
log.Fatalln(err)
}
iter := query.Run([]interface{}{
int64(2), int32(2), int16(2), int8(2),
uint64(2), uint32(2), uint16(2), uint8(2),
^uint(0), uint64(math.MaxUint64),
int64(2), int32(2), int16(2), int8(2), uint64(2), uint32(2), uint16(2), uint8(2),
^uint(0), int64(math.MaxInt64), uint64(math.MaxUint64), uint32(math.MaxUint32),
new(big.Int).SetUint64(math.MaxUint64), new(big.Int).SetUint64(math.MaxUint32),
json.Number(fmt.Sprint(uint64(math.MaxInt64))), json.Number(fmt.Sprint(uint64(math.MaxInt32))),
float64(2.0), float32(2.0),
})
for {
Expand Down

0 comments on commit 6437200

Please sign in to comment.