-struct EndianInt : public detail::EndianIntBase<T> {
- public:
- static T big(T x) { return EndianInt::swap(x); }
- static T little(T x) { return x; }
-};
-
-#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
-
-template <class T>
-struct EndianInt : public detail::EndianIntBase<T> {
- public:
- static T big(T x) { return x; }
- static T little(T x) { return EndianInt::swap(x); }
+struct EndianInt {
+ static_assert(
+ (std::is_integral<T>::value && !std::is_same<T, bool>::value) ||
+ std::is_floating_point<T>::value,
+ "template type parameter must be non-bool integral or floating point");
+ static T swap(T x) {
+ // we implement this with memcpy because that is defined behavior in C++
+ // we rely on compilers to optimize away the memcpy calls
+ constexpr auto s = sizeof(T);
+ using B = typename uint_types_by_size<s>::type;
+ B b;
+ std::memcpy(&b, &x, s);
+ b = byteswap_gen(b);
+ std::memcpy(&x, &b, s);
+ return x;
+ }
+ static T big(T x) {
+ return kIsLittleEndian ? EndianInt::swap(x) : x;
+ }
+ static T little(T x) {
+ return kIsBigEndian ? EndianInt::swap(x) : x;
+ }