byte swapping
All checks were successful
Linux arm64 / Build (push) Successful in 15s

This commit is contained in:
2025-06-26 14:43:27 +02:00
parent 10b49b34dd
commit 073872df94
11 changed files with 168 additions and 178 deletions

View File

@@ -1,27 +1,21 @@
#include <sp/common/ByteSwapping.h>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#include <endian.h>
#define htonll htobe64
#define ntohll be64toh
#endif
#include <algorithm>
namespace sp {
template <typename T>
void SwapBytes(T& value) {
char* ptr = reinterpret_cast<char*>(&value);
std::reverse(ptr, ptr + sizeof(T));
}
bool IsSystemBigEndian() {
static constexpr std::uint16_t test = 10;
static const bool isBigEndian = reinterpret_cast<const std::uint8_t*>(&test)[1] == 10;
return isBigEndian;
}
template <>
void ToNetwork<std::uint16_t>(std::uint16_t& value) {
value = htons(value);
@@ -34,9 +28,7 @@ void ToNetwork<std::uint32_t>(std::uint32_t& value) {
template <>
void ToNetwork<std::uint64_t>(std::uint64_t& value) {
if (IsSystemBigEndian())
return;
SwapBytes(value);
value = htonll(value);
}
template <>
@@ -51,24 +43,7 @@ void FromNetwork<std::uint32_t>(std::uint32_t& value) {
template <>
void FromNetwork<std::uint64_t>(std::uint64_t& value) {
if (IsSystemBigEndian())
return;
SwapBytes(value);
}
template <>
void TrySwapBytes<std::uint16_t>(std::uint16_t& value) {
SwapBytes(value);
}
template <>
void TrySwapBytes<std::uint32_t>(std::uint32_t& value) {
SwapBytes(value);
}
template <>
void TrySwapBytes<std::uint64_t>(std::uint64_t& value) {
SwapBytes(value);
value = ntohll(value);
}
} // namespace sp