github.com/vicanso/pike@v1.0.1-0.20210630235453-9099e041f6ec/compress/brotli.go (about) 1 // MIT License 2 3 // Copyright (c) 2020 Tree Xie 4 5 // Permission is hereby granted, free of charge, to any person obtaining a copy 6 // of this software and associated documentation files (the "Software"), to deal 7 // in the Software without restriction, including without limitation the rights 8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 // copies of the Software, and to permit persons to whom the Software is 10 // furnished to do so, subject to the following conditions: 11 12 // The above copyright notice and this permission notice shall be included in all 13 // copies or substantial portions of the Software. 14 15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 // SOFTWARE. 22 23 package compress 24 25 import ( 26 "bytes" 27 "io/ioutil" 28 29 "github.com/andybalholm/brotli" 30 ) 31 32 const ( 33 defaultBrQuality = 6 34 ) 35 36 func brotliEncode(buf []byte, level int) (*bytes.Buffer, error) { 37 buffer := new(bytes.Buffer) 38 if level <= 0 || level > 11 { 39 level = defaultBrQuality 40 } 41 w := brotli.NewWriterLevel(buffer, level) 42 defer w.Close() 43 _, err := w.Write(buf) 44 if err != nil { 45 return nil, err 46 } 47 return buffer, nil 48 } 49 50 // doBrotli brotli compress 51 func doBrotli(buf []byte, level int) ([]byte, error) { 52 buffer, err := brotliEncode(buf, level) 53 if err != nil { 54 return nil, err 55 } 56 return buffer.Bytes(), nil 57 } 58 59 // doBrotliDecode brotli decode 60 func doBrotliDecode(buf []byte) ([]byte, error) { 61 if len(buf) == 0 { 62 return nil, nil 63 } 64 r := brotli.NewReader(bytes.NewBuffer(buf)) 65 return ioutil.ReadAll(r) 66 }