simonmittag/jabba

View on GitHub
gzip.go

Summary

Maintainability
A
1 hr
Test Coverage
A
100%
package j8a

import (
    "bytes"
    "github.com/klauspost/compress/gzip"
    "io/ioutil"
    "sync"
)

const gzipLevel int = 1

var gzipMagicBytes = []byte{0x1f, 0x8b}
var gzipSmall = []byte{31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 170, 174, 5, 4, 0, 0, 255, 255, 67, 191, 166, 163, 2, 0, 0, 0}

var zipPool = sync.Pool{
    New: func() interface{} {
        var buf bytes.Buffer
        w, _ := gzip.NewWriterLevel(&buf, gzipLevel)
        return w
    },
}

var unzipPool = sync.Pool{
    New: func() interface{} {
        buf := bytes.NewBuffer(gzipSmall)
        r, _ := gzip.NewReader(buf)
        return r
    },
}

// Gzip a []byte
func Gzip(input []byte) *[]byte {
    wrt, _ := zipPool.Get().(*gzip.Writer)
    buf := &bytes.Buffer{}
    wrt.Reset(buf)

    _, _ = wrt.Write(input)
    _ = wrt.Close()
    defer zipPool.Put(wrt)

    enc := buf.Bytes()
    return &enc
}

// Gunzip a []byte
func Gunzip(input []byte) *[]byte {
    rd, _ := unzipPool.Get().(*gzip.Reader)
    buf := bytes.NewBuffer(input)
    _ = rd.Reset(buf)

    dec, _ := ioutil.ReadAll(rd)
    _ = rd.Close()
    defer unzipPool.Put(rd)

    return &dec
}