Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions changelog/bit-cast.dd
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Added `std.conv.bitCast`

This convenience function allows reinterpreting casts to be written in a more
readable way.

---
uint n = 0xDEADBEEF;

// Before
writeln("Bytes of n are: ", *cast(const ubyte[4]*) &n);

// After
writeln("Bytes of n are: ", n.bitCast!(const ubyte[4]));
---
36 changes: 36 additions & 0 deletions std/conv.d
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ $(TR $(TD Generic) $(TD
$(LREF parse)
$(LREF to)
$(LREF toChars)
$(LREF bitCast)
))
$(TR $(TD Strings) $(TD
$(LREF text)
Expand Down Expand Up @@ -6047,3 +6048,38 @@ package enum toCtString(ulong n) = n.stringof[0 .. $ - "LU".length];
assert(toCtString!0 == "0");
assert(toCtString!123456 == "123456");
}

/**
* Takes the raw bits of a value and reinterprets them as a different type.
*
* Params:
* T = the new type.
* value = the value to reinterpret.
*
* Returns: a reference to the reinterpreted value.
*/
pragma(inline, true)
ref T bitCast(T, S)(ref S value)
if (T.sizeof <= S.sizeof)
{
return *cast(T*) &value;
}

///
@safe unittest
{
uint n = 0xDEADBEEF;

version (LittleEndian)
assert(n.bitCast!(ubyte[4]) == [0xEF, 0xBE, 0xAD, 0xDE]);
version (BigEndian)
assert(n.bitCast!(ubyte[4]) == [0xDE, 0xAD, 0xBE, 0xEF]);
}

// Sizes must be compatible
@safe unittest
{
uint n;

assert(!__traits(compiles, n.bitCast!ulong));
}
Loading