Skip to content

Commit

Permalink
combine allocation check logic
Browse files Browse the repository at this point in the history
  • Loading branch information
brianshih1 committed Apr 20, 2024
1 parent a505765 commit 180a476
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 13 deletions.
10 changes: 1 addition & 9 deletions codec_array.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,6 @@ type arrayDecoder struct {
decoder ValDecoder
}

// Max allocation size for an array due to the limit in number of bits in a heap address:
// https://github.com/golang/go/blob/7f76c00fc5678fa782708ba8fece63750cb89d03/src/runtime/malloc.go#L183
var maxAllocSize = uint64(1 << 48)

func (d *arrayDecoder) Decode(ptr unsafe.Pointer, r *Reader) {
var size int
sliceType := d.typ
Expand All @@ -55,12 +51,8 @@ func (d *arrayDecoder) Decode(ptr unsafe.Pointer, r *Reader) {

start := size
size += int(l)
if size > int(maxAllocSize) {
r.ReportError("decode array", "size exceeded max allocation size")
return
}

if max := r.cfg.getMaxSliceAllocSize(); max > 0 && size > max {
if size > r.cfg.getMaxSliceAllocSize() {
r.ReportError("decode array", "size is greater than `Config.MaxSliceAllocSize`")
return
}
Expand Down
13 changes: 9 additions & 4 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ type Config struct {
// If this size is exceeded, the Reader returns an error. This can be disabled by setting a negative number.
MaxByteSliceSize int

// MaxSliceAllocSize is the maximum size that the decoder will allocate, disabled by default.
// If this size is exceeded, the decoder returns an error. This can be disabled by setting a negative number.
// MaxSliceAllocSize is the maximum size that the decoder will allocate, set to the max heap
// allocation size by default.
// If this size is exceeded, the decoder returns an error.
MaxSliceAllocSize int
}

Expand Down Expand Up @@ -274,10 +275,14 @@ func (c *frozenConfig) getMaxByteSliceSize() int {
return size
}

// Max allocation size for an array due to the limit in number of bits in a heap address:
// https://github.com/golang/go/blob/7f76c00fc5678fa782708ba8fece63750cb89d03/src/runtime/malloc.go#L183
var maxAllocSize = int(1 << 48)

func (c *frozenConfig) getMaxSliceAllocSize() int {
size := c.config.MaxSliceAllocSize
if size == 0 {
return defaultMaxSliceAllocSize
if size > maxAllocSize || size <= 0 {
return maxAllocSize
}
return size
}

0 comments on commit 180a476

Please sign in to comment.