-
Notifications
You must be signed in to change notification settings - Fork 13
/
compression.go
73 lines (61 loc) · 2.04 KB
/
compression.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright (c) 2022 Target Brands, Inc. All rights reserved.
//
// Use of this source code is governed by the LICENSE file in this repository.
package database
import (
"bytes"
"compress/zlib"
"io"
)
// compress is a helper function to compress values. First, an
// empty buffer is created for storing compressed data. Then,
// a zlib writer, using the DEFLATE algorithm, is created with
// the provided compression level to output to this buffer.
// Finally, the provided value is compressed and written to the
// buffer and the writer is closed which flushes all bytes from
// the writer to the buffer.
func compress(level int, value []byte) ([]byte, error) {
// create new buffer for storing compressed data
b := new(bytes.Buffer)
// create new zlib writer for outputting data to the buffer in a compressed format
w, err := zlib.NewWriterLevel(b, level)
if err != nil {
return value, err
}
// write data to the buffer in compressed format
_, err = w.Write(value)
if err != nil {
return value, err
}
// close the writer
//
// compressed bytes are not flushed until the writer is closed or explicitly flushed
err = w.Close()
if err != nil {
return value, err
}
// return compressed bytes from the buffer
return b.Bytes(), nil
}
// decompress is a helper function to decompress values. First, a
// buffer is created from the provided compressed data. Then, a
// zlib reader, using the DEFLATE algorithm, is created from the
// buffer as an input for reading data from the buffer. Finally,
// the data is decompressed and read from the buffer.
func decompress(value []byte) ([]byte, error) {
// create new buffer from the compressed data
b := bytes.NewBuffer(value)
// create new zlib reader for reading the compressed data from the buffer
r, err := zlib.NewReader(b)
if err != nil {
return value, err
}
// close the reader after the data has been decompressed
defer r.Close()
// capture decompressed data from the compressed data in the buffer
data, err := io.ReadAll(r)
if err != nil {
return value, err
}
return data, nil
}