Support for memory allocation

- Corten now has basic support for memory allocation through with the ALOC code.
This commit is contained in:
Anthony Foxclaw 2020-02-09 16:41:13 -05:00
parent 86f060e0f5
commit b825931ce5
3 changed files with 26 additions and 2 deletions

View file

@ -44,6 +44,8 @@ pub enum Opcode {
JMPF,
/// Jump backward
JMPB,
/// Allocate memory
ALOC,
NOP,
}
@ -67,6 +69,7 @@ impl From<u8> for Opcode {
14 => Opcode::LT,
15 => Opcode::JMPE,
16 => Opcode::NOP,
17 => Opcode::ALOC,
_ => Opcode::IGL,
}
}
@ -92,6 +95,7 @@ impl From<Opcode> for u8 {
Opcode::GT => 14,
Opcode::JMPE => 15,
Opcode::NOP => 16,
Opcode::ALOC => 17,
Opcode::IGL => 100,
}
}
@ -116,6 +120,7 @@ impl<'a> From<CompleteStr<'a>> for Opcode {
CompleteStr("lte") => Opcode::LTE,
CompleteStr("lt") => Opcode::LT,
CompleteStr("jmpe") => Opcode::JMPE,
CompleteStr("aloc") => Opcode::ALOC,
CompleteStr("nop") => Opcode::NOP,
_ => Opcode::IGL,
}

View file

@ -140,4 +140,4 @@ mod instruction_parser_test {
))
);
}
}
}

View file

@ -8,7 +8,9 @@ pub struct VM {
pc: usize,
/// The byte of the program being ran
pub program: Vec<u8>,
/// The remainer of the module used in the division opcode
/// Memory allocation
heap: Vec<u8>,
/// The remainder of the module used in the division opcode
remainder: u32,
/// The result of the last comparison operation
equal_flag: bool,
@ -21,6 +23,7 @@ impl VM {
registers: [0; 32],
pc: 0,
program: vec![],
heap: vec![],
remainder: 0,
equal_flag: false,
}
@ -204,6 +207,12 @@ impl VM {
self.next_8_bits();
self.next_8_bits();
}
Opcode::ALOC => {
let reg = self.next_8_bits() as usize;
let bytes = self.registers[reg];
let new_end = self.heap.len() as i32 + bytes;
self.heap.resize(new_end as usize, 0);
}
}
true
}
@ -260,6 +269,16 @@ mod vm_tests {
assert_eq!(vm.registers[2], 2);
}
#[test]
fn test_aloc_opcode()
{
let mut vm = get_test_vm();
vm.registers[0] = 1024;
vm.program = vec![17, 0, 0, 0];
vm.run_once();
assert_eq!(vm.heap.len(), 1024);
}
#[test]
fn test_eq_opcode() {
let mut vm = get_test_vm();