Skip to content

Commit

Permalink
Add gzipz package.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan Bertona committed Apr 1, 2022
1 parent c09ffbe commit 9257394
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
38 changes: 38 additions & 0 deletions gzipz/gzipz.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package gzipz

import (
"bytes"
"compress/gzip"
"io/ioutil"

"github.com/ibrt/golang-bites/internal"
)

// MustCompress implements in-memory GZIP compression.
func MustCompress(buf []byte) []byte {
cBuf := &bytes.Buffer{}
w, err := gzip.NewWriterLevel(cBuf, gzip.BestCompression)
internal.MaybePanic(err)
defer func() {
internal.MaybePanic(w.Close())
}()

_, err = w.Write(buf)
internal.MaybePanic(err)
internal.MaybePanic(w.Close())

return cBuf.Bytes()
}

// MustDecompress implements in-memory GZIP decompression.
func MustDecompress(buf []byte) []byte {
r, err := gzip.NewReader(bytes.NewReader(buf))
internal.MaybePanic(err)
defer func() {
internal.MaybePanic(r.Close())
}()

dBuf, err := ioutil.ReadAll(r)
internal.MaybePanic(err)
return dBuf
}
18 changes: 18 additions & 0 deletions gzipz/gzipz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package gzipz_test

import (
"strings"
"testing"

"github.com/stretchr/testify/require"

"github.com/ibrt/golang-bites/gzipz"
)

func TestCompress(t *testing.T) {
buf := []byte(strings.Repeat("x", 1000))
gBuf := gzipz.MustCompress(buf)
require.Less(t, len(gBuf), len(buf))
uBuf := gzipz.MustDecompress(gBuf)
require.Equal(t, buf, uBuf)
}

0 comments on commit 9257394

Please sign in to comment.