#include "window.h" static unsigned opcode(uint16_t word) { return word >> 8; } static unsigned operand(uint16_t word) { return word & 255u; } int instruction_valid(uint16_t word, int last) { unsigned op = opcode(word); unsigned byte = operand(word); if (last) { return op == 0 && byte == 0; } if (op == 0 || op > 6) { return 0; } if (op == 4 && byte > 31) { return 0; } return 1; } int program_valid(const uint16_t *words, unsigned count) { if (words == NULL || count == 0 || count > CW_CAPACITY) { return 0; } for (unsigned index = 0; index < count; ++index) { if (!instruction_valid(words[index], index + 1 == count)) { return 0; } } return 1; } static uint32_t signed_operand(unsigned byte) { if (byte < 128) { return byte; } return UINT32_MAX - (255u - byte); } static uint32_t rotate_left(uint32_t value, unsigned bits) { if (bits == 0) { return value; } return (value << bits) | (value >> (32u - bits)); } static uint32_t apply_instruction(uint32_t accumulator, uint16_t word) { unsigned byte = operand(word); switch (opcode(word)) { case 1: return accumulator + signed_operand(byte); case 2: return accumulator ^ byte; case 3: return accumulator * byte; case 4: return rotate_left(accumulator, byte); case 5: return signed_operand(byte); case 6: return accumulator & byte; default: return accumulator; } } CodeResult interpret(const uint16_t *words, unsigned count, uint32_t input) { CodeResult result = {CW_OK, input, 0}; if (words == NULL || count == 0 || count > CW_CAPACITY) { result.rc = CW_EXECUTION; result.value = 0; return result; } for (unsigned index = 0; index < count; ++index) { uint16_t word = words[index]; result.retired += 1; if (!instruction_valid(word, index + 1 == count)) { result.rc = CW_EXECUTION; result.value = 0; return result; } if (opcode(word) != 0) { result.value = apply_instruction(result.value, word); } } return result; }