c++/rgb-assembler/memory.h
author František Kučera <franta-hg@frantovo.cz>
Sun, 24 Dec 2017 00:30:54 +0100
changeset 29 10d6964e7b4a
parent 20 b9ceffdcaf14
child 31 b997cbf9e30b
permissions -rw-r--r--
license: GNU GPLv3+
     1 /**
     2  * RGB assembler
     3  * Copyright © 2017 František Kučera (frantovo.cz)
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, either version 3 of the License, or
     8  * (at your option) any later version.
     9  *
    10  * This program is distributed in the hope that it will be useful,
    11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  * GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License
    16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 
    19 #pragma once
    20 
    21 #include "types.h"
    22 
    23 const address_t MEMORY_SIZE = 1024;
    24 
    25 template<typename T> T logMemoryError(const address_t &index) {
    26 	wprintf(L"memory error: index = %d, sizeof(T) = %d, MEMORY_SIZE = %d\n", index, sizeof (T), MEMORY_SIZE);
    27 	// TODO: return error value or throw exception
    28 	return T();
    29 }
    30 
    31 /**
    32  * Reads data on given position in memory and increments the index (position).
    33  * 
    34  * @param memory array of bytes / octets
    35  * @param index offset in same units as memory type
    36  * @return value found at given position
    37  */
    38 template<typename T> T read(octet_t * memory, address_t &index) {
    39 	// TODO: map higher memory to static hardcoded areas or peripherals
    40 	if (index + sizeof (T) <= MEMORY_SIZE) {
    41 		T * value = reinterpret_cast<T*> (memory + index);
    42 		index += sizeof (T);
    43 		return *value;
    44 	} else {
    45 		return logMemoryError<T>(index);
    46 	}
    47 }
    48 
    49 /**
    50  * Writes data to given position in memory and increments the index (position).
    51  * @param memory array of bytes / octets
    52  * @param index offset in same units as memory type
    53  * @param value value to be written at given position
    54  */
    55 template<typename T> T write(octet_t * memory, address_t &index, const T value) {
    56 	if (index + sizeof (T) <= MEMORY_SIZE) {
    57 		T * m = reinterpret_cast<T*> (memory + index);
    58 		*m = value;
    59 		index += sizeof (value);
    60 	} else {
    61 		return logMemoryError<T>(index);
    62 	}
    63 }