From 5b0203fbd3cdd375e80ced58f1f6973b48ed1d6f Mon Sep 17 00:00:00 2001 From: luke Date: Thu, 10 Mar 2022 01:34:15 +0000 Subject: [PATCH] check writer level when use NewWriterLevel Signed-off-by: luke --- brotli_test.go | 6 +++--- writer.go | 11 ++++++++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/brotli_test.go b/brotli_test.go index 3392a94..5d53b5b 100644 --- a/brotli_test.go +++ b/brotli_test.go @@ -484,7 +484,7 @@ func BenchmarkEncodeLevels(b *testing.B) { b.ReportAllocs() b.SetBytes(int64(len(opticks))) for i := 0; i < b.N; i++ { - w := NewWriterLevel(ioutil.Discard, level) + w, _ := NewWriterLevel(ioutil.Discard, level) w.Write(opticks) w.Close() } @@ -500,7 +500,7 @@ func BenchmarkEncodeLevelsReset(b *testing.B) { for level := BestSpeed; level <= BestCompression; level++ { buf := new(bytes.Buffer) - w := NewWriterLevel(buf, level) + w, _ := NewWriterLevel(buf, level) w.Write(opticks) w.Close() b.Run(fmt.Sprintf("%d", level), func(b *testing.B) { @@ -524,7 +524,7 @@ func BenchmarkDecodeLevels(b *testing.B) { for level := BestSpeed; level <= BestCompression; level++ { buf := new(bytes.Buffer) - w := NewWriterLevel(buf, level) + w, _ := NewWriterLevel(buf, level) w.Write(opticks) w.Close() compressed := buf.Bytes() diff --git a/writer.go b/writer.go index 39feaef..0881468 100644 --- a/writer.go +++ b/writer.go @@ -2,6 +2,7 @@ package brotli import ( "errors" + "fmt" "io" ) @@ -30,17 +31,21 @@ var ( // It is the caller's responsibility to call Close on the Writer when done. // Writes may be buffered and not flushed until Close. func NewWriter(dst io.Writer) *Writer { - return NewWriterLevel(dst, DefaultCompression) + b, _ := NewWriterLevel(dst, DefaultCompression) + return b } // NewWriterLevel is like NewWriter but specifies the compression level instead // of assuming DefaultCompression. // The compression level can be DefaultCompression or any integer value between // BestSpeed and BestCompression inclusive. -func NewWriterLevel(dst io.Writer, level int) *Writer { +func NewWriterLevel(dst io.Writer, level int) (*Writer, error) { + if level < BestSpeed || level > BestCompression { + return nil, fmt.Errorf("brotli: invalid compression level: %d", level) + } return NewWriterOptions(dst, WriterOptions{ Quality: level, - }) + }), nil } // NewWriterOptions is like NewWriter but specifies WriterOptions