summaryrefslogtreecommitdiff
path: root/ext/node/polyfills
diff options
context:
space:
mode:
Diffstat (limited to 'ext/node/polyfills')
-rw-r--r--ext/node/polyfills/internal/crypto/hash.ts32
1 files changed, 19 insertions, 13 deletions
diff --git a/ext/node/polyfills/internal/crypto/hash.ts b/ext/node/polyfills/internal/crypto/hash.ts
index 7a7c0be8e..e2907632f 100644
--- a/ext/node/polyfills/internal/crypto/hash.ts
+++ b/ext/node/polyfills/internal/crypto/hash.ts
@@ -1,13 +1,9 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright Joyent, Inc. and Node.js contributors. All rights reserved. MIT license.
-import {
- TextDecoder,
- TextEncoder,
-} from "internal:deno_web/08_text_encoding.js";
+import { TextEncoder } from "internal:deno_web/08_text_encoding.js";
import { Buffer } from "internal:deno_node/buffer.ts";
import { Transform } from "internal:deno_node/stream.ts";
-import { encode as encodeToHex } from "internal:deno_node/internal/crypto/_hex.ts";
import {
forgivingBase64Encode as encodeToBase64,
forgivingBase64UrlEncode as encodeToBase64Url,
@@ -26,6 +22,14 @@ import { notImplemented } from "internal:deno_node/_utils.ts";
const { ops } = globalThis.__bootstrap.core;
+// TODO(@littledivy): Use Result<T, E> instead of boolean when
+// https://bugs.chromium.org/p/v8/issues/detail?id=13600 is fixed.
+function unwrapErr(ok: boolean) {
+ if (!ok) {
+ throw new Error("Context is not initialized");
+ }
+}
+
const coerceToBytes = (data: string | BufferSource): Uint8Array => {
if (data instanceof Uint8Array) {
return data;
@@ -71,6 +75,9 @@ export class Hash extends Transform {
this.#context = ops.op_node_create_hash(
algorithm,
);
+ if (this.#context === 0) {
+ throw new TypeError(`Unknown hash algorithm: ${algorithm}`);
+ }
} else {
this.#context = algorithm;
}
@@ -86,16 +93,12 @@ export class Hash extends Transform {
* Updates the hash content with the given data.
*/
update(data: string | ArrayBuffer, _encoding?: string): this {
- let bytes;
if (typeof data === "string") {
- data = new TextEncoder().encode(data);
- bytes = coerceToBytes(data);
+ unwrapErr(ops.op_node_hash_update_str(this.#context, data));
} else {
- bytes = coerceToBytes(data);
+ unwrapErr(ops.op_node_hash_update(this.#context, coerceToBytes(data)));
}
- ops.op_node_hash_update(this.#context, bytes);
-
return this;
}
@@ -107,14 +110,17 @@ export class Hash extends Transform {
* Supported encodings are currently 'hex', 'binary', 'base64', 'base64url'.
*/
digest(encoding?: string): Buffer | string {
+ if (encoding === "hex") {
+ return ops.op_node_hash_digest_hex(this.#context);
+ }
+
const digest = ops.op_node_hash_digest(this.#context);
if (encoding === undefined) {
return Buffer.from(digest);
}
+ // TODO(@littedivy): Fast paths for below encodings.
switch (encoding) {
- case "hex":
- return new TextDecoder().decode(encodeToHex(new Uint8Array(digest)));
case "binary":
return String.fromCharCode(...digest);
case "base64":