1. Revision History
1.1. Revision 4
-
Fix typos and missing words
-
Fix feature test macro definition
-
Do not use abbreviated function syntax.
1.2. Revision 3
-
Update wording to use C++20 features
1.3. Revision 2
-
Add missing remarks of undefined behavior in cases such as byteswapping an
such as a bitfield.IntegerType -
Update feature macro value for the Cologne 2019 meeting
1.4. Revision 1
-
Update wording based on feedback from CWG regarding the representation of the "reversed" object.
-
Update wording based on feedback from LWG subclause location and grammatical changes
-
Readjust wording to use [N4820] library wording constructs instead of [N4672]
1.5. 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 { constexpr auto byteswap ( integral auto value ) noexcept ; }
4. Wording
The following synopsis is to be added to subclause 25.5.2 Header Synopsis [bit.syn]:
The following is to be placed before the current subclause 25.5.4 [bit.pow.two] into [bit.byteswap]:
The following modification in 26.5.3 [bit.cast]:
Returns: An object of typetemplate < typename To , typename From > constexpr To bit_cast ( const From & from ) noexcept ; . Each bit of the value representation of the result is equal to the corresponding bit in the object representation ofTo . Padding bits of thefrom object are unspecified. If there is no value of typeTo corresponding to the value representation produced, the behavior is undefined. If there are multiple such values, which value is produced is unspecified.To
4.1. Feature Testing
Add a new macro in set to the date of adoption.
The macro is also present in .
5. Acknowledgement
Thanks to Nicole Mazzuca for feedback on writing this proposal.