1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/c++/rgb-assembler/memory.h Sat Dec 23 23:24:51 2017 +0100
1.3 @@ -0,0 +1,45 @@
1.4 +#pragma once
1.5 +
1.6 +#include "types.h"
1.7 +
1.8 +const address_t MEMORY_SIZE = 1024;
1.9 +
1.10 +template<typename T> T logMemoryError(const address_t &index) {
1.11 + wprintf(L"memory error: index = %d, sizeof(T) = %d, MEMORY_SIZE = %d\n", index, sizeof (T), MEMORY_SIZE);
1.12 + // TODO: return error value or throw exception
1.13 + return T();
1.14 +}
1.15 +
1.16 +/**
1.17 + * Reads data on given position in memory and increments the index (position).
1.18 + *
1.19 + * @param memory array of bytes / octets
1.20 + * @param index offset in same units as memory type
1.21 + * @return value found at given position
1.22 + */
1.23 +template<typename T> T read(octet_t * memory, address_t &index) {
1.24 + // TODO: map higher memory to static hardcoded areas or peripherals
1.25 + if (index + sizeof (T) <= MEMORY_SIZE) {
1.26 + T * value = reinterpret_cast<T*> (memory + index);
1.27 + index += sizeof (T);
1.28 + return *value;
1.29 + } else {
1.30 + return logMemoryError<T>(index);
1.31 + }
1.32 +}
1.33 +
1.34 +/**
1.35 + * Writes data to given position in memory and increments the index (position).
1.36 + * @param memory array of bytes / octets
1.37 + * @param index offset in same units as memory type
1.38 + * @param value value to be written at given position
1.39 + */
1.40 +template<typename T> T write(octet_t * memory, address_t &index, const T value) {
1.41 + if (index + sizeof (T) <= MEMORY_SIZE) {
1.42 + T * m = reinterpret_cast<T*> (memory + index);
1.43 + *m = value;
1.44 + index += sizeof (value);
1.45 + } else {
1.46 + return logMemoryError<T>(index);
1.47 + }
1.48 +}