From 9f5726004ef124b8d3a4844c90c8700ba20d154e Mon Sep 17 00:00:00 2001 From: Marty <58218546+PotatoesFall@users.noreply.github.com> Date: Thu, 9 Feb 2023 18:02:25 +0100 Subject: [PATCH] Allow integers to be unmarshaled into floats (#841) Co-authored-by: Marty --- fast_test.go | 9 ++++++++- internal/imported_tests/unmarshal_imported_test.go | 4 ---- unmarshaler.go | 7 ++++++- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/fast_test.go b/fast_test.go index 02910bb..14d1def 100644 --- a/fast_test.go +++ b/fast_test.go @@ -7,13 +7,20 @@ import ( "github.com/stretchr/testify/require" ) -func TestFastSimple(t *testing.T) { +func TestFastSimpleInt(t *testing.T) { m := map[string]int64{} err := toml.Unmarshal([]byte(`a = 42`), &m) require.NoError(t, err) require.Equal(t, map[string]int64{"a": 42}, m) } +func TestFastSimpleFloat(t *testing.T) { + m := map[string]float64{} + err := toml.Unmarshal([]byte("a = 42\nb = 1.1\nc = 12341234123412341234123412341234"), &m) + require.NoError(t, err) + require.Equal(t, map[string]float64{"a": 42, "b": 1.1, "c": 1.2341234123412342e+31}, m) +} + func TestFastSimpleString(t *testing.T) { m := map[string]string{} err := toml.Unmarshal([]byte(`a = "hello"`), &m) diff --git a/internal/imported_tests/unmarshal_imported_test.go b/internal/imported_tests/unmarshal_imported_test.go index 7a396e2..ead9bfb 100644 --- a/internal/imported_tests/unmarshal_imported_test.go +++ b/internal/imported_tests/unmarshal_imported_test.go @@ -1085,10 +1085,6 @@ func TestUnmarshalCheckConversionFloatInt(t *testing.T) { desc: "int", input: `I = 1e300`, }, - { - desc: "float", - input: `F = 9223372036854775806`, - }, } for _, test := range testCases { diff --git a/unmarshaler.go b/unmarshaler.go index 70f6ec5..25ec05f 100644 --- a/unmarshaler.go +++ b/unmarshaler.go @@ -887,6 +887,11 @@ func init() { } func (d *decoder) unmarshalInteger(value *unstable.Node, v reflect.Value) error { + kind := v.Kind() + if kind == reflect.Float32 || kind == reflect.Float64 { + return d.unmarshalFloat(value, v) + } + i, err := parseInteger(value.Data) if err != nil { return err @@ -894,7 +899,7 @@ func (d *decoder) unmarshalInteger(value *unstable.Node, v reflect.Value) error var r reflect.Value - switch v.Kind() { + switch kind { case reflect.Int64: v.SetInt(i) return nil