- Implemented `toBytes(T)(T)`

Utils (unittest)

- Added unit test for the above
This commit is contained in:
Tristan B. Velloza Kildaire 2023-09-29 10:50:57 +02:00
parent 4b88e34d4b
commit f71f9e9594
1 changed files with 61 additions and 0 deletions

View File

@ -202,4 +202,65 @@ unittest
ubyte[] values = [1,2,3];
ubyte free = findNextFree(values);
assert(isPresent(values, free) == false);
}
/**
* Converts the given integral value to
* its byte encoding
*
* Params:
* integral = the integral value
* Returns: a `ubyte[]` of the value
*/
public ubyte[] toBytes(T)(T integral) if(__traits(isIntegral, T))
{
ubyte[] bytes;
static if(integral.sizeof == 1)
{
bytes = [cast(ubyte)integral];
}
else static if(integral.sizeof == 2)
{
ubyte* ptrBase = cast(ubyte*)&integral;
bytes = [*ptrBase, *(ptrBase+1)];
}
else static if(integral.sizeof == 4)
{
ubyte* ptrBase = cast(ubyte*)&integral;
bytes = [*ptrBase, *(ptrBase+1), *(ptrBase+2), *(ptrBase+3)];
}
else static if(integral.sizeof == 8)
{
ubyte* ptrBase = cast(ubyte*)&integral;
bytes = [*ptrBase, *(ptrBase+1), *(ptrBase+2), *(ptrBase+3), *(ptrBase+4), *(ptrBase+5), *(ptrBase+6), *(ptrBase+7)];
}
else
{
pragma(msg, "toBytes cannot support integral types greater than 8 bytes");
static assert(false);
}
return bytes;
}
/**
* Tests the `toBytes!(T)(T)` function
*/
unittest
{
version(LittleEndian)
{
ulong value = 1;
ubyte[] bytes = toBytes(value);
assert(bytes == [1, 0, 0, 0, 0, 0, 0, 0]);
}
else version(BigEndian)
{
ulong value = 1;
ubyte[] bytes = toBytes(value);
assert(bytes == [0, 0, 0, 0, 0, 0, 0, 1]);
}
}