limit up-front allocation when reading bytes

Fixes #73
This commit is contained in:
David Howden
2020-08-29 07:40:07 +10:00
parent 5d76b8eaae
commit 46e57f75db
2 changed files with 52 additions and 0 deletions
+12
View File
@@ -5,6 +5,7 @@
package tag
import (
"bytes"
"encoding/binary"
"io"
)
@@ -40,7 +41,18 @@ func readUint64LittleEndian(r io.Reader) (uint64, error) {
return binary.LittleEndian.Uint64(b), nil
}
// readBytesMaxUpfront is the max up-front allocation allowed
const readBytesMaxUpfront = 10 << 20 // 10MB
func readBytes(r io.Reader, n uint) ([]byte, error) {
if n > readBytesMaxUpfront {
b := &bytes.Buffer{}
if _, err := io.CopyN(b, r, int64(n)); err != nil {
return nil, err
}
return b.Bytes(), nil
}
b := make([]byte, n)
_, err := io.ReadFull(r, b)
if err != nil {