BatchedHash.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. /**
  10. * @param {Hash} hash hash
  11. */
  12. constructor(hash) {
  13. super();
  14. this.string = undefined;
  15. this.encoding = undefined;
  16. this.hash = hash;
  17. }
  18. /**
  19. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  20. * @param {string|Buffer} data data
  21. * @param {string=} inputEncoding data encoding
  22. * @returns {this} updated hash
  23. */
  24. update(data, inputEncoding) {
  25. if (this.string !== undefined) {
  26. if (
  27. typeof data === "string" &&
  28. inputEncoding === this.encoding &&
  29. this.string.length + data.length < MAX_SHORT_STRING
  30. ) {
  31. this.string += data;
  32. return this;
  33. }
  34. this.hash.update(this.string, this.encoding);
  35. this.string = undefined;
  36. }
  37. if (typeof data === "string") {
  38. if (
  39. data.length < MAX_SHORT_STRING &&
  40. // base64 encoding is not valid since it may contain padding chars
  41. (!inputEncoding || !inputEncoding.startsWith("ba"))
  42. ) {
  43. this.string = data;
  44. this.encoding = inputEncoding;
  45. } else {
  46. this.hash.update(data, inputEncoding);
  47. }
  48. } else {
  49. this.hash.update(data);
  50. }
  51. return this;
  52. }
  53. /**
  54. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  55. * @param {string=} encoding encoding of the return value
  56. * @returns {string|Buffer} digest
  57. */
  58. digest(encoding) {
  59. if (this.string !== undefined) {
  60. this.hash.update(this.string, this.encoding);
  61. }
  62. return this.hash.digest(encoding);
  63. }
  64. }
  65. module.exports = BatchedHash;