summaryrefslogtreecommitdiffhomepage
path: root/serialize/binary-serializer.inl
diff options
context:
space:
mode:
Diffstat (limited to 'serialize/binary-serializer.inl')
-rw-r--r--serialize/binary-serializer.inl33
1 files changed, 28 insertions, 5 deletions
diff --git a/serialize/binary-serializer.inl b/serialize/binary-serializer.inl
index 35b7ddc7..d16504e6 100644
--- a/serialize/binary-serializer.inl
+++ b/serialize/binary-serializer.inl
@@ -1,6 +1,6 @@
#pragma once
-
#include "binary-serializer.hpp"
+#include "compat/assert.hpp"
namespace floormat::Serialize {
@@ -70,17 +70,28 @@ constexpr inline T maybe_byteswap(T x)
}
template<std::output_iterator<char> It>
-constexpr binary_writer<It>::binary_writer(It it) noexcept : it{it} {}
+constexpr binary_writer<It>::binary_writer(It it) noexcept : it{it}, _bytes_written{0} {}
template<std::output_iterator<char> It>
template<integer T>
-void binary_writer<It>::write(T x) noexcept
+constexpr void binary_writer<It>::write(T x) noexcept
{
union {
T datum;
char bytes[sizeof(T)];
} buf;
- buf.datum = maybe_byteswap(x);
+
+ if (std::is_constant_evaluated())
+ for (std::size_t i = 0; i < std::size(buf.bytes); i++)
+ buf.bytes[i] = 0;
+ _bytes_written += sizeof(T);
+ if constexpr(sizeof(T) == 1)
+ buf.bytes[0] = (char)x;
+ else if (!std::is_constant_evaluated())
+ buf.datum = maybe_byteswap(x);
+ else
+ for (std::size_t i = 0; i < sizeof(T); x >>= 8, i++)
+ buf.bytes[i] = (char)(unsigned char)x;
for (std::size_t i = 0; i < sizeof(T); i++)
*it++ = buf.bytes[i];
}
@@ -93,6 +104,7 @@ void binary_writer<It>::write(T x) noexcept
T datum;
char bytes[sizeof(T)];
} buf;
+ _bytes_written += sizeof(T);
buf.datum = maybe_byteswap(x);
for (std::size_t i = 0; i < sizeof(T); i++)
*it++ = buf.bytes[i];
@@ -107,12 +119,23 @@ binary_reader<It>& operator>>(binary_reader<It>& reader, T& x) noexcept
}
template<std::output_iterator<char> It, serializable T>
-binary_writer<It>& operator<<(binary_writer<It>& writer, T x) noexcept
+constexpr binary_writer<It>& operator<<(binary_writer<It>& writer, T x) noexcept
{
writer.template write<T>(x);
return writer;
}
+template<std::output_iterator<char> It>
+constexpr void binary_writer<It>::write_asciiz_string(StringView str) noexcept
+{
+ fm_assert_debug(str.flags() & StringViewFlag::NullTerminated);
+ const auto sz = str.size();
+ _bytes_written += sz + 1;
+ for (std::size_t i = 0; i < sz; i++)
+ *it++ = str[i];
+ *it++ = '\0';
+}
+
} // namespace floormat::Serialize