Fix panic using SortFastShuffle to encode a struct with no fields.

Signed-off-by: Ben Luddy <bluddy@redhat.com>
This commit is contained in:
Ben Luddy 2024-06-10 11:02:51 -04:00
parent 878cfefeff
commit ffab76a44a
No known key found for this signature in database
GPG Key ID: A6551E73A5974C30
2 changed files with 16 additions and 1 deletions

View File

@ -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.
}

View File

@ -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