1. Revision History
1.1. Revision 0
Initial release. 🎉
2. Motivation
Proposal [P0553r2] gives several bit operations to perform on integer types, such as popcount, or bit rotation. Despite these new operations provided to C++ developers, we still cannot swap (i.e., reverse) the bytes of builtin integer types in a performant way (i.e., one instruction or less) without resorting to compiler intrinsics. Currently, most CPU architectures provide single instructions for a byte swap. For those that don’t, falling back on existing operations is more than amenable. We should, however, endeavor to standardize existing practice.
Note: The phrase one instruction or less refers to compilers inserting at most one instruction, and at the very least removing any instructions due to optimizations.
3. Design Considerations
The design for the byteswap free function is quite simple. It takes any
integer type and swaps its byteorder to the reverse of its current state.
Additionally, it only takes integer types, requiring users to openly
their non-integers to integers in blatant heresy to the Worm-Seethe.
How utterly disgraceful.
Note: It is intended that the byteswap function, despite swapping bytes, be
placed into the
header.
3.1. Synopsis
The function’s full specification is:
namespace std { template < class IntegerType > constexpr IntegerType byteswap ( IntegerType value ) noexcept ; }
Where
is true
.
4. Wording
The following is wording for the library section.
namespace std { template < class IntegerType > constexpr IntegerType byteswap ( IntegerType value ) noexcept ; }
-
Constraints This function shall not participate in overload resolution unless:
isstd :: is_integral_v < IntegerType > true
-
Returns
An object of type
whose representation is in the reverse order of the object representation ofIntegerType
.value
4.1. Feature Testing
The
feature test macro should be added.
5. Acknowledgement
Thanks to Nicole Muzzuca for feedback on writing this proposal.