BatchedHash.js 1.8 KB

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