|
| 1 | +// Copyright 2013 The Flutter Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +#ifndef FLUTTER_FML_ENDIANNESS_H_ |
| 6 | +#define FLUTTER_FML_ENDIANNESS_H_ |
| 7 | + |
| 8 | +#include <cstdint> |
| 9 | +#include <type_traits> |
| 10 | +#if defined(_MSC_VER) |
| 11 | +#include "intrin.h" |
| 12 | +#endif |
| 13 | + |
| 14 | +#include "flutter/fml/build_config.h" |
| 15 | + |
| 16 | +// Compiler intrinsics for flipping endianness. |
| 17 | +#define FML_BYTESWAP_16(n) __builtin_bswap16(n) |
| 18 | +#define FML_BYTESWAP_32(n) __builtin_bswap32(n) |
| 19 | +#define FML_BYTESWAP_64(n) __builtin_bswap64(n) |
| 20 | + |
| 21 | +#if defined(_MSC_VER) |
| 22 | +#define FML_BYTESWAP_16(n) _byteswap_ushort(n) |
| 23 | +#define FML_BYTESWAP_32(n) _byteswap_ulong(n) |
| 24 | +#define FML_BYTESWAP_64(n) _byteswap_uint64(n) |
| 25 | +#endif |
| 26 | + |
| 27 | +namespace fml { |
| 28 | + |
| 29 | +/// @brief Flips the endianness of the given value. |
| 30 | +/// The given value must be an integral type of size 1, 2, 4, or 8. |
| 31 | +template <typename T, class = std::enable_if_t<std::is_integral_v<T>>> |
| 32 | +constexpr T ByteSwap(T n) { |
| 33 | + if constexpr (sizeof(T) == 1) { |
| 34 | + return n; |
| 35 | + } else if constexpr (sizeof(T) == 2) { |
| 36 | + return (T)FML_BYTESWAP_16((uint16_t)n); |
| 37 | + } else if constexpr (sizeof(T) == 4) { |
| 38 | + return (T)FML_BYTESWAP_32((uint32_t)n); |
| 39 | + } else if constexpr (sizeof(T) == 8) { |
| 40 | + return (T)FML_BYTESWAP_64((uint64_t)n); |
| 41 | + } else { |
| 42 | + static_assert(!sizeof(T), "Unsupported size"); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/// @brief Convert a known big endian value to match the endianness of the |
| 47 | +/// current architecture. This is effectively a cross platform |
| 48 | +/// ntohl/ntohs (as network byte order is always Big Endian). |
| 49 | +/// The given value must be an integral type of size 1, 2, 4, or 8. |
| 50 | +template <typename T, class = std::enable_if_t<std::is_integral_v<T>>> |
| 51 | +constexpr T BigEndianToArch(T n) { |
| 52 | +#if ARCH_CPU_LITTLE_ENDIAN |
| 53 | + return ByteSwap<T>(n); |
| 54 | +#else |
| 55 | + return n; |
| 56 | +#endif |
| 57 | +} |
| 58 | + |
| 59 | +/// @brief Convert a known little endian value to match the endianness of the |
| 60 | +/// current architecture. |
| 61 | +/// The given value must be an integral type of size 1, 2, 4, or 8. |
| 62 | +template <typename T, class = std::enable_if_t<std::is_integral_v<T>>> |
| 63 | +constexpr T LittleEndianToArch(T n) { |
| 64 | +#if !ARCH_CPU_LITTLE_ENDIAN |
| 65 | + return ByteSwap<T>(n); |
| 66 | +#else |
| 67 | + return n; |
| 68 | +#endif |
| 69 | +} |
| 70 | + |
| 71 | +} // namespace fml |
| 72 | + |
| 73 | +#endif // FLUTTER_FML_ENDIANNESS_H_ |
0 commit comments