|
1 | | -import {Buffer} from 'node:buffer'; |
2 | 1 | import {Worker} from 'node:worker_threads'; |
3 | 2 | import crypto from 'node:crypto'; |
| 3 | +import {bufferToHex} from './utilities.js'; |
4 | 4 |
|
5 | 5 | let create = algorithm => async (buffer, {outputFormat = 'hex'} = {}) => { |
6 | 6 | const hash = crypto.createHash(algorithm); |
@@ -52,24 +52,11 @@ if (Worker !== undefined) { |
52 | 52 | }); |
53 | 53 |
|
54 | 54 | create = algorithm => async (source, {outputFormat = 'hex'} = {}) => { |
55 | | - let buffer; |
56 | | - if (typeof source === 'string') { |
57 | | - // Saving one copy operation by writing string to buffer right away and then transfering buffer |
58 | | - buffer = new ArrayBuffer(Buffer.byteLength(source, 'utf8')); |
59 | | - Buffer.from(buffer).write(source, 'utf8'); |
60 | | - } else { |
61 | | - const finalSource = source instanceof ArrayBuffer ? new Uint8Array(source) : source; |
62 | | - |
63 | | - // Creating a copy of buffer at call time, will be transfered later |
64 | | - buffer = finalSource.buffer.slice(0); // eslint-disable-line unicorn/prefer-spread |
65 | | - } |
| 55 | + const {buffer} = typeof source === 'string' ? new TextEncoder().encode(source) : (source instanceof ArrayBuffer ? new Uint8Array(source) : source); |
66 | 56 |
|
67 | | - const result = await taskWorker({algorithm, buffer}, [buffer]); |
68 | | - if (outputFormat === 'hex') { |
69 | | - return Buffer.from(result).toString('hex'); |
70 | | - } |
| 57 | + const hash = await taskWorker({algorithm, buffer}, [buffer]); |
71 | 58 |
|
72 | | - return result; |
| 59 | + return outputFormat === 'hex' ? bufferToHex(hash) : hash; |
73 | 60 | }; |
74 | 61 | } |
75 | 62 |
|
|
0 commit comments