fix(decode): overflow-check uint and float32 destinations

Assisted-by: GLM 5.3
This commit is contained in:
2026-09-17 23:10:24 +02:00
parent 30b28fe7fc
commit c485aab227
4 changed files with 51 additions and 18 deletions
+14 -12
View File
@@ -5,7 +5,6 @@ package interpres
import (
"fmt"
"math"
"reflect"
"slices"
"strings"
@@ -205,21 +204,21 @@ func setInt(dst reflect.Value, v int64) error {
if v < 0 {
return fmt.Errorf("interpres: cannot assign negative %d to %s", v, dst.Type())
}
var max uint64
switch dst.Kind() {
case reflect.Uint8:
max = math.MaxUint8
case reflect.Uint16:
max = math.MaxUint16
case reflect.Uint32:
max = math.MaxUint32
}
if max != 0 && uint64(v) > max {
// OverflowUint knows every width, uint included on platforms where it
// is narrower than uint64; SetUint would silently truncate instead.
if dst.OverflowUint(uint64(v)) {
return fmt.Errorf("interpres: integer %d overflows %s", v, dst.Type())
}
dst.SetUint(uint64(v))
case reflect.Float32, reflect.Float64:
dst.SetFloat(float64(v))
// A finite value beyond the float32 range would silently become ±Inf;
// infinities and NaN themselves pass through. An int64 never
// overflows either float width.
f := float64(v)
if dst.OverflowFloat(f) {
return fmt.Errorf("interpres: integer %d overflows %s", v, dst.Type())
}
dst.SetFloat(f)
default:
return fmt.Errorf("interpres: cannot assign integer to %s", dst.Type())
}
@@ -229,6 +228,9 @@ func setInt(dst reflect.Value, v int64) error {
func setFloat(dst reflect.Value, v float64) error {
switch dst.Kind() {
case reflect.Float32, reflect.Float64:
if dst.OverflowFloat(v) {
return fmt.Errorf("interpres: float %g overflows %s", v, dst.Type())
}
dst.SetFloat(v)
return nil
default: