+/TECS
git clone https://git.julia.blue/+/TECS
b17cc4b
master
1/** 2 * This library provides two services: direct access to the computer's main 3 * memory (RAM), and allocation and recycling of memory blocks. The Hack RAM 4 * consists of 32,768 words, each holding a 16-bit binary number. 5 */ 6class Memory { 7 static Array mem; 8 static Array freeList; 9 10 /** Initializes the class. */ 11 function void init() { 12 let freeList = 2048; // Heap starts at 2048 13 let freeList[0] = null; //Never allocate to the head of the heap 14 let freeList[1] = 2050; // Next 15 let freeList[2] = 14333; // Ends at 16383 16 let freeList[3] = null; 17 return; 18 } 19 20 /** Returns the RAM value at the given address. */ 21 function int peek(int address) { 22 return mem[address]; 23 } 24 25 /** Sets the RAM value at the given address to the given value. */ 26 function void poke(int address, int value) { 27 let mem[address] = value; 28 return; 29 } 30 31 /** Finds an available RAM block of the given size and returns 32 * a reference to its base address. This implementation uses 33 * first fit linked list as opposed to best fit. */ 34 function int alloc(int size) { 35 var Array current, prev, temp; 36 var int remainder; 37 if(size <= 0){ 38 do Sys.error(5); 39 } 40 let current = freeList; 41 while(current[1] ~= null){ 42 let prev = current; 43 let current = current[1]; 44 if(size <= current[0]){ 45 let temp = current + 1; 46 if((current[0] - size) < 5){ // Minimum block size 47 let prev[1] = current[1]; 48 } 49 else{ 50 let prev[1] = temp + size; 51 let remainder = current[0] - (size + 1); // +1 for the size bookkeeping word 52 let current[0] = size; // Size of allocated block 53 let current = prev[1]; 54 let current[0] = remainder; 55 let current[1] = temp[0]; 56 } 57 return temp; 58 } 59 } 60 do Sys.error(6); 61 } 62 63 /** De-allocates the given object (cast as an array) by making 64 * it available for future allocations. */ 65 function void deAlloc(Array o) { 66 var Array current; 67 let o = o - 1; 68 let o[1] = null; 69 let current = freeList; 70 while(current[1] ~= null){ 71 let current = current[1]; 72 } 73 let current[1] = o; 74 return; 75 } 76}