mirror of
https://github.com/ddnet/ddnet.git
synced 2024-11-10 01:58:19 +00:00
fix undefined behavior in byte packing functions, add tests
This commit is contained in:
parent
8d34626b5f
commit
0726703937
|
@ -2275,6 +2275,7 @@ if(GTEST_FOUND OR DOWNLOAD_GTEST)
|
|||
aio.cpp
|
||||
bezier.cpp
|
||||
blocklist_driver.cpp
|
||||
bytes_be.cpp
|
||||
color.cpp
|
||||
compression.cpp
|
||||
csv.cpp
|
||||
|
|
|
@ -3523,15 +3523,30 @@ const char *str_next_token(const char *str, const char *delim, char *buffer, int
|
|||
|
||||
int bytes_be_to_int(const unsigned char *bytes)
|
||||
{
|
||||
return ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff);
|
||||
int Result;
|
||||
unsigned char *pResult = (unsigned char *)&Result;
|
||||
for(unsigned i = 0; i < sizeof(int); i++)
|
||||
{
|
||||
#if defined(CONF_ARCH_ENDIAN_BIG)
|
||||
pResult[i] = bytes[i];
|
||||
#else
|
||||
pResult[i] = bytes[sizeof(int) - i - 1];
|
||||
#endif
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
void int_to_bytes_be(unsigned char *bytes, int value)
|
||||
{
|
||||
bytes[0] = (value >> 24) & 0xff;
|
||||
bytes[1] = (value >> 16) & 0xff;
|
||||
bytes[2] = (value >> 8) & 0xff;
|
||||
bytes[3] = value & 0xff;
|
||||
const unsigned char *pValue = (const unsigned char *)&value;
|
||||
for(unsigned i = 0; i < sizeof(int); i++)
|
||||
{
|
||||
#if defined(CONF_ARCH_ENDIAN_BIG)
|
||||
bytes[i] = pValue[i];
|
||||
#else
|
||||
bytes[sizeof(int) - i - 1] = pValue[i];
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
unsigned bytes_be_to_uint(const unsigned char *bytes)
|
||||
|
|
31
src/test/bytes_be.cpp
Normal file
31
src/test/bytes_be.cpp
Normal file
|
@ -0,0 +1,31 @@
|
|||
#include "test.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <base/system.h>
|
||||
|
||||
static const int INT_DATA[] = {0, 1, -1, 32, 64, 256, -512, 12345, -123456, 1234567, 12345678, 123456789, 2147483647, (-2147483647 - 1)};
|
||||
static const int INT_NUM = sizeof(INT_DATA) / sizeof(int);
|
||||
|
||||
static const unsigned UINT_DATA[] = {0u, 1u, 2u, 32u, 64u, 256u, 512u, 12345u, 123456u, 1234567u, 12345678u, 123456789u, 2147483647u, 2147483648u, 4294967295u};
|
||||
static const int UINT_NUM = sizeof(INT_DATA) / sizeof(unsigned);
|
||||
|
||||
TEST(BytePacking, RoundtripInt)
|
||||
{
|
||||
for(int i = 0; i < INT_NUM; i++)
|
||||
{
|
||||
unsigned char aPacked[4];
|
||||
int_to_bytes_be(aPacked, INT_DATA[i]);
|
||||
EXPECT_EQ(bytes_be_to_int(aPacked), INT_DATA[i]);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(BytePacking, RoundtripUnsigned)
|
||||
{
|
||||
for(int i = 0; i < UINT_NUM; i++)
|
||||
{
|
||||
unsigned char aPacked[4];
|
||||
uint_to_bytes_be(aPacked, UINT_DATA[i]);
|
||||
EXPECT_EQ(bytes_be_to_uint(aPacked), UINT_DATA[i]);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue