Skip to content

Commit

Permalink
works
Browse files Browse the repository at this point in the history
  • Loading branch information
baileympearson committed Nov 14, 2024
1 parent b624f18 commit 78c32f9
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
25 changes: 25 additions & 0 deletions addon/compress.h
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);
}
34 changes: 34 additions & 0 deletions addon/decompress.h
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);
}

0 comments on commit 78c32f9

Please sign in to comment.