Add helpers converting network-order (big-endian)

This commit is contained in:
Stephen Seo 2020-01-16 20:28:42 +09:00
parent 0170423a35
commit c37909bde3
3 changed files with 100 additions and 0 deletions

View file

@ -649,11 +649,21 @@ const char *UDPC_atostr_cid(UDPC_HContext ctx, UDPC_ConnectionId connectionId);
const char *UDPC_atostr(UDPC_HContext ctx, UDPC_IPV6_ADDR_TYPE addr);
// =============================================================================
// Helpers
/// addrStr must be a valid ipv6 address or a valid ipv4 address
UDPC_IPV6_ADDR_TYPE UDPC_strtoa(const char *addrStr);
UDPC_IPV6_ADDR_TYPE UDPC_strtoa_link(const char *addrStr, uint32_t *linkId_out);
int UDPC_is_big_endian();
uint16_t UDPC_no16i(uint16_t i);
uint32_t UDPC_no32i(uint32_t i);
uint64_t UDPC_no64i(uint64_t i);
float UDPC_no32f(float f);
double UDPC_no64f(double f);
#ifdef __cplusplus
}
#endif

View file

@ -2932,3 +2932,32 @@ UDPC_IPV6_ADDR_TYPE UDPC_strtoa_link(const char *addrStr, uint32_t *linkId_out)
checkSetOut(scope_id);
return result;
}
int UDPC_is_big_endian() {
return UDPC::isBigEndian() ? 1 : 0;
}
uint16_t UDPC_no16i(uint16_t i) {
return htons(i);
}
uint32_t UDPC_no32i(uint32_t i) {
return htonl(i);
}
uint64_t UDPC_no64i(uint64_t i) {
UDPC::be64((char*)&i);
return i;
}
float UDPC_no32f(float f) {
uint32_t *i = reinterpret_cast<uint32_t*>(&f);
*i = htonl(*i);
return f;
}
double UDPC_no64f(double f) {
uint64_t *i = reinterpret_cast<uint64_t*>(&f);
UDPC::be64((char*)i);
return f;
}

View file

@ -3,6 +3,7 @@
#include <UDPC.h>
#include <UDPC_Defines.hpp>
#include <cstdio>
#include <cstring>
#include <future>
@ -257,3 +258,63 @@ TEST(UDPC, ConnectionIdBits) {
EXPECT_EQ(((char*)&id)[i], 0);
}
}
TEST(UDPC, NetworkOrderEndianness) {
if(UDPC_is_big_endian() != 0) {
puts("Is big-endian");
uint16_t s = 0x0102;
s = UDPC_no16i(s);
EXPECT_EQ(s, 0x0102);
uint32_t l = 0x01020304;
l = UDPC_no32i(l);
EXPECT_EQ(l, 0x01020304);
uint64_t ll = 0x0102030405060708;
ll = UDPC_no64i(ll);
EXPECT_EQ(ll, 0x0102030405060708);
l = 0x40208040;
float *f = reinterpret_cast<float*>(&l);
*f = UDPC_no32f(*f);
EXPECT_EQ(l, 0x40208040);
ll = 0x4000001010008040;
double *d = reinterpret_cast<double*>(&ll);
*d = UDPC_no64f(*d);
EXPECT_EQ(ll, 0x4000001010008040);
} else {
puts("Is NOT big-endian");
uint16_t s = 0x0102;
s = UDPC_no16i(s);
EXPECT_EQ(s, 0x0201);
s = UDPC_no16i(s);
EXPECT_EQ(s, 0x0102);
uint32_t l = 0x01020304;
l = UDPC_no32i(l);
EXPECT_EQ(l, 0x04030201);
l = UDPC_no32i(l);
EXPECT_EQ(l, 0x01020304);
uint64_t ll = 0x0102030405060708;
ll = UDPC_no64i(ll);
EXPECT_EQ(ll, 0x0807060504030201);
ll = UDPC_no64i(ll);
EXPECT_EQ(ll, 0x0102030405060708);
l = 0x40208040;
float *f = reinterpret_cast<float*>(&l);
*f = UDPC_no32f(*f);
EXPECT_EQ(l, 0x40802040);
*f = UDPC_no32f(*f);
EXPECT_EQ(l, 0x40208040);
ll = 0x4000001010008040;
double *d = reinterpret_cast<double*>(&ll);
*d = UDPC_no64f(*d);
EXPECT_EQ(ll, 0x4080001010000040);
*d = UDPC_no64f(*d);
EXPECT_EQ(ll, 0x4000001010008040);
}
}