]> zoso.dev Git - libnemo.git/commitdiff
Add pool function to check if object should be transferred to the worker directly...
authorChris Duncan <chris@zoso.dev>
Thu, 12 Dec 2024 14:59:27 +0000 (06:59 -0800)
committerChris Duncan <chris@zoso.dev>
Thu, 12 Dec 2024 14:59:27 +0000 (06:59 -0800)
src/lib/pool.ts

index 87994175e9ecb9e147812a085c5e7b27c01c9775..0ca7d977f25c39ad450d1c495f695c67a97b8b1b 100644 (file)
@@ -48,6 +48,12 @@ export class Pool {
                job.data = job.data.slice(chunk)
                if (job.data.length === 0) this.#queue.shift()
                if (next?.length > 0) {
+                       if (this.#isTransferable(next)) {
+                               thread.worker.postMessage({ name: job.name, next }, [next])
+                       }
+               } else if (this.#isTransferable(next[0])) {
+                       thread.worker.postMessage({ name: job.name, next }, next)
+               } else {
                        const buffer = new TextEncoder().encode(JSON.stringify(next)).buffer
                        thread.job = job
                        thread.worker.postMessage({ name: job.name, buffer }, [buffer])
@@ -61,6 +67,25 @@ export class Pool {
                return true
        }
 
+       static #isTransferable (obj: any): boolean {
+               return obj instanceof ArrayBuffer
+                       //@ts-expect-error
+                       || obj instanceof AudioData
+                       || obj instanceof ImageBitmap
+                       || obj instanceof MediaSourceHandle
+                       || obj instanceof MIDIAccess
+                       || obj instanceof OffscreenCanvas
+                       || obj instanceof ReadableStream
+                       || obj instanceof RTCDataChannel
+                       || obj instanceof TransformStream
+                       || obj instanceof VideoFrame
+                       //@ts-expect-error
+                       || obj instanceof WebTransportReceiveStream
+                       //@ts-expect-error
+                       || obj instanceof WebTransportSendStream
+                       || obj instanceof WritableStream
+       }
+
        static #report (thread: Thread, results: any[]): void {
                if (thread.job == null) {
                        throw new Error('Thread returned results but had nowhere to report it.')