-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b624f18
commit 78c32f9
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
|
||
#include <napi.h> | ||
|
||
#include <vector> | ||
|
||
#include "zstd.h" | ||
|
||
using namespace Napi; | ||
|
||
CompressionResult compress(const std::vector<uint8_t> data, size_t compression_level) { | ||
size_t output_buffer_size = ZSTD_compressBound(data.size()); | ||
std::vector<uint8_t> output(output_buffer_size); | ||
|
||
size_t result_code = | ||
ZSTD_compress(output.data(), output.size(), data.data(), data.size(), compression_level); | ||
|
||
if (ZSTD_isError(result_code)) { | ||
std::string error(ZSTD_getErrorName(result_code)); | ||
return CompressionResult::Error(error); | ||
} | ||
|
||
output.resize(result_code); | ||
|
||
return CompressionResult::Ok(output); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
#include <napi.h> | ||
|
||
#include <vector> | ||
|
||
#include "zstd.h" | ||
|
||
using namespace Napi; | ||
|
||
CompressionResult decompress(const std::vector<uint8_t>& compressed) { | ||
std::vector<uint8_t> decompressed; | ||
|
||
using DCTX_Deleter = void (*)(ZSTD_DCtx*); | ||
|
||
std::unique_ptr<ZSTD_DCtx, DCTX_Deleter> decompression_context(ZSTD_createDCtx(), | ||
(DCTX_Deleter)ZSTD_freeDCtx); | ||
|
||
ZSTD_inBuffer input = {compressed.data(), compressed.size(), 0}; | ||
|
||
while (input.pos < input.size) { | ||
std::vector<uint8_t> chunk(ZSTD_DStreamOutSize()); | ||
ZSTD_outBuffer output = {chunk.data(), chunk.size(), 0}; | ||
size_t const ret = ZSTD_decompressStream(decompression_context.get(), &output, &input); | ||
if (ZSTD_isError(ret)) { | ||
std::string error(ZSTD_getErrorName(ret)); | ||
return CompressionResult::Error(error); | ||
} | ||
|
||
for (size_t i = 0; i < output.pos; ++i) { | ||
decompressed.push_back(chunk[i]); | ||
} | ||
} | ||
|
||
return CompressionResult::Ok(decompressed); | ||
} |