Skip to content

Commit aebefd9

Browse files
authored
Merge pull request #31 from valyala/remove-mallocs-from-compress-decompress
Remove mallocs from Compress/Decompress
2 parents f300818 + f9cd78f commit aebefd9

2 files changed

Lines changed: 22 additions & 6 deletions

File tree

zstd.go

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,20 @@ package zstd
33
/*
44
#define ZSTD_STATIC_LINKING_ONLY
55
#include "zstd.h"
6+
#include "stdint.h" // for uintptr_t
7+
8+
// The following *_wrapper function are used for removing superflouos
9+
// memory allocations when calling the wrapped functions from Go code.
10+
// See https://github.com/golang/go/issues/24450 for details.
11+
12+
static size_t ZSTD_compress_wrapper(uintptr_t dst, size_t maxDstSize, const uintptr_t src, size_t srcSize, int compressionLevel) {
13+
return ZSTD_compress((void*)dst, maxDstSize, (const void*)src, srcSize, compressionLevel);
14+
}
15+
16+
static size_t ZSTD_decompress_wrapper(uintptr_t dst, size_t maxDstSize, uintptr_t src, size_t srcSize) {
17+
return ZSTD_decompress((void*)dst, maxDstSize, (const void *)src, srcSize);
18+
}
19+
620
*/
721
import "C"
822
import (
@@ -61,10 +75,10 @@ func CompressLevel(dst, src []byte, level int) ([]byte, error) {
6175
dst = make([]byte, bound)
6276
}
6377

64-
cWritten := C.ZSTD_compress(
65-
unsafe.Pointer(&dst[0]),
78+
cWritten := C.ZSTD_compress_wrapper(
79+
C.uintptr_t(uintptr(unsafe.Pointer(&dst[0]))),
6680
C.size_t(len(dst)),
67-
unsafe.Pointer(&src[0]),
81+
C.uintptr_t(uintptr(unsafe.Pointer(&src[0]))),
6882
C.size_t(len(src)),
6983
C.int(level))
7084

@@ -82,10 +96,10 @@ func CompressLevel(dst, src []byte, level int) ([]byte, error) {
8296
func Decompress(dst, src []byte) ([]byte, error) {
8397
decompress := func(dst, src []byte) ([]byte, error) {
8498

85-
cWritten := C.ZSTD_decompress(
86-
unsafe.Pointer(&dst[0]),
99+
cWritten := C.ZSTD_decompress_wrapper(
100+
C.uintptr_t(uintptr(unsafe.Pointer(&dst[0]))),
87101
C.size_t(len(dst)),
88-
unsafe.Pointer(&src[0]),
102+
C.uintptr_t(uintptr(unsafe.Pointer(&src[0]))),
89103
C.size_t(len(src)))
90104

91105
written := int(cWritten)

zstd_stream_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ func BenchmarkStreamCompression(b *testing.B) {
141141
if err != nil {
142142
b.Fatalf("Failed writing to compress object: %s", err)
143143
}
144+
// Prevent from unbound buffer growth.
145+
intermediate.Reset()
144146
}
145147
}
146148

0 commit comments

Comments
 (0)