Skip to content

Commit

Permalink
push
Browse files Browse the repository at this point in the history
  • Loading branch information
baileympearson committed Nov 14, 2024
1 parent 5a9c863 commit 5340712
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
33 changes: 21 additions & 12 deletions addon/decompressor.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,34 @@

using namespace Napi;

using DCTX_Deleter = void (*)(ZSTD_DCtx*);

struct Decompressor {
std::vector<uint8_t> data;
size_t buffer_size;

Decompressor(std::vector<uint8_t> data, size_t buffer_size)
: data(data), buffer_size(buffer_size) {}
Decompressor(std::vector<uint8_t> data) : data(data) {}

CompressionResult operator()() {
std::vector<uint8_t> decompressed(buffer_size);
std::vector<uint8_t> decompressed;

size_t _result =
ZSTD_decompress(decompressed.data(), decompressed.size(), data.data(), data.size());
std::unique_ptr<ZSTD_DCtx, DCTX_Deleter> decompression_context(ZSTD_createDCtx(),
(DCTX_Deleter)ZSTD_freeDCtx);

if (ZSTD_isError(_result)) {
std::string error(ZSTD_getErrorName(_result));
return CompressionResult::Error(error);
}
ZSTD_inBuffer input = {data.data(), data.size(), 0};

decompressed.resize(_result);
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);
}
Expand All @@ -36,6 +45,6 @@ struct Decompressor {
std::vector<uint8_t> data(total);
std::copy(input_data, input_data + total, data.data());

return Decompressor(data, total * 1000);
return Decompressor(data);
}
};
4 changes: 4 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ describe('compress', function () {
test('compress() returns a Nodejs buffer', async function () {
expect(await compress(Buffer.from([1, 2, 3]))).to.be.instanceOf(Buffer);
});

test('decompress() with empty buffer', async function () {
expect(await decompress(Buffer.from([]))).to.deep.equal(Buffer.from([]))
})
});

/**
Expand Down

0 comments on commit 5340712

Please sign in to comment.