UNPKG

1.59 kBJavaScriptView Raw
1/**
2 * WorkersResult
3 * =============
4 *
5 * A response sent back from a worker to the main thread. Contains the "result"
6 * of the computation in the form of a buffer, resbuf. If the actual result is
7 * an object with a .toFastBuffer method, the object is converted to a buffer
8 * using that method. Otherwise it is JSON serialized into a buffer. The result
9 * can also be an error, in which case the isError flag is set.
10 */
11'use strict'
12
13import { Bw } from './bw'
14import { Struct } from './struct'
15
16class WorkersResult extends Struct {
17 constructor (resbuf, isError, id) {
18 super({ resbuf, isError, id })
19 }
20
21 fromResult (result, id) {
22 if (result.toFastBuffer) {
23 this.resbuf = result.toFastBuffer()
24 } else if (Buffer.isBuffer(result)) {
25 this.resbuf = result
26 } else {
27 this.resbuf = Buffer.from(JSON.stringify(result))
28 }
29 this.isError = false
30 this.id = id
31 return this
32 }
33
34 static fromResult (result, id) {
35 return new this().fromResult(result, id)
36 }
37
38 fromError (error, id) {
39 this.resbuf = Buffer.from(JSON.stringify(error.message))
40 this.isError = true
41 this.id = id
42 return this
43 }
44
45 toBw (bw) {
46 if (!bw) {
47 bw = new Bw()
48 }
49 bw.writeVarIntNum(this.resbuf.length)
50 bw.write(this.resbuf)
51 bw.writeUInt8(Number(this.isError))
52 bw.writeVarIntNum(this.id)
53 return bw
54 }
55
56 fromBr (br) {
57 const resbuflen = br.readVarIntNum()
58 this.resbuf = br.read(resbuflen)
59 this.isError = Boolean(br.readUInt8())
60 this.id = br.readVarIntNum()
61 return this
62 }
63}
64
65export { WorkersResult }