-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
52 lines (50 loc) · 1.36 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { decompress, decompressAll } from './src/'
import { spawn, Pool, Transfer } from 'threads'
import Worker from './src/worker.js'
class LZW {
constructor (numWorkers, outputBuffer) {
this.outputBuffer= outputBuffer
this.usingWorkers = numWorkers > 0
if (this.usingWorkers > 0) {
this.pool = Pool(
() => spawn(new Worker(), numWorkers)
)
} else {
this.pool = null
}
}
prepareDataForTransfer (typedArrays) {
const transfers = []
return Transfer(
typedArrays.map(function (typedArray) {
if (typedArray.buffer instanceof SharedArrayBuffer) {
return typedArray
} else {
if (typedArray.byteLength != typedArray.buffer.byteLength) {
// If the typedArray doesn't span the buffer, lets play it safe and make a copy
typedArray = typedArray.slice()
}
transfers.push(typedArray.buffer)
return typedArray
}
}),
transfers
)
}
async decompress(typedArrays) {
if (!this.pool) {
return await decompressAll(typedArrays, this.outputBuffer)
} else {
const data = this.prepareDataForTransfer(typedArrays)
const pool = await this.pool
return await pool.queue(
async worker => await worker.decompressAll(data)
)
}
}
}
export {
decompress,
decompressAll,
LZW
}