BatchedHash.js 1.7 KB

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