Skip to content

Commit 18351dc

Browse files
committed
feat: implement async variant
1 parent afcf37e commit 18351dc

File tree

5 files changed

+30
-5
lines changed

5 files changed

+30
-5
lines changed

index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@
55

66
export function hash(input: Uint8Array): Uint8Array
77
export function hashInto(input: Uint8Array, output: Uint8Array): void
8+
export function hashAsync(input: Uint8Array): Promise<Uint8Array>

index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,8 @@ if (!nativeBinding) {
310310
throw new Error(`Failed to load native binding`)
311311
}
312312

313-
const { hash, hashInto } = nativeBinding
313+
const { hash, hashInto, hashAsync } = nativeBinding
314314

315315
module.exports.hash = hash
316316
module.exports.hashInto = hashInto
317+
module.exports.hashAsync = hashAsync

src/lib.rs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#![deny(clippy::all)]
22

33
use hashtree_rs::{hash as HASH, init};
4-
use napi::{bindgen_prelude::Uint8Array, Error};
4+
use napi::{bindgen_prelude::{AsyncTask, Uint8Array}, Env, Error, Task};
55
use std::sync::Once;
66

77
#[macro_use]
@@ -45,3 +45,25 @@ pub fn hash_into(input: Uint8Array, mut output: Uint8Array) -> Result<(), Error>
4545
HASH(output.as_mut(), input.as_ref(), output_len / 32);
4646
Ok(())
4747
}
48+
49+
pub struct AsyncHash {
50+
input: Uint8Array
51+
}
52+
53+
#[napi]
54+
impl Task for AsyncHash {
55+
type Output = Uint8Array;
56+
type JsValue = Uint8Array;
57+
fn compute(&mut self) -> Result<Uint8Array, Error> {
58+
hash(self.input.clone())
59+
}
60+
61+
fn resolve(&mut self, _env: Env, output: Self::Output) -> Result<Self::JsValue, Error> {
62+
Ok(output)
63+
}
64+
}
65+
66+
#[napi]
67+
pub fn hash_async(input: Uint8Array) -> AsyncTask<AsyncHash> {
68+
AsyncTask::new(AsyncHash { input })
69+
}

test/index.spec.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {createHash} from "node:crypto";
2-
import {hash, hashInto} from "../index";
2+
import {hash, hashInto, hashAsync} from "../index";
33

44
type BufferLike = string | Uint8Array | Buffer;
55

@@ -49,10 +49,11 @@ function nodeCryptoHashInto(input: Buffer, output: Buffer): void {
4949

5050
describe("should hash similarly to crypto.createHash('sha256')", () => {
5151
for (let i = 1; i <= 16; i++) {
52-
test(`No of Chunks=${i}`, () => {
52+
test(`No of Chunks=${i}`, async () => {
5353
for (let j = 0; j < 255; j++) {
5454
const input = Buffer.alloc(CHUNK_SIZE * i, j);
5555
expectEqualHex(hash(input), nodeCryptoHash(input));
56+
expectEqualHex(hash(input), await hashAsync(input));
5657
}
5758
});
5859
}

0 commit comments

Comments
 (0)