Memory utility
by Nicholas C. Zakas
If you find this useful, please consider supporting my work with a donation.
Description
A JavaScript implementation of dynamic memory using an ArrayBuffer as the memory storage.
Warning: Very experimental right now. May or may not be useful.
Usage
Node.js
Install using npm or yarn:
npm install @humanwhocodes/memory --save
# or
yarn add @humanwhocodes/memory
Import into your Node.js project:
const { Memory } = require("@humanwhocodes/memory");
import { Memory } from "@humanwhocodes/memory";
Deno
Import into your Deno project:
import { Memory } from "https://cdn.skypack.dev/@humanwhocodes/memory?dts";
Browser
It's recommended to import the minified version to save bandwidth:
import { Memory } from "https://cdn.skypack.dev/@humanwhocodes/memory?min";
However, you can also import the unminified version for debugging purposes:
import { Memory } from "https://cdn.skypack.dev/@humanwhocodes/memory";
API
After importing, create a new instance of Memory and pass in an ArrayBuffer to represent your memory:
const memory = new Memory(new ArrayBuffer(64));
const address = memory.allocate(4);
if (address) {
memory.write(address, new Uint8Array([1, 2, 3, 4]));
const data = memory.read(address);
memory.free(address);
} else {
console.error("Could not allocate memory.");
}
Safety
The Memory class provides safeguards to ensure you aren't accidentally writing or reading data where you shouldn't:
allocate() returns 0 when no more memory can be allocated, allowing you to handle out-of-memory issues gracefully.
write() throws an error when:
- You try to write to address
0.
- You try to write to an unallocated address.
- The data you're writing is larger than the allocated space.
read() throws an error if you attempt to read from an invalid address.
free() throws an error if you attempt to free an invalid address.
All of this is to say, it should be difficult to accidentally overwrite memory locations.
Developer Setup
- Fork the repository
- Clone your fork
- Run
npm install to setup dependencies
- Run
npm test to run tests
License
Apache 2.0