Skip to content

Commit

Permalink
Fix panic using SortFastShuffle to encode a struct with no fields.
Browse files Browse the repository at this point in the history
Signed-off-by: Ben Luddy <bluddy@redhat.com>
  • Loading branch information
benluddy committed Jun 10, 2024
1 parent 878cfef commit ffab76a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
}

Expand Down
15 changes: 15 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit ffab76a

Please sign in to comment.