Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
poor-circle committed Nov 21, 2023
1 parent a00ff4b commit 9852956
Showing 1 changed file with 26 additions and 19 deletions.
45 changes: 26 additions & 19 deletions include/ylt/struct_pack/endian_wrapper.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ void low_bytes_write_wrapper(writer_t& writer, const T& elem) {
}
else {
const char* SP_RESTRICT data = sizeof(T) - block_size + (const char*)&elem;
if constexpr (block_size == 2) {
if constexpr (block_size == 1) {
writer.write((char*)&data, block_size);
}
else if constexpr (block_size == 2) {
auto tmp = bswap16(*(uint16_t*)data);
writer.write((char*)&tmp, block_size);
}
Expand All @@ -188,7 +191,7 @@ void low_bytes_write_wrapper(writer_t& writer, const T& elem) {
}
else {
static_assert(!sizeof(writer),
"illegal block size(should be 1,2,4,8,16)");
"illegal block size(should be 1,2,4,8)");
}
}
}
Expand Down Expand Up @@ -234,31 +237,35 @@ bool read_bytes_array(reader_t& reader, char* SP_RESTRICT data,
template <std::size_t block_size, typename reader_t, typename T>
bool low_bytes_read_wrapper(reader_t& reader, T& elem) {
static_assert(sizeof(T) >= block_size);
if constexpr (is_system_little_endian || block_size == sizeof(T) ||
block_size == 1) {
if constexpr (is_system_little_endian || block_size == sizeof(T)) {
char* SP_RESTRICT data = (char*)&elem;
return static_cast<bool>(reader.read(data, block_size));
}
else {
char tmp[block_size];
char* SP_RESTRICT data = (char*)&elem + sizeof(T) - block_size;
bool res = static_cast<bool>(reader.read(tmp, block_size));
if SP_UNLIKELY (!res) {
return res;
}
if constexpr (block_size == 2) {
*(uint16_t*)data = bswap16(*(uint16_t*)tmp);
}
else if constexpr (block_size == 4) {
*(uint32_t*)data = bswap32(*(uint32_t*)tmp);
}
else if constexpr (block_size == 8) {
*(uint64_t*)data = bswap64(*(uint64_t*)tmp);
if constexpr (block_size > 1) {
char tmp[block_size];
bool res = static_cast<bool>(reader.read(tmp, block_size));
if SP_UNLIKELY (!res) {
return res;
}
if constexpr (block_size == 2) {
*(uint16_t*)data = bswap16(*(uint16_t*)tmp);
}
else if constexpr (block_size == 4) {
*(uint32_t*)data = bswap32(*(uint32_t*)tmp);
}
else if constexpr (block_size == 8) {
*(uint64_t*)data = bswap64(*(uint64_t*)tmp);
}
else {
static_assert(!sizeof(reader), "illegal block size(should be 1,2,4,8)");
}
return true;
}
else {
static_assert(!sizeof(reader), "illegal block size(should be 1,2,4,8)");
reader.read(data, block_size);
}
return true;
}
}
}; // namespace struct_pack::detail

0 comments on commit 9852956

Please sign in to comment.