git ssb

0+

wanderer🌟 / js-primea-wasm-container



Tree: 5f942df4b072166f79f934a8cfe0c6888abcaf21

Files: 5f942df4b072166f79f934a8cfe0c6888abcaf21 / index.js

1909 bytesRaw
1const ReferanceMap = require('./referanceMap.js')
2
3module.exports = class WasmContainer {
4 /**
5 * The interface API is the api the exposed to interfaces. All queries about
6 * the enviroment and call to the kernel go through this API
7 */
8 constructor (exoInterface, imports) {
9 this.exoInterface = exoInterface
10 this.imports = imports
11 this.referanceMap = new ReferanceMap()
12 }
13
14 /**
15 * Runs the core VM with a given environment and imports
16 */
17 async run (message) {
18 /**
19 * Builds a import map with an array of given interfaces
20 */
21 const importMap = {}
22 for (const name in this.imports) {
23 importMap[name] = {}
24 const Import = this.imports[name]
25 const newInterface = new Import(this)
26 const props = Object.getOwnPropertyNames(Import.prototype)
27
28 // bind the methods to the correct 'this'
29 for (const prop of props) {
30 if (prop !== 'constructor') {
31 importMap[name][prop] = newInterface[prop].bind(newInterface)
32 }
33 }
34 }
35
36 const result = await WebAssembly.instantiate(this.exoInterface.state['/'].code, importMap)
37 this.instance = result.instance
38 if (this.instance.exports.main) {
39 this.instance.exports.main()
40 }
41 return this.onDone()
42 }
43
44 /**
45 * returns a promise that resolves when the wasm instance is done running
46 */
47 async onDone () {
48 let prevOps
49 while (prevOps !== this._opsQueue) {
50 prevOps = this._opsQueue
51 await prevOps
52 }
53 this.referanceMap.clear()
54 }
55
56 pushOpsQueue (promise) {
57 this._opsQueue = Promise.all([this._opsQueue, promise])
58 return this._opsQueue
59 }
60
61 get memory () {
62 return this.instance.exports.memory.buffer
63 }
64
65 getMemory (offset, length) {
66 return new Uint8Array(this.memory, offset, length)
67 }
68
69 static createState (wasm) {
70 return {
71 nonce: [0],
72 ports: {},
73 code: wasm
74 }
75 }
76}
77

Built with git-ssb-web