From ffab76a44ad99db0f709179d23575ffd66f5ca83 Mon Sep 17 00:00:00 2001 From: Ben Luddy Date: Mon, 10 Jun 2024 11:02:51 -0400 Subject: [PATCH] Fix panic using SortFastShuffle to encode a struct with no fields. Signed-off-by: Ben Luddy --- encode.go | 2 +- encode_test.go | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/encode.go b/encode.go index a977b7f..6508e29 100644 --- a/encode.go +++ b/encode.go @@ -1444,7 +1444,7 @@ func encodeStruct(e *bytes.Buffer, em *encMode, v reflect.Value) (err error) { flds := structType.getFields(em) start := 0 - if em.sort == SortFastShuffle { + if em.sort == SortFastShuffle && len(flds) > 0 { start = rand.Intn(len(flds)) //nolint:gosec // Don't need a CSPRNG for deck cutting. } diff --git a/encode_test.go b/encode_test.go index f2e25b8..3b22db9 100644 --- a/encode_test.go +++ b/encode_test.go @@ -4519,6 +4519,21 @@ func TestSortModeFastShuffle(t *testing.T) { } } +func TestSortModeFastShuffleEmptyStruct(t *testing.T) { + em, err := EncOptions{Sort: SortFastShuffle}.EncMode() + if err != nil { + t.Fatal(err) + } + + got, err := em.Marshal(struct{}{}) + if err != nil { + t.Fatal(err) + } + if want := []byte{0xa0}; !bytes.Equal(got, want) { + t.Errorf("got 0x%x, want 0x%x", got, want) + } +} + func TestInvalidByteSliceExpectedFormat(t *testing.T) { for _, tc := range []struct { name string