parallel_hasher.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ParallelHasher = void 0;
  4. ;
  5. var ParallelHasher = /** @class */ (function () {
  6. function ParallelHasher(workerUri, workerOptions) {
  7. this._queue = [];
  8. this._ready = true;
  9. var self = this;
  10. if (Worker) {
  11. self._hashWorker = new Worker(workerUri, workerOptions);
  12. self._hashWorker.onmessage = self._recievedMessage.bind(self);
  13. self._hashWorker.onerror = function (err) {
  14. self._ready = false;
  15. console.error('Hash worker failure', err);
  16. };
  17. }
  18. else {
  19. self._ready = false;
  20. console.error('Web Workers are not supported in this browser');
  21. }
  22. }
  23. /**
  24. * Hash a blob of data in the worker
  25. * @param blob Data to hash
  26. * @returns Promise of the Hashed result
  27. */
  28. ParallelHasher.prototype.hash = function (blob) {
  29. var self = this;
  30. var promise;
  31. promise = new Promise(function (resolve, reject) {
  32. self._queue.push({
  33. blob: blob,
  34. resolve: resolve,
  35. reject: reject,
  36. });
  37. self._processNext();
  38. });
  39. return promise;
  40. };
  41. /** Terminate any existing hash requests */
  42. ParallelHasher.prototype.terminate = function () {
  43. this._ready = false;
  44. this._hashWorker.terminate();
  45. };
  46. // Processes the next item in the queue
  47. ParallelHasher.prototype._processNext = function () {
  48. if (this._ready && !this._processing && this._queue.length > 0) {
  49. this._processing = this._queue.pop();
  50. this._hashWorker.postMessage(this._processing.blob);
  51. }
  52. };
  53. // Hash result is returned from the worker
  54. ParallelHasher.prototype._recievedMessage = function (evt) {
  55. var _a, _b;
  56. var data = evt.data;
  57. if (data.success) {
  58. (_a = this._processing) === null || _a === void 0 ? void 0 : _a.resolve(data.result);
  59. }
  60. else {
  61. (_b = this._processing) === null || _b === void 0 ? void 0 : _b.reject(data.result);
  62. }
  63. this._processing = undefined;
  64. this._processNext();
  65. };
  66. return ParallelHasher;
  67. }());
  68. exports.ParallelHasher = ParallelHasher;
  69. //# sourceMappingURL=parallel_hasher.js.map