From 1891d01a6f555287012d65944404656d2d64ea66 Mon Sep 17 00:00:00 2001 From: Martin Tournoij Date: Thu, 23 Sep 2021 14:40:54 +0800 Subject: [PATCH] Fix nested structs on 32bit archs Not entirely sure why this fails, but this fixes it in the meanwhile. Fixes #314 --- encode.go | 12 +++++++++++- encode_test.go | 17 +++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/encode.go b/encode.go index 10d88ac6..b7edd78f 100644 --- a/encode.go +++ b/encode.go @@ -411,7 +411,17 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { if typeIsHash(tomlTypeOfGo(frv)) { fieldsSub = append(fieldsSub, append(start, f.Index...)) } else { - fieldsDirect = append(fieldsDirect, append(start, f.Index...)) + // Copy so it works correct on 32bit archs; not clear why this + // is needed. See #314, and https://www.reddit.com/r/golang/comments/pnx8v4 + // This also works fine on 64bit, but 32bit archs are somewhat + // rare and this is a wee bit faster. + if math.MaxInt == math.MaxInt32 { + copyStart := make([]int, len(start)) + copy(copyStart, start) + fieldsDirect = append(fieldsDirect, append(copyStart, f.Index...)) + } else { + fieldsDirect = append(fieldsDirect, append(start, f.Index...)) + } } } } diff --git a/encode_test.go b/encode_test.go index 2d95662f..02bcef20 100644 --- a/encode_test.go +++ b/encode_test.go @@ -396,6 +396,21 @@ Fun = "why would you do this?" } } +// Would previously fail on 32bit architectures; can test with: +// GOARCH=386 go test -c && ./toml.test +// GOARCH=arm GOARM=7 go test -c && qemu-arm ./toml.test +func TestEncode32bit(t *testing.T) { + type Inner struct { + A, B, C string + } + type Outer struct{ Inner } + + encodeExpected(t, "embedded anonymous untagged struct", + Outer{Inner{"a", "b", "c"}}, + "A = \"a\"\nB = \"b\"\nC = \"c\"\n", + nil) +} + func encodeExpected(t *testing.T, label string, val interface{}, want string, wantErr error) { t.Helper() @@ -420,8 +435,6 @@ func encodeExpected(t *testing.T, label string, val interface{}, want string, wa want = strings.TrimSpace(want) if want != have { t.Errorf("\nhave:\n%s\nwant:\n%s\n", have, want) - // v, _ := json.MarshalIndent(val, "", " ") - // t.Log(string(v)) } }) }