-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompression.go
More file actions
58 lines (47 loc) · 1.28 KB
/
compression.go
File metadata and controls
58 lines (47 loc) · 1.28 KB
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
package codec
import (
"bytes"
"compress/lzw"
"fmt"
)
var (
// compression is the map containing all the
// available compression functions by their identifiers.
compression = map[CompressionAlgorithm]func([]byte) ([]byte, error){
CompressionAlgorithmLZWOrderLSBLitWidth8: CompressLZWOrderLSBLitWidth8,
}
)
// Compress compresses the given data using
// the consented compression function.
func Compress(in []byte) ([]byte, error) {
compressionAlgorithm, ok := compression[CompressionAlgorithmLZWOrderLSBLitWidth8]
if !ok {
return nil, fmt.Errorf(
"compression algorithm '%s' not found",
ConsentedCompressionAlgorithm)
}
return compressionAlgorithm(in)
}
// CompressLZWOrderLSBLitWidth8 uses the
// LZWOrderLSBLitWidth8 compression algorithm
// to compress the given data.
func CompressLZWOrderLSBLitWidth8(in []byte) ([]byte, error) {
var buffer bytes.Buffer
writer := lzw.NewWriter(&buffer, lzw.LSB, 8)
total := 0
var written int
var err error
for written, err = writer.Write(in[total:]); written > 0 && err == nil; written, err = writer.Write(in[total:]) {
total += written
}
if err != nil {
return nil, err
}
// It seems it's not okay to
// defer the Close() call here.
err = writer.Close()
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}