On Tuesday, 12 March 2024 at 05:38:03 UTC, Liam McGillivray wrote:
I am in need of a data type for holding direction information;
one of 8 directions on a single axis. They are named in terms
of compass directions. If D had a 4-bit datatype, I would just
use this and do `+=2` whenever I want to change the datatype,
but it doesn't.
Perhaps this would be a good programming challenge for someone
more experienced than me. Make a data type (probably a struct)
for holding one of 8 directional values using 3 bits. It should
accept the use of increment operators to change the angle.
Ideally (but optionally), it should work as an enum of the same
name; "Direction".
Here's a unittest that it should ideally pass:
D actually supports both 3 and 4 bit integers. People will likely
warn you of minor portability risks... but if you target a
limited amount of platforms and prefer concise readable code,
then it's a text book example for bitfields. The risk can easily
be mitigated by having an unittest to catch the error directly(if
you try to port to some exotic platform).
dmd -preview=bitfields
(Some lines stolen from Rikki)
```d
struct Direction
{
private uint value : 3;
alias this = value;
enum Direction N = Direction(0);
enum Direction NE = Direction(1);
enum Direction E = Direction(2);
enum Direction SE = Direction(3);
enum Direction S = Direction(4);
enum Direction SW = Direction(5);
enum Direction W = Direction(6);
enum Direction NW = Direction(7);
}
```