hash-instance.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { inputToArray, defaultHashLength } from './hash-fn.js';
  2. /**
  3. * Base implementation of hashing.
  4. */
  5. export class BaseHash {
  6. constructor(implementation, alloc, getReader) {
  7. this.alloc = alloc;
  8. this.getReader = getReader;
  9. this.hash = implementation;
  10. }
  11. /**
  12. * @inheritdoc
  13. */
  14. update(data) {
  15. if (!this.hash) {
  16. throw new Error('Cannot continue updating hashing after dispose() has been called');
  17. }
  18. this.hash.update(inputToArray(data));
  19. return this;
  20. }
  21. /**
  22. * @inheritdoc
  23. */
  24. digest({ length = defaultHashLength, dispose = true } = {}) {
  25. if (!this.hash) {
  26. throw new Error('Cannot call digest() after dipose() has been called');
  27. }
  28. const digested = this.alloc(length);
  29. this.hash.digest(digested);
  30. if (dispose) {
  31. this.dispose();
  32. }
  33. return digested;
  34. }
  35. /**
  36. * @inheritdoc
  37. */
  38. reader({ dispose = true } = {}) {
  39. if (!this.hash) {
  40. throw new Error('Cannot call reader() after dipose() has been called');
  41. }
  42. const reader = this.getReader(this.hash.reader());
  43. if (dispose) {
  44. this.dispose();
  45. }
  46. return reader;
  47. }
  48. /**
  49. * @inheritdoc
  50. */
  51. dispose() {
  52. var _a;
  53. (_a = this.hash) === null || _a === void 0 ? void 0 : _a.free();
  54. this.hash = undefined;
  55. }
  56. }
  57. //# sourceMappingURL=hash-instance.js.map