Endianness - How to test code for portability
Preetpal
preetpal.sohal at gmail.com
Fri Mar 12 17:03:31 UTC 2021
On Friday, 12 March 2021 at 10:26:55 UTC, Dennis wrote:
> ```
> version(BigEndian) {
> private enum bigEndian = true;
> } else {
> private enum bigEndian = false;
> }
>
> int parse(in ubyte[] data) {
> if (__ctfe || bigEndian) {
> // Portable code
> } else {
> // Little-endian optimized code
> }
> }
> ```
>
> Then you can test both at runtime and compile time:
> ```
> unittest {
> ubyte[] testData = [...];
> assert(parse(testData) == 3);
> static assert(parse(testData) == 3);
> }
> ```
>
> So no, I don't have a big-endian computer I can test it on, but
> I do test with CTFE, so I'm pretty sure I'm not relying on a
> specific byte order.
I never even thought of using CTFE for this purpose. Using CTFE
to test cases you cannot simulate using runtime testing is a
really great idea.
More information about the Digitalmars-d-learn
mailing list