[79a0317] | 1 | /*
|
---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
| 3 | Author Tobias Koppers @sokra
|
---|
| 4 | */
|
---|
| 5 |
|
---|
| 6 | "use strict";
|
---|
| 7 |
|
---|
| 8 | const Hash = require("../Hash");
|
---|
| 9 | const MAX_SHORT_STRING = require("./wasm-hash").MAX_SHORT_STRING;
|
---|
| 10 |
|
---|
| 11 | class BatchedHash extends Hash {
|
---|
| 12 | /**
|
---|
| 13 | * @param {Hash} hash hash
|
---|
| 14 | */
|
---|
| 15 | constructor(hash) {
|
---|
| 16 | super();
|
---|
| 17 | this.string = undefined;
|
---|
| 18 | this.encoding = undefined;
|
---|
| 19 | this.hash = hash;
|
---|
| 20 | }
|
---|
| 21 |
|
---|
| 22 | /**
|
---|
| 23 | * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
|
---|
| 24 | * @param {string|Buffer} data data
|
---|
| 25 | * @param {string=} inputEncoding data encoding
|
---|
| 26 | * @returns {this} updated hash
|
---|
| 27 | */
|
---|
| 28 | update(data, inputEncoding) {
|
---|
| 29 | if (this.string !== undefined) {
|
---|
| 30 | if (
|
---|
| 31 | typeof data === "string" &&
|
---|
| 32 | inputEncoding === this.encoding &&
|
---|
| 33 | this.string.length + data.length < MAX_SHORT_STRING
|
---|
| 34 | ) {
|
---|
| 35 | this.string += data;
|
---|
| 36 | return this;
|
---|
| 37 | }
|
---|
| 38 | this.hash.update(this.string, this.encoding);
|
---|
| 39 | this.string = undefined;
|
---|
| 40 | }
|
---|
| 41 | if (typeof data === "string") {
|
---|
| 42 | if (
|
---|
| 43 | data.length < MAX_SHORT_STRING &&
|
---|
| 44 | // base64 encoding is not valid since it may contain padding chars
|
---|
| 45 | (!inputEncoding || !inputEncoding.startsWith("ba"))
|
---|
| 46 | ) {
|
---|
| 47 | this.string = data;
|
---|
| 48 | this.encoding = inputEncoding;
|
---|
| 49 | } else {
|
---|
| 50 | this.hash.update(data, inputEncoding);
|
---|
| 51 | }
|
---|
| 52 | } else {
|
---|
| 53 | this.hash.update(data);
|
---|
| 54 | }
|
---|
| 55 | return this;
|
---|
| 56 | }
|
---|
| 57 |
|
---|
| 58 | /**
|
---|
| 59 | * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
|
---|
| 60 | * @param {string=} encoding encoding of the return value
|
---|
| 61 | * @returns {string|Buffer} digest
|
---|
| 62 | */
|
---|
| 63 | digest(encoding) {
|
---|
| 64 | if (this.string !== undefined) {
|
---|
| 65 | this.hash.update(this.string, this.encoding);
|
---|
| 66 | }
|
---|
| 67 | return this.hash.digest(encoding);
|
---|
| 68 | }
|
---|
| 69 | }
|
---|
| 70 |
|
---|
| 71 | module.exports = BatchedHash;
|
---|