|
1 | 1 | #[macro_use]
|
2 | 2 | extern crate napi_derive;
|
3 | 3 |
|
4 |
| -use napi::bindgen_prelude::*; |
| 4 | +use napi::{ |
| 5 | + bindgen_prelude::AsyncTask, |
| 6 | + Env, Error, JsBuffer, JsBufferValue, Ref, Result, Status, Task, |
| 7 | +}; |
| 8 | +use zstd::stream::{encode_all, decode_all}; |
| 9 | + |
| 10 | +struct Encoder { |
| 11 | + data: Ref<JsBufferValue> |
| 12 | +} |
| 13 | + |
| 14 | +#[napi] |
| 15 | +impl Task for Encoder { |
| 16 | + type Output = Vec<u8>; |
| 17 | + type JsValue = JsBuffer; |
| 18 | + |
| 19 | + fn compute(&mut self) -> Result<Self::Output> { |
| 20 | + let data: &[u8] = self.data.as_ref(); |
| 21 | + encode_all(data, 3).map_err(|e| Error::new(Status::GenericFailure, format!("{}", e))) |
| 22 | + } |
| 23 | + |
| 24 | + fn resolve(&mut self, env: Env, output: Self::Output) -> Result<JsBuffer> { |
| 25 | + env.create_buffer_with_data(output).map(|b| b.into_raw()) |
| 26 | + } |
| 27 | + |
| 28 | + fn finally(&mut self, env: Env) -> Result<()> { |
| 29 | + self.data.unref(env)?; |
| 30 | + Ok(()) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +struct Decoder { |
| 35 | + data: Ref<JsBufferValue> |
| 36 | +} |
| 37 | + |
| 38 | +#[napi] |
| 39 | +impl Task for Decoder { |
| 40 | + type Output = Vec<u8>; |
| 41 | + type JsValue = JsBuffer; |
| 42 | + |
| 43 | + fn compute(&mut self) -> Result<Self::Output> { |
| 44 | + let data: &[u8] = self.data.as_ref(); |
| 45 | + decode_all(data).map_err(|e| Error::new(Status::GenericFailure, format!("{}", e))) |
| 46 | + } |
| 47 | + |
| 48 | + fn resolve(&mut self, env: Env, output: Self::Output) -> Result<JsBuffer> { |
| 49 | + env.create_buffer_with_data(output).map(|b| b.into_raw()) |
| 50 | + } |
| 51 | + |
| 52 | + fn finally(&mut self, env: Env) -> Result<()> { |
| 53 | + self.data.unref(env)?; |
| 54 | + Ok(()) |
| 55 | + } |
| 56 | +} |
5 | 57 |
|
6 | 58 | #[napi]
|
7 |
| -async fn compress(buffer: Buffer) -> Result<Buffer> { |
8 |
| - Ok(buffer) |
| 59 | +fn compress(data: JsBuffer) -> Result<AsyncTask<Encoder>> { |
| 60 | + let encoder = Encoder { |
| 61 | + data: data.into_ref()?, |
| 62 | + }; |
| 63 | + Ok(AsyncTask::new(encoder)) |
9 | 64 | }
|
10 | 65 |
|
11 | 66 | #[napi]
|
12 |
| -async fn decompress(buffer: Buffer) -> Result<Buffer> { |
13 |
| - Ok(buffer) |
| 67 | +fn decompress(data: JsBuffer) -> Result<AsyncTask<Decoder>> { |
| 68 | + let decoder = Decoder { |
| 69 | + data: data.into_ref()?, |
| 70 | + }; |
| 71 | + Ok(AsyncTask::new(decoder)) |
14 | 72 | }
|
0 commit comments