From 4c982b2ffe99f5dee70657424161de9541e00a21 Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Sat, 29 Oct 2022 16:49:12 +0200 Subject: serialize: use std::bit_cast --- serialize/binary-reader.inl | 48 ++++++++++----------------------------------- 1 file changed, 10 insertions(+), 38 deletions(-) (limited to 'serialize/binary-reader.inl') diff --git a/serialize/binary-reader.inl b/serialize/binary-reader.inl index 0c5b8531..b190f463 100644 --- a/serialize/binary-reader.inl +++ b/serialize/binary-reader.inl @@ -16,24 +16,16 @@ constexpr binary_reader::binary_reader(It begin, It end) noexcept : {} template -template -constexpr value_u binary_reader::read_u() noexcept +template +constexpr T binary_reader::read() noexcept { - value_u buf; - static_assert(sizeof(T) <= sizeof(buf)); - fm_assert(std::distance(it, end) >= sizeof(T)); - num_bytes_read += sizeof(T); - for (int i = 0; i < sizeof(T); i++) - buf.bytes[i] = *it++; - return buf; -} - -template -template -T binary_reader::read() noexcept -{ - value_u buf = read_u(); - return *reinterpret_cast(buf.bytes); + constexpr std::size_t N = sizeof(T); + fm_assert((std::ptrdiff_t)N <= std::distance(it, end)); + num_bytes_read += N; + char buf[N]; + for (std::size_t i = 0; i < N; i++) + buf[i] = *it++; + return maybe_byteswap(std::bit_cast(buf)); } template @@ -56,26 +48,6 @@ constexpr void binary_reader::assert_end() noexcept fm_assert(it == end); } -template -template -constexpr value_u binary_reader::read_u() noexcept -{ - value_u buf; - if (std::is_constant_evaluated()) - for (std::size_t i = 0; i < std::size(buf.bytes); i++) - buf.bytes[i] = 0; - static_assert(sizeof(T) <= sizeof(buf)); - fm_assert((std::ptrdiff_t)sizeof(T) <= std::distance(it, end)); - num_bytes_read += sizeof(T); - if constexpr(std::endian::native == std::endian::big) - for (int i = sizeof(T) - 1; i >= 0; i--) - buf.bytes[i] = *it++; - else - for (std::size_t i = 0; i < sizeof(T); i++) - buf.bytes[i] = *it++; - return buf; -} - template binary_reader& operator>>(binary_reader& reader, T& x) noexcept { @@ -85,7 +57,7 @@ binary_reader& operator>>(binary_reader& reader, T& x) noexcept template template -auto binary_reader::read_asciiz_string() noexcept +constexpr auto binary_reader::read_asciiz_string() noexcept { static_assert(MAX > 0); -- cgit v1.2.3