1
0
mirror of https://github.com/pevans/erc-c.git synced 2024-10-11 04:23:36 +00:00

Add error codes to segment functions

This commit is contained in:
Peter Evans 2017-12-09 15:16:56 -06:00
parent c4a6f77bcd
commit 850fdc55b5
4 changed files with 19 additions and 12 deletions

View File

@ -5,6 +5,12 @@
#define LOG_FILENAME "/tmp/emp.log"
enum log_errcode {
OK = 1,
ERR_OOM, // out of memory
ERR_OOB, // out of bounds
};
extern void log_write(int, const char *, ...);
extern void log_close();
extern void log_open(FILE *);

View File

@ -2,6 +2,7 @@
#define _VM_SEGMENT_H_
#include "vm_bits.h"
#include "log.h"
/*
* The bounds check is just some inline code to try and cut down on the
@ -22,10 +23,10 @@ typedef struct {
vm_8bit *memory;
} vm_segment;
extern void vm_segment_copy(vm_segment *, vm_segment *, size_t, size_t, size_t);
extern int vm_segment_copy(vm_segment *, vm_segment *, size_t, size_t, size_t);
extern vm_segment *vm_segment_create(size_t);
extern void vm_segment_free(vm_segment *);
extern vm_8bit vm_segment_get(vm_segment *, size_t);
extern void vm_segment_set(vm_segment *, size_t, vm_8bit);
extern int vm_segment_set(vm_segment *, size_t, vm_8bit);
#endif

View File

@ -58,7 +58,7 @@ vm_segment_free(vm_segment *segment)
* bounds-checking here will _crash_ the program if we are
* out-of-bounds.
*/
void
int
vm_segment_set(vm_segment *segment, size_t index, vm_8bit value)
{
// Some bounds checking.
@ -68,13 +68,11 @@ vm_segment_set(vm_segment *segment, size_t index, vm_8bit value)
index,
segment->size);
// We prefer to exit in this scenario, rather than try to
// "handle" it with an overflow, because we would rather a crash
// over ill-defined behavior.
exit(1);
return ERR_OOB;
}
segment->memory[index] = value;
return OK;
}
/*
@ -102,7 +100,7 @@ vm_segment_get(vm_segment *segment, size_t index)
* Copy a set of bytes from `src` (at `src_index`) to `dest` (at
* `dest_index`), such that the range is `length` bytes long.
*/
void
int
vm_segment_copy(vm_segment *dest,
vm_segment *src,
size_t dest_index,
@ -116,7 +114,7 @@ vm_segment_copy(vm_segment *dest,
length,
src->size);
exit(1);
return ERR_OOB;
}
if (dest_index + length >= dest->size) {
@ -126,10 +124,12 @@ vm_segment_copy(vm_segment *dest,
length,
dest->size);
exit(1);
return ERR_OOB;
}
memcpy(dest->memory + dest_index,
src->memory + src_index,
length * sizeof(src->memory[src_index]));
return OK;
}

View File

@ -23,7 +23,7 @@ Test(vm_segment, set) {
segment = vm_segment_create(length);
cr_assert_neq(segment, NULL);
vm_segment_set(segment, index, value);
cr_assert_eq(vm_segment_set(segment, index, value), OK);
cr_assert_eq(segment->memory[index], value);
vm_segment_free(segment);
@ -56,7 +56,7 @@ Test(vm_segment, copy) {
vm_segment_set(src, 2, 0xBE);
vm_segment_set(src, 3, 0xEF);
vm_segment_copy(dest, src, 8, 0, 4);
cr_assert_eq(vm_segment_copy(dest, src, 8, 0, 4), OK);
cr_assert_eq(vm_segment_get(dest, 8), 0xDE);
cr_assert_eq(vm_segment_get(dest, 9), 0xAD);