Memory
WebAssembly memory constructor.
Usage
var Memory = require( '@stdlib/wasm/memory' );
Memory( descriptor )
Returns a new WebAssembly memory instance.
var mem = new Memory({
'initial': 0
});
// returns <Memory>
The descriptor
argument is an object which supports the following properties:
- initial: (required) initial memory size in units of WebAssembly pages (i.e., 64KiB).
- maximum: maximum memory size in units of WebAssembly pages (i.e., 64KiB).
- shared: boolean indicating whether the memory is shared. Default:
false
.
Memory.prototype.buffer
Read-only property which returns the ArrayBuffer
(or SharedArrayBuffer
) referenced by memory instance.
var mem = new Memory({
'initial': 0
});
var buf = mem.buffer;
// returns <ArrayBuffer>
Methods
Memory.prototype.grow( delta )
Increases the size of the memory instance by a specified number of WebAssembly pages (i.e., 64KiB).
var mem = new Memory({
'initial': 0
});
// ...
var prevSize = mem.grow( 1 );
The method returns the size of the previous ArrayBuffer
(or SharedArrayBuffer
).
Notes
- Upon increasing the size, the previous
ArrayBuffer
is detached, thus invalidating any typed arrays which were views over the previousArrayBuffer
. - Detachment means that the previous
ArrayBuffer
byte length becomes zero, and it no longer has bytes accessible to JavaScript. - When calling
grow
,ArrayBuffer
detachment applies even whendelta
is zero. - Detachment only applies for non-shared memory instances. For a shared memory instance, the initial buffer (which is a
SharedArrayBuffer
) will not become detached and, instead, its length will not be updated. - Accesses to the
buffer
property after growing aSharedArrayBuffer
will yield a largerSharedArrayBuffer
which may access a larger span of memory than the buffer before growing memory. - Every
SharedArrayBuffer
accessed via thebuffer
property will always refer to the start of the same memory address range and thus manipulate the same data.
Examples
var hasWebAssemblySupport = require( '@stdlib/assert/has-wasm-support' );
var DataView = require( '@stdlib/array/dataview' );
var Memory = require( '@stdlib/wasm/memory' );
function main() {
var view;
var mem;
var v;
if ( !hasWebAssemblySupport() ) {
console.error( 'Environment does not support WebAssembly.' );
return;
}
mem = new Memory({
'initial': 1
});
view = new DataView( mem.buffer );
view.setFloat64( 0, 3.14 );
// ...
v = view.getFloat64( 0 );
console.log( v );
// => 3.14
}
main();