From 1b22980cb57576955423a1778ede1f7c106085e2 Mon Sep 17 00:00:00 2001 From: Tomi Valkeinen Date: Fri, 2 Dec 2022 12:43:31 +0200 Subject: kms++util: Add endian.h Add simple endianness supporting write function, and, for now, only one shortcut helper, write16le(). Signed-off-by: Tomi Valkeinen Reviewed-by: Laurent Pinchart --- kms++util/inc/kms++util/endian.h | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 kms++util/inc/kms++util/endian.h (limited to 'kms++util') diff --git a/kms++util/inc/kms++util/endian.h b/kms++util/inc/kms++util/endian.h new file mode 100644 index 0000000..0f7aecd --- /dev/null +++ b/kms++util/inc/kms++util/endian.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include + +static_assert((__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || + (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__), + "Unable to detect endianness"); + +enum class endian { + little = __ORDER_LITTLE_ENDIAN__, + big = __ORDER_BIG_ENDIAN__, + native = __BYTE_ORDER__ +}; + +template +constexpr T byteswap(T value) noexcept +{ + static_assert(std::is_integral(), "Type is not integral"); + static_assert(sizeof(T) == 2 || + sizeof(T) == 4 || + sizeof(T) == 8, + "Illegal value size"); + + switch (sizeof(T)) { + case 2: return bswap_16(value); + case 4: return bswap_32(value); + case 8: return bswap_64(value); + } +} + +template +static void write_endian(T* dst, T val) +{ + if constexpr (E != endian::native) + val = byteswap(val); + + *dst = val; +} + +[[maybe_unused]] +static void write16le(uint16_t* dst, uint16_t val) +{ + write_endian(dst, val); +} -- cgit v1.2.3