From fd19f2e15313fba83e971f49092f5511ac610584 Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Thu, 27 Oct 2022 19:46:44 +0200 Subject: more serializer work --- serialize/binary-serializer.inl | 44 +++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 15 deletions(-) (limited to 'serialize/binary-serializer.inl') diff --git a/serialize/binary-serializer.inl b/serialize/binary-serializer.inl index 200622f4..35b7ddc7 100644 --- a/serialize/binary-serializer.inl +++ b/serialize/binary-serializer.inl @@ -60,8 +60,8 @@ constexpr value_u binary_reader::read_u() noexcept return buf; } -template -[[maybe_unused]] constexpr inline T maybe_byteswap(T x) +template +constexpr inline T maybe_byteswap(T x) { if constexpr(std::endian::native == std::endian::big) return std::byteswap(x); @@ -69,34 +69,48 @@ template return x; } -template -binary_reader& operator>>(binary_reader& reader, T x) noexcept -{ - value_u u = reader.template read(); - x = *reinterpret_cast(&u.bytes[0]); - return reader; -} - template It> constexpr binary_writer::binary_writer(It it) noexcept : it{it} {} template It> -template +template void binary_writer::write(T x) noexcept { union { T datum; char bytes[sizeof(T)]; } buf; - buf.datum = x; + buf.datum = maybe_byteswap(x); for (std::size_t i = 0; i < sizeof(T); i++) *it++ = buf.bytes[i]; -}; +} -template It, serializable T> -binary_writer& operator>>(binary_writer& writer, T x) noexcept +template It> +template +void binary_writer::write(T x) noexcept { + union { + T datum; + char bytes[sizeof(T)]; + } buf; + buf.datum = maybe_byteswap(x); + for (std::size_t i = 0; i < sizeof(T); i++) + *it++ = buf.bytes[i]; +} +template +binary_reader& operator>>(binary_reader& reader, T& x) noexcept +{ + value_u u = reader.template read(); + x = *reinterpret_cast(&u.bytes[0]); + return reader; +} + +template It, serializable T> +binary_writer& operator<<(binary_writer& writer, T x) noexcept +{ + writer.template write(x); + return writer; } } // namespace floormat::Serialize -- cgit v1.2.3