Last active
November 21, 2018 21:30
-
-
Save jotux/132a93a4bcd99def0356baa03210cce4 to your computer and use it in GitHub Desktop.
C++ array access with automatic dirty flag set.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdint.h> | |
using namespace std; | |
template<uint8_t N> | |
class Register | |
{ | |
private: | |
uint8_t data[N]; | |
class Proxy | |
{ | |
private: | |
Register<N>& parent; | |
uint8_t index; | |
public: | |
Proxy(Register<N>& p, uint8_t i) : parent(p), index(i){} | |
void operator=(uint8_t val) | |
{ | |
if (val != parent.data[index]) | |
{ | |
parent.dirty = true; | |
} | |
parent.data[index] = val; | |
} | |
operator uint8_t&() | |
{ | |
return parent.data[index]; | |
} | |
uint8_t operator++(int) | |
{ | |
parent.data[index]++; | |
parent.dirty = true; | |
return parent.data[index]; | |
} | |
uint8_t operator--(int) | |
{ | |
parent.data[index]--; | |
parent.dirty = true; | |
return parent.data[index]; | |
} | |
uint8_t operator+=(uint8_t val) | |
{ | |
parent.data[index] += val; | |
parent.dirty = true; | |
return parent.data[index]; | |
} | |
}; | |
public: | |
bool dirty; | |
Register<N>() | |
{ | |
memset(data,0,N); | |
dirty = false; | |
} | |
Proxy operator[](uint8_t index) | |
{ | |
return Proxy(*this,index); | |
} | |
void operator=(uint32_t val) | |
{ | |
if (N == 4) | |
{ | |
uint32_t old = reinterpret_cast<uint32_t&>(data); | |
memcpy(data,&val,4); | |
if (old != val) | |
{ | |
dirty = true; | |
} | |
} | |
} | |
operator uint32_t&() | |
{ | |
return reinterpret_cast<uint32_t&>(data); | |
} | |
}; | |
const uint8_t size = 4; | |
Register<size> sample; | |
void PrintData() | |
{ | |
printf("Data\n----\n"); | |
for (int i = 0;i < size;i++){printf("%d%s\n",(uint8_t)sample[i],sample.dirty?"~":"");} | |
} | |
int main() | |
{ | |
PrintData(); | |
sample[1] = 0; | |
PrintData(); | |
sample[1]++; | |
PrintData(); | |
sample[0] += (uint8_t)5; | |
PrintData(); | |
sample.dirty = false; | |
PrintData(); | |
sample = 0x04030201; | |
PrintData(); | |
uint32_t foo = (uint32_t)sample; | |
printf("Foo: 0x%x\n",foo); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment