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