Skip to content

Commit

Permalink
Merge pull request #31 from valyala/remove-mallocs-from-compress-deco…
Browse files Browse the repository at this point in the history
…mpress

Remove mallocs from Compress/Decompress
  • Loading branch information
Viq111 committed Mar 30, 2018
2 parents f300818 + f9cd78f commit aebefd9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
26 changes: 20 additions & 6 deletions zstd.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@ package zstd
/*
#define ZSTD_STATIC_LINKING_ONLY
#include "zstd.h"
#include "stdint.h" // for uintptr_t
// The following *_wrapper function are used for removing superflouos
// memory allocations when calling the wrapped functions from Go code.
// See https://github.com/golang/go/issues/24450 for details.
static size_t ZSTD_compress_wrapper(uintptr_t dst, size_t maxDstSize, const uintptr_t src, size_t srcSize, int compressionLevel) {
return ZSTD_compress((void*)dst, maxDstSize, (const void*)src, srcSize, compressionLevel);
}
static size_t ZSTD_decompress_wrapper(uintptr_t dst, size_t maxDstSize, uintptr_t src, size_t srcSize) {
return ZSTD_decompress((void*)dst, maxDstSize, (const void *)src, srcSize);
}
*/
import "C"
import (
Expand Down Expand Up @@ -61,10 +75,10 @@ func CompressLevel(dst, src []byte, level int) ([]byte, error) {
dst = make([]byte, bound)
}

cWritten := C.ZSTD_compress(
unsafe.Pointer(&dst[0]),
cWritten := C.ZSTD_compress_wrapper(
C.uintptr_t(uintptr(unsafe.Pointer(&dst[0]))),
C.size_t(len(dst)),
unsafe.Pointer(&src[0]),
C.uintptr_t(uintptr(unsafe.Pointer(&src[0]))),
C.size_t(len(src)),
C.int(level))

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

cWritten := C.ZSTD_decompress(
unsafe.Pointer(&dst[0]),
cWritten := C.ZSTD_decompress_wrapper(
C.uintptr_t(uintptr(unsafe.Pointer(&dst[0]))),
C.size_t(len(dst)),
unsafe.Pointer(&src[0]),
C.uintptr_t(uintptr(unsafe.Pointer(&src[0]))),
C.size_t(len(src)))

written := int(cWritten)
Expand Down
2 changes: 2 additions & 0 deletions zstd_stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ func BenchmarkStreamCompression(b *testing.B) {
if err != nil {
b.Fatalf("Failed writing to compress object: %s", err)
}
// Prevent from unbound buffer growth.
intermediate.Reset()
}
}

Expand Down

0 comments on commit aebefd9

Please sign in to comment.