-
Notifications
You must be signed in to change notification settings - Fork 0
/
Memory.jack
90 lines (83 loc) · 2.27 KB
/
Memory.jack
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// 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 RAM, freeList;
/** Initializes the class. */
function void init() {
let RAM = 0;
let freeList = 2048;
let freeList[0] = 16383 - 2048 + 1;
let freeList[1] = -1;
return;
}
/** Returns the RAM value at the given address. */
function int peek(int address) {
return RAM[address];
}
/** Sets the RAM value at the given address to the given value. */
function void poke(int address, int value) {
let RAM[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 block;
var int next, blockSize;
let blockSize = freeList[0];
let next = freeList[1];
if (blockSize > (size + 2)) {
let block = freeList;
if (~(next = -1)) {
let freeList = next;
} else {
let freeList = block + size + 2;
let freeList[0] = blockSize - size - 2;
let freeList[1] = -1;
}
// let block[0] = blockSize - size - 1;
// let block[1] = freeList;
// let block[block[0]] = size + 1;
// return block + block[0] + 1;
let block[0] = size;
let block[1] = -1;
return block + 2;
}
// if (~(next = -1)) {
// let freeList = next;
// return Memory.alloc(size);
// }
while (~(next = -1)) {
let block = next;
let next = block[1];
if (blockSize > (size + 2)) {
let blockSize = blockSize - size - 2;
let block[0] = blockSize;
let block[blockSize] = size;
let block[blockSize + 1] = -1;
return block + blockSize + 2;
}
}
return -1;
}
/** De-allocates the given object (cast as an array) by making
* it available for future allocations. */
function void deAlloc(Array o) {
var Array seg, next;
let seg = freeList;
let next = seg[1];
while (~(next = -1)) {
let seg = next;
let next = seg[1];
}
let next = o;
return;
}
}