forked from cloudflare/golz4
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lz4.go
55 lines (47 loc) · 1.46 KB
/
lz4.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
package lz4
// #cgo CFLAGS: -O3
// #include "src/lz4.h"
// #include "src/lz4.c"
import "C"
import (
"errors"
"fmt"
"unsafe"
)
// p gets a char pointer to the first byte of a []byte slice
func p(in []byte) *C.char {
if len(in) == 0 {
return (*C.char)(unsafe.Pointer(nil))
}
return (*C.char)(unsafe.Pointer(&in[0]))
}
// clen gets the length of a []byte slice as a char *
func clen(s []byte) C.int {
return C.int(len(s))
}
// Uncompress with a known output size. len(out) should be equal to
// the length of the uncompressed out.
func Uncompress(in, out []byte) (error) {
if int(C.LZ4_decompress_safe(p(in), p(out), clen(in), clen(out))) < 0 {
return errors.New("Malformed compression stream")
}
return nil
}
// CompressBound calculates the size of the output buffer needed by
// Compress. This is based on the following macro:
//
// #define LZ4_COMPRESSBOUND(isize)
// ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
func CompressBound(in []byte) int {
return len(in) + ((len(in) / 255) + 16)
}
// Compress compresses in and puts the content in out. len(out)
// should have enough space for the compressed data (use CompressBound
// to calculate). Returns the number of bytes in the out slice.
func Compress(in, out []byte) (outSize int, err error) {
outSize = int(C.LZ4_compress_limitedOutput(p(in), p(out), clen(in), clen(out)))
if outSize == 0 {
err = fmt.Errorf("insufficient space for compression")
}
return
}