c++/rgb-assembler/memory.h
author František Kučera <franta-hg@frantovo.cz>
Sat, 23 Dec 2017 23:24:51 +0100
changeset 20 b9ceffdcaf14
child 29 10d6964e7b4a
permissions -rw-r--r--
move memory functions to a header file + introduce Command classes
franta-hg@20
     1
#pragma once
franta-hg@20
     2
franta-hg@20
     3
#include "types.h"
franta-hg@20
     4
franta-hg@20
     5
const address_t MEMORY_SIZE = 1024;
franta-hg@20
     6
franta-hg@20
     7
template<typename T> T logMemoryError(const address_t &index) {
franta-hg@20
     8
	wprintf(L"memory error: index = %d, sizeof(T) = %d, MEMORY_SIZE = %d\n", index, sizeof (T), MEMORY_SIZE);
franta-hg@20
     9
	// TODO: return error value or throw exception
franta-hg@20
    10
	return T();
franta-hg@20
    11
}
franta-hg@20
    12
franta-hg@20
    13
/**
franta-hg@20
    14
 * Reads data on given position in memory and increments the index (position).
franta-hg@20
    15
 * 
franta-hg@20
    16
 * @param memory array of bytes / octets
franta-hg@20
    17
 * @param index offset in same units as memory type
franta-hg@20
    18
 * @return value found at given position
franta-hg@20
    19
 */
franta-hg@20
    20
template<typename T> T read(octet_t * memory, address_t &index) {
franta-hg@20
    21
	// TODO: map higher memory to static hardcoded areas or peripherals
franta-hg@20
    22
	if (index + sizeof (T) <= MEMORY_SIZE) {
franta-hg@20
    23
		T * value = reinterpret_cast<T*> (memory + index);
franta-hg@20
    24
		index += sizeof (T);
franta-hg@20
    25
		return *value;
franta-hg@20
    26
	} else {
franta-hg@20
    27
		return logMemoryError<T>(index);
franta-hg@20
    28
	}
franta-hg@20
    29
}
franta-hg@20
    30
franta-hg@20
    31
/**
franta-hg@20
    32
 * Writes data to given position in memory and increments the index (position).
franta-hg@20
    33
 * @param memory array of bytes / octets
franta-hg@20
    34
 * @param index offset in same units as memory type
franta-hg@20
    35
 * @param value value to be written at given position
franta-hg@20
    36
 */
franta-hg@20
    37
template<typename T> T write(octet_t * memory, address_t &index, const T value) {
franta-hg@20
    38
	if (index + sizeof (T) <= MEMORY_SIZE) {
franta-hg@20
    39
		T * m = reinterpret_cast<T*> (memory + index);
franta-hg@20
    40
		*m = value;
franta-hg@20
    41
		index += sizeof (value);
franta-hg@20
    42
	} else {
franta-hg@20
    43
		return logMemoryError<T>(index);
franta-hg@20
    44
	}
franta-hg@20
    45
}