Some time ago I created a simple simulated computer. It had peripherals, a screen buffer that could be rendered for OpenGL texture, and several other neat features. It works, it works well, and overall I am quite pleased with it.
In addition, I cheated.
A suitable data type is a combination of integers, float, and type of instruction (divided into bit fields).
For any correct (simulated) program, the union is always used safely, only ever read from the last member of the association written in. However, the potential that a poorly formed program (for example, downloaded from a simulated hard drive) can gain access to members out of order can lead to common problems associated with union violence:
- The possibility that a record can be optimized at compile time - the compiler could not have enough information to attempt this optimization.
- A value read from a union can be garbage - this is perfectly acceptable behavior for me.
- A float read this way can be a signal-NaN / trap-value - this is a real problem - a malfunctioning simulated computer is OK, but a real program crash is a disaster.
- This is technically undefined behavior, so although it probably won't, it can cause the computer to crash, erase my hard drive, or cause Cthulhu.
Considered solutions:
- Adhering to the union - maybe it is well defined enough for all platforms of the real world? Maybe there are ways to misinform sNaNs?
- Tagged union - effectively reduce the amount of memory by half.
- A separately stored array of effectively packed tags is a slightly distorting tag, but otherwise somewhat viable. Array
- char - it seems simple, but the costs of using it safely, allowing you to read from a type other than the one that was written, really add up.
- The type of the integer type, as indicated above for the float and command, with the difference that the integers are trivial.
- char array plus separate registers integer and float are characteristic and in many respects ideal, but it will require me to write a compiler that could use them effectively.
I assume that this is the project that many SO users tried to do at one time or another, so the experience associated with specific problems is especially useful.
source share