-
Notifications
You must be signed in to change notification settings - Fork 1
/
Memory.jack
66 lines (57 loc) · 1.29 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
class Memory{
static Array RAM;
static Array HEAP;
function void init(){
let RAM = 0;
let HEAP = 2048;
let HEAP[0] = -1; // No more free segments
let HEAP[1] = 16384 - 2048 - 2; // Initial free size
return;
}
function int peek(int address){
return RAM[address];
}
function void poke(int address, int value){
let RAM[address] = value;
return;
}
function Array alloc(int size){
var Array current, selected, block;
var int currentSize, selectedSize;
if(size < 0){
do Sys.error(5);
}
let current = HEAP;
let selected = -1;
let selectedSize = HEAP[1] + 1; // Strictly greater than max
let currentSize = current[1];
while(current > -1){
if(~(currentSize < (size + 2))){
if(currentSize < selectedSize){
let selected = current;
let selectedSize = currentSize;
}
}
let current = current[0];
let currentSize = current[1];
}
if(selected = -1){
do Sys.error(6);
}
let selected[1] = selected[1] - size -2;
let block = selected + selected[1] + 1;
let block[0] = -1;
let block[1] = size;
return block + 2;
}
function void deAlloc(Array array){
var Array current, block;
let block = array - 2;
let current = HEAP;
while(current[0] > 0){
let current = current[0];
}
let current[0] = block;
return;
}
}