#include "window.h" #include static CodeResult outcome(int rc) { CodeResult result = {rc, 0, 0}; return result; } static int usable_slot(unsigned slot) { return slot < CW_SLOTS; } CodeResult window_install(CodeWorkbench *work, unsigned slot, const uint16_t *words, unsigned count) { if (!usable_slot(slot) || !program_valid(words, count)) { return outcome(CW_PROGRAM); } int rc = store_write(work, slot, 0, words, count); if (rc != CW_OK) { return outcome(rc); } rc = store_sync(work, slot, 0, count); if (rc != CW_OK) { return outcome(rc); } rc = store_publish(work, slot, count, CW_INSTALL); return outcome(rc); } static int prepare_edit(const CodeSlot *current, unsigned first, const uint16_t *words, unsigned count, uint16_t *merged) { if (count == 0 || first >= current->length) { return 0; } if (count > current->length - first) { return 0; } memcpy(merged, current->data, current->length * sizeof(*merged)); memcpy(merged + first, words, count * sizeof(*merged)); return program_valid(merged, current->length); } CodeResult window_patch(CodeWorkbench *work, unsigned slot, uint64_t expected, unsigned first, const uint16_t *words, unsigned count) { if (!usable_slot(slot)) { return outcome(CW_PROGRAM); } CodeSlot *current = &work->slots[slot]; if (!current->active) { return outcome(CW_INACTIVE); } if (expected != work->counts.serial) { return outcome(CW_CONFLICT); } uint16_t merged[CW_CAPACITY]; if (!prepare_edit(current, first, words, count, merged)) { return outcome(CW_PROGRAM); } int rc = store_write(work, slot, first, words, count); if (rc != CW_OK) { return outcome(rc); } rc = store_sync(work, slot, first, first + count); if (rc != CW_OK) { return outcome(rc); } rc = store_publish(work, slot, current->length, CW_PATCH); return outcome(rc); } CodeResult window_drop(CodeWorkbench *work, unsigned slot, uint64_t expected) { if (!usable_slot(slot)) { return outcome(CW_PROGRAM); } CodeSlot *current = &work->slots[slot]; if (!current->active) { return outcome(CW_INACTIVE); } if (expected != current->generation) { return outcome(CW_CONFLICT); } return outcome(store_publish(work, slot, 0, CW_DROP)); } CodeResult window_execute(CodeWorkbench *work, unsigned slot, uint32_t input) { if (!usable_slot(slot)) { return outcome(CW_PROGRAM); } const CodeSlot *current = &work->slots[slot]; if (!current->active) { return outcome(CW_INACTIVE); } work->counts.executions += 1; return interpret(current->execution, current->length, input); }