From 5f05e27227eeb2431e67f69dacf4738f164d3a58 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Wed, 25 Nov 2026 00:03:21 +0800 Subject: [PATCH] Check native integer width before converting key values --- key.go | 4 +-- key_native_int_test.go | 57 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 key_native_int_test.go diff --git a/key.go b/key.go index 9ec0fb3..921eb3f 100644 --- a/key.go +++ b/key.go @@ -298,7 +298,7 @@ func (k *Key) Float64() (float64, error) { // Int returns int type value. func (k *Key) Int() (int, error) { - v, err := strconv.ParseInt(k.String(), 0, 64) + v, err := strconv.ParseInt(k.String(), 0, strconv.IntSize) return int(v), err } @@ -309,7 +309,7 @@ func (k *Key) Int64() (int64, error) { // Uint returns uint type valued. func (k *Key) Uint() (uint, error) { - u, e := strconv.ParseUint(k.String(), 0, 64) + u, e := strconv.ParseUint(k.String(), 0, strconv.IntSize) return uint(u), e } diff --git a/key_native_int_test.go b/key_native_int_test.go new file mode 100644 index 0000000..9866877 --- /dev/null +++ b/key_native_int_test.go @@ -0,0 +1,57 @@ +package ini + +import ( + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestKey_NativeIntegerOverflow(t *testing.T) { + aboveInt := "9223372036854775808" + belowInt := "-9223372036854775809" + aboveUint := "18446744073709551616" + if strconv.IntSize == 32 { + aboveInt = "2147483648" + belowInt = "-2147483649" + aboveUint = "4294967296" + } + key := Empty().Section("").Key("size") + for _, value := range []string{aboveInt, belowInt} { + t.Run(value, func(t *testing.T) { + key.SetValue(value) + _, err := key.Int() + assert.ErrorIs(t, err, strconv.ErrRange) + assert.Equal(t, 7, key.MustInt(7)) + if strconv.IntSize == 32 { + _, err := key.Int64() + assert.NoError(t, err, "the value still fits an explicit int64") + } + }) + } + key.SetValue(aboveUint) + _, err := key.Uint() + assert.ErrorIs(t, err, strconv.ErrRange) + assert.Equal(t, uint(7), key.MustUint(7)) + if strconv.IntSize == 32 { + _, err := key.Uint64() + assert.NoError(t, err, "the value still fits an explicit uint64") + } +} + +func TestKey_NativeIntegerLimits(t *testing.T) { + key := Empty().Section("").Key("size") + maxInt := int(^uint(0) >> 1) + for _, want := range []int{0, maxInt, -maxInt - 1} { + key.SetValue(strconv.FormatInt(int64(want), 10)) + got, err := key.Int() + require.NoError(t, err) + assert.Equal(t, want, got) + } + maxUint := ^uint(0) + key.SetValue(strconv.FormatUint(uint64(maxUint), 10)) + got, err := key.Uint() + require.NoError(t, err) + assert.Equal(t, maxUint, got) +}