-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathlib.rs
More file actions
81 lines (71 loc) · 2.38 KB
/
Copy pathlib.rs
File metadata and controls
81 lines (71 loc) · 2.38 KB
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
76
77
78
79
80
81
extern crate napi;
#[macro_use]
extern crate napi_derive;
extern crate xxhash_rust;
use napi::{CallContext, Env, JsBuffer, JsObject, JsString, JsUndefined, Property, Result};
use std::hash::Hasher;
use xxhash_rust::xxh3::{xxh3_64, Xxh3};
#[js_function(1)]
fn hash_string(ctx: CallContext) -> Result<JsString> {
let s = ctx.get::<JsString>(0)?.into_utf8()?;
let s = s.as_slice();
let res = xxh3_64(s);
let res_str = format!("{:016x}", res);
ctx.env.create_string_from_std(res_str)
}
#[js_function(1)]
fn hash_buffer(ctx: CallContext) -> Result<JsString> {
let s = ctx.get::<JsBuffer>(0)?.into_value()?;
let s = s.as_ref();
let res = xxh3_64(s);
let res_str = format!("{:016x}", res);
ctx.env.create_string_from_std(res_str)
}
#[js_function(1)]
fn constructor(ctx: CallContext) -> Result<JsUndefined> {
let mut this: JsObject = ctx.this_unchecked();
let h = Xxh3::new();
ctx.env.wrap(&mut this, h)?;
ctx.env.get_undefined()
}
#[js_function(1)]
fn write_string(ctx: CallContext) -> Result<JsUndefined> {
let this: JsObject = ctx.this_unchecked();
let h: &mut Xxh3 = ctx.env.unwrap(&this)?;
let s = ctx.get::<JsString>(0)?.into_utf8()?;
let s = s.as_slice();
h.write(s);
ctx.env.get_undefined()
}
#[js_function(1)]
fn write_buffer(ctx: CallContext) -> Result<JsUndefined> {
let this: JsObject = ctx.this_unchecked();
let h: &mut Xxh3 = ctx.env.unwrap(&this)?;
let s = ctx.get::<JsBuffer>(0)?.into_value()?;
let s = s.as_ref();
h.write(s);
ctx.env.get_undefined()
}
#[js_function(1)]
fn finish(ctx: CallContext) -> Result<JsString> {
let this: JsObject = ctx.this_unchecked();
let h: &mut Xxh3 = ctx.env.unwrap(&this)?;
let res = h.finish();
let res_str = format!("{:016x}", res);
ctx.env.create_string_from_std(res_str)
}
#[module_exports]
fn init(mut exports: JsObject, env: Env) -> Result<()> {
exports.create_named_method("hashString", hash_string)?;
exports.create_named_method("hashBuffer", hash_buffer)?;
let write_string_method = Property::new(&env, "writeString")?.with_method(write_string);
let write_buffer_method = Property::new(&env, "writeBuffer")?.with_method(write_buffer);
let finish_method = Property::new(&env, "finish")?.with_method(finish);
let hash_class = env.define_class(
"Hash",
constructor,
&[write_string_method, write_buffer_method, finish_method],
)?;
exports.set_named_property("Hash", hash_class)?;
Ok(())
}