From 2c1a9171c689c1fc87428d383ffeb823291f84cf Mon Sep 17 00:00:00 2001 From: Durran Jordan Date: Fri, 6 May 2022 14:51:32 -0400 Subject: [PATCH] feat(NODE-1837): support passing compression level --- index.d.ts | 2 +- src/lib.rs | 10 +++++++--- test/index.test.js | 33 ++++++++++++++++++++++++++++++--- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/index.d.ts b/index.d.ts index 51188c8..8d16577 100644 --- a/index.d.ts +++ b/index.d.ts @@ -3,5 +3,5 @@ /* auto-generated by NAPI-RS */ -export function compress(data: Buffer): Promise +export function compress(data: Buffer, level?: number | undefined | null): Promise export function decompress(data: Buffer): Promise diff --git a/src/lib.rs b/src/lib.rs index 6cf7426..6d3b134 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,8 +7,11 @@ use napi::{ }; use zstd::stream::{encode_all, decode_all}; +const DEFAULT_LEVEL: i32 = 3; + struct Encoder { - data: Ref + data: Ref, + level: i32 } #[napi] @@ -18,7 +21,7 @@ impl Task for Encoder { fn compute(&mut self) -> Result { let data: &[u8] = self.data.as_ref(); - encode_all(data, 3).map_err(|e| Error::new(Status::GenericFailure, format!("{}", e))) + encode_all(data, self.level).map_err(|e| Error::new(Status::GenericFailure, format!("{}", e))) } fn resolve(&mut self, env: Env, output: Self::Output) -> Result { @@ -56,9 +59,10 @@ impl Task for Decoder { } #[napi] -fn compress(data: JsBuffer) -> Result> { +fn compress(data: JsBuffer, level: Option) -> Result> { let encoder = Encoder { data: data.into_ref()?, + level: level.unwrap_or(DEFAULT_LEVEL) }; Ok(AsyncTask::new(encoder)) } diff --git a/test/index.test.js b/test/index.test.js index 753e871..781f005 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -5,9 +5,36 @@ describe('zstd', () => { describe('#compress', () => { const buffer = Buffer.from('test'); - it('returns a compressed buffer', async () => { - const result = await compress(buffer); - expect(await decompress(result)).to.deep.equal(buffer); + context('when not providing a compression level', () => { + it('returns a compressed buffer', async () => { + const result = await compress(buffer); + expect(await decompress(result)).to.deep.equal(buffer); + }); + }); + + context('when providing a compression level', () => { + context('when the level is valid', () => { + it('returns a compressed buffer', async () => { + const result = await compress(buffer, 1); + expect(await decompress(result)).to.deep.equal(buffer); + }); + }); + + context('when the level is invalid', () => { + context('when the level is too high', () => { + it('returns a compressed buffer', async () => { + const result = await compress(buffer, 100); + expect(await decompress(result)).to.deep.equal(buffer); + }); + }); + + context('when the level is too low', () => { + it('returns a compressed buffer', async () => { + const result = await compress(buffer, -100); + expect(await decompress(result)).to.deep.equal(buffer); + }); + }); + }); }); }); });