Skip to content

Commit 5be608f

Browse files
committed
golfed transferrables
1 parent 9ed2f9f commit 5be608f

File tree

3 files changed

+12
-78
lines changed

3 files changed

+12
-78
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
/dist
22
/node_modules
33
/package-lock.json
4+
/npm-debug.log

greenlet.js

Lines changed: 11 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,3 @@
1-
/**
2-
* Checks whether an object implements a Transferable interface
3-
* @param {*} obj
4-
* obj to check for Transferable interface
5-
*/
6-
function isTransferable(obj) {
7-
// https://developer.mozilla.org/en-US/docs/Web/API/Transferable
8-
return (
9-
obj instanceof ArrayBuffer ||
10-
obj instanceof MessagePort ||
11-
obj instanceof ImageBitmap
12-
);
13-
}
14-
151
/** Move an async function into its own thread.
162
* @param {Function} asyncFunction An (async) function to run in a Worker.
173
* @public
@@ -26,27 +12,17 @@ export default function greenlet(asyncFunction) {
2612
'onmessage=(' + (
2713
// userFunc() is the user-supplied async function
2814
userFunc => e => {
29-
// To check whether an obj is transferable
30-
function isTransferable(obj) {
31-
// https://developer.mozilla.org/en-US/docs/Web/API/Transferable
32-
return (
33-
obj instanceof ArrayBuffer ||
34-
obj instanceof MessagePort ||
35-
obj instanceof ImageBitmap
36-
);
37-
}
3815
// Invoking within then() captures exceptions in userFunc() as rejections
3916
Promise.resolve(e.data[1]).then(
4017
userFunc.apply.bind(userFunc, userFunc)
4118
).then(
4219
// success handler - callback(id, SUCCESS(0), result)
20+
// if `d` is transferrable transfer zero-copy
4321
d => {
44-
if (isTransferable(d)) {
45-
postMessage([e.data[0], 0, d], [d]);
46-
}
47-
else {
48-
postMessage([e.data[0], 0, d]);
49-
}
22+
postMessage([e.data[0], 0, d], (
23+
d instanceof ArrayBuffer ||
24+
d instanceof MessagePort ||
25+
d instanceof ImageBitmap) ? [d] : []);
5026
},
5127
// error handler - callback(id, ERROR(1), error)
5228
er => { postMessage([e.data[0], 1, '' + er]); }
@@ -85,7 +61,12 @@ export default function greenlet(asyncFunction) {
8561
promises[++currentId] = arguments;
8662

8763
// Send an RPC call to the worker - call(id, params)
88-
worker.postMessage([currentId, args], args.filter(x => isTransferable(x)));
64+
// The filter is to provide a list of transferrables to send zero-copy
65+
worker.postMessage([currentId, args], args.filter(x => (
66+
x instanceof ArrayBuffer ||
67+
x instanceof MessagePort ||
68+
x instanceof ImageBitmap
69+
)));
8970
});
9071
};
9172
}

npm-debug.log

Lines changed: 0 additions & 48 deletions
This file was deleted.

0 commit comments

Comments
 (0)