Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions key.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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
}

Expand Down
57 changes: 57 additions & 0 deletions key_native_int_test.go
Original file line number Diff line number Diff line change
@@ -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)
}