Nand2Tetris — Chapter 12
The Jack Operating System
// Math.jack
//OS implementation example
//multiply implements multiplication with repeated addition.
//divide implements division with repeated subtraction.
class Math {
function void init() {
return;
}
function int multiply(int x, int y) {
var int result;
let result = 0;
while (y > 0) {
let result = result + x;
let y = y - 1;
}
return result;
}
function int divide(int x, int y) {
var int result;
let result = 0;
while (~(x < y)) {
let x = x - y;
let result = result + 1;
}
return result;
}
}
// String.jack
//String object partial implementation
//Store characters in an internal array and manage length separately
class String {
field Array data;
field int length;
field int capacity;
constructor String new(int maxLength) {
let capacity = maxLength;
let length = 0;
let data = Array.new(maxLength);
return this;
}
method void dispose() {
do data.dispose();
do Memory.deAlloc(this);
return;
}
method int length() {
return length;
}
method String appendChar(char c) {
let data[length] = c;
let length = length + 1;
return this;
}
method char charAt(int index) {
return data[index];
}
}
// Array.jack
//Array.new allocates memory equal to size in the Heap.
//The Jack array is actually a block of memory with a base address.
class Array {
function Array new(int size) {
return Memory.alloc(size);
}
method void dispose() {
do Memory.deAlloc(this);
return;
}
}