64 lines
1.9 KiB
Plaintext
Executable File
64 lines
1.9 KiB
Plaintext
Executable File
// This file is part of www.nand2tetris.org
|
|
// and the book "The Elements of Computing Systems"
|
|
// by Nisan and Schocken, MIT Press.
|
|
// File name: projects/12/Memory.jack
|
|
|
|
/**
|
|
* This library provides two services: direct access to the computer's main
|
|
* memory (RAM), and allocation and recycling of memory blocks. The Hack RAM
|
|
* consists of 32,768 words, each holding a 16-bit binary number.
|
|
*/
|
|
class Memory {
|
|
static Array mem;
|
|
/** Initializes the class. */
|
|
function void init() {
|
|
let mem = 0;
|
|
let mem[2048] = 14334;
|
|
let mem[2049] = -1;
|
|
return;
|
|
}
|
|
|
|
/** Returns the RAM value at the given address. */
|
|
function int peek(int address) {
|
|
return mem[address];
|
|
}
|
|
|
|
/** Sets the RAM value at the given address to the given value. */
|
|
function void poke(int address, int value) {
|
|
let mem[address] = value;
|
|
return;
|
|
}
|
|
|
|
/** Finds an available RAM block of the given size and returns
|
|
* a reference to its base address. */
|
|
function int alloc(int size) {
|
|
var Array current_block;
|
|
var int tmp;
|
|
let current_block = 2048;
|
|
if (size < 0){
|
|
do Sys.error(5);
|
|
}
|
|
if (size = 0){
|
|
let size = 1;
|
|
}
|
|
while (current_block[0] < (size + 2)) {
|
|
let current_block = current_block[1];
|
|
}
|
|
let current_block[0] = current_block[0] - size - 2;
|
|
let current_block = current_block + current_block[0] + 2;
|
|
let current_block[0] = size;
|
|
return current_block + 2;
|
|
}
|
|
|
|
/** De-allocates the given object (cast as an array) by making
|
|
* it available for future allocations. */
|
|
function void deAlloc(Array o) {
|
|
var Array current_block;
|
|
let current_block = 2048;
|
|
let o[1]= current_block[1];
|
|
let current_block[1] = o;
|
|
return;
|
|
|
|
}
|
|
}
|