forked from denoland/deno
/
034_plugin.ts
67 lines (56 loc) · 1.8 KB
/
034_plugin.ts
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const { openPlugin, pluginFilename, env } = Deno;
const plugin = openPlugin(
env().DENO_BUILD_PATH + "/rust_crates/" + pluginFilename("test_plugin")
);
const testOp = plugin.loadOp("test_op");
const asyncTestOp = plugin.loadOp("async_test_op");
interface TestOptions {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
zeroCopyData: any;
}
interface TestResponse {
data: Uint8Array;
}
const textEncoder = new TextEncoder();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function encodeTestOp(args: any): Uint8Array {
return textEncoder.encode(JSON.stringify(args));
}
const textDecoder = new TextDecoder();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function decodeTestOp(data: Uint8Array): string {
return textDecoder.decode(data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const doTestOp = (args: TestOptions): any => {
const response = testOp.dispatch(
encodeTestOp(args.data),
encodeTestOp(args.zeroCopyData)
);
if (response instanceof Uint8Array) {
return decodeTestOp(response);
} else {
throw new Error("Unexpected response type");
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function doAsyncTestOp(args: TestOptions): Promise<any> {
const response = asyncTestOp.dispatch(
encodeTestOp(args.data),
encodeTestOp(args.zeroCopyData)
);
if (response instanceof Promise) {
return decodeTestOp(await response);
} else {
throw new Error("Unexpected response type");
}
}
async function main(): Promise<void> {
console.log(doTestOp({ data: "test", zeroCopyData: { some: "data" } }));
console.log(
await doAsyncTestOp({ data: "test", zeroCopyData: { some: "data" } })
);
}
main();