Skip to content

Commit

Permalink
pkg: add a verification on the pagebytes which must be > 0
Browse files Browse the repository at this point in the history
Signed-off-by: n00607095 <[email protected]>
  • Loading branch information
new-dream committed Aug 25, 2023
1 parent 6186538 commit 7b8de81
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pkg/ioutil/pagewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package ioutil

import (
"fmt"
"io"
)

Expand All @@ -41,6 +42,9 @@ type PageWriter struct {
// NewPageWriter creates a new PageWriter. pageBytes is the number of bytes
// to write per page. pageOffset is the starting offset of io.Writer.
func NewPageWriter(w io.Writer, pageBytes, pageOffset int) *PageWriter {
if pageBytes <= 0 {
panic(fmt.Sprintf("assertion failed: invalid pageBytes (%d) value, it must be greater than 0", pageBytes))
}
return &PageWriter{
w: w,
pageOffset: pageOffset,
Expand Down
41 changes: 41 additions & 0 deletions pkg/ioutil/pagewriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ package ioutil
import (
"math/rand"
"testing"

"github.com/stretchr/testify/assert"
)

func TestPageWriterRandom(t *testing.T) {
Expand Down Expand Up @@ -111,6 +113,45 @@ func TestPageWriterOffset(t *testing.T) {
}
}

func TestPageWriterPageBytes(t *testing.T) {
cases := []struct {
name string
pageBytes int
expectPanic bool
}{
{
name: "normal page bytes",
pageBytes: 4096,
expectPanic: false,
},
{
name: "negative page bytes",
pageBytes: -1,
expectPanic: true,
},
{
name: "zero page bytes",
pageBytes: 0,
expectPanic: true,
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
defaultBufferBytes = 1024
cw := &checkPageWriter{pageBytes: tc.pageBytes, t: t}
if tc.expectPanic {
assert.Panicsf(t, func() {
NewPageWriter(cw, tc.pageBytes, 0)
}, "expected panic when pageBytes is %d", tc.pageBytes)
} else {
pw := NewPageWriter(cw, tc.pageBytes, 0)
assert.NotEqual(t, pw, nil)
}
})
}
}

// checkPageWriter implements an io.Writer that fails a test on unaligned writes.
type checkPageWriter struct {
pageBytes int
Expand Down

0 comments on commit 7b8de81

Please sign in to comment.