1 | ;
|
2 | export class ParallelHasher {
|
3 | constructor(workerUri, workerOptions) {
|
4 | this._queue = [];
|
5 | this._ready = true;
|
6 | const self = this;
|
7 | if (Worker) {
|
8 | self._hashWorker = new Worker(workerUri, workerOptions);
|
9 | self._hashWorker.onmessage = self._recievedMessage.bind(self);
|
10 | self._hashWorker.onerror = (err) => {
|
11 | self._ready = false;
|
12 | console.error('Hash worker failure', err);
|
13 | };
|
14 | }
|
15 | else {
|
16 | self._ready = false;
|
17 | console.error('Web Workers are not supported in this browser');
|
18 | }
|
19 | }
|
20 | |
21 |
|
22 |
|
23 |
|
24 |
|
25 | hash(blob) {
|
26 | const self = this;
|
27 | let promise;
|
28 | promise = new Promise((resolve, reject) => {
|
29 | self._queue.push({
|
30 | blob,
|
31 | resolve,
|
32 | reject,
|
33 | });
|
34 | self._processNext();
|
35 | });
|
36 | return promise;
|
37 | }
|
38 |
|
39 | terminate() {
|
40 | this._ready = false;
|
41 | this._hashWorker.terminate();
|
42 | }
|
43 |
|
44 | _processNext() {
|
45 | if (this._ready && !this._processing && this._queue.length > 0) {
|
46 | this._processing = this._queue.pop();
|
47 | this._hashWorker.postMessage(this._processing.blob);
|
48 | }
|
49 | }
|
50 |
|
51 | _recievedMessage(evt) {
|
52 | var _a, _b;
|
53 | const data = evt.data;
|
54 | if (data.success) {
|
55 | (_a = this._processing) === null || _a === void 0 ? void 0 : _a.resolve(data.result);
|
56 | }
|
57 | else {
|
58 | (_b = this._processing) === null || _b === void 0 ? void 0 : _b.reject(data.result);
|
59 | }
|
60 | this._processing = undefined;
|
61 | this._processNext();
|
62 | }
|
63 | }
|
64 |
|
\ | No newline at end of file |