-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Ivan Bertona
committed
Apr 1, 2022
1 parent
c09ffbe
commit 9257394
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |