-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
mozlz4.go
80 lines (65 loc) · 1.61 KB
/
mozlz4.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
74
75
76
77
78
79
80
package main
import (
"bytes"
"encoding/binary"
"io"
"os"
"github.com/pierrec/lz4/v3"
"github.com/pkg/errors"
)
const (
mozLz4Header = "mozLz40\x00"
)
func mozLz4Decompress(filename string) ([]byte, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
header := make([]byte, len(mozLz4Header))
_, err = file.Read(header)
if err != nil {
return nil, errors.Wrap(err, "couldn't read header")
}
if string(header) != mozLz4Header {
return nil, errors.New("no mozLz4 header")
}
var size uint32
err = binary.Read(file, binary.LittleEndian, &size)
if err != nil {
return nil, errors.Wrap(err, "couldn't read size")
}
src, err := io.ReadAll(file)
if err != nil {
return nil, errors.Wrap(err, "couldn't read compressed data")
}
out := make([]byte, size)
_, err = lz4.UncompressBlock(src, out)
if err != nil {
return nil, errors.Wrap(err, "couldn't decompress data")
}
return out, nil
}
func mozLz4Compress(src []byte) ([]byte, error) {
out := new(bytes.Buffer)
_, err := out.Write([]byte(mozLz4Header))
if err != nil {
return nil, errors.Wrap(err, "couldn't write header")
}
err = binary.Write(out, binary.LittleEndian, uint32(len(src)))
if err != nil {
return nil, errors.Wrap(err, "couldn't encode length")
}
buf := make([]byte, 10*len(src))
sz, err := lz4.CompressBlockHC(src, buf, -1)
if err != nil {
return nil, errors.Wrap(err, "couldn't compress data")
}
if sz == 0 {
return nil, errors.New("data incompressible")
}
_, err = out.Write(buf[:sz])
if err != nil {
return nil, errors.Wrap(err, "couldn't write compressed data")
}
return out.Bytes(), nil
}