Skip to content

Commit

Permalink
Try to fix incorrect 64-bit alignment
Browse files Browse the repository at this point in the history
Added unit tests for alignment macros.
Fixes #418
  • Loading branch information
miloyip committed Sep 1, 2015
1 parent 3ede21c commit 311b482
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
6 changes: 3 additions & 3 deletions include/rapidjson/rapidjson.h
Original file line number Diff line number Diff line change
Expand Up @@ -238,13 +238,13 @@
\param x pointer to align
Some machines require strict data alignment. Currently the default uses 4 bytes
alignment. User can customize by defining the RAPIDJSON_ALIGN function macro.,
alignment. User can customize by defining the RAPIDJSON_ALIGN function macro.
*/
#ifndef RAPIDJSON_ALIGN
#if RAPIDJSON_64BIT == 1
#define RAPIDJSON_ALIGN(x) ((x + 7u) & ~7u)
#define RAPIDJSON_ALIGN(x) (((x) + static_cast<uint64_t>(7u)) & ~static_cast<uint64_t>(7u))
#else
#define RAPIDJSON_ALIGN(x) ((x + 3u) & ~3u)
#define RAPIDJSON_ALIGN(x) (((x) + 3u) & ~3u)
#endif
#endif

Expand Down
20 changes: 20 additions & 0 deletions test/unittest/allocatorstest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,23 @@ TEST(Allocator, MemoryPoolAllocator) {
EXPECT_LE(a.Size(), a.Capacity());
}
}

TEST(Allocator, Alignment) {
#if RAPIDJSON_64BIT == 1
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000000), RAPIDJSON_ALIGN(0));
for (uint64_t i = 1; i < 8; i++) {
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008), RAPIDJSON_ALIGN(i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000010), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008) + i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000001, 0x00000000), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0xFFFFFFF8) + i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF8), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF0) + i));
}
#else
EXPECT_EQ(0u, RAPIDJSON_ALIGN(0u));
for (uint32_t i = 1; i < 4; i++) {
EXPECT_EQ(4u, RAPIDJSON_ALIGN(i));
EXPECT_EQ(8u, RAPIDJSON_ALIGN(4u + i));
EXPECT_EQ(0xFFFFFFF8u, RAPIDJSON_ALIGN(0xFFFFFFF4u + i));
EXPECT_EQ(0xFFFFFFFCu, RAPIDJSON_ALIGN(0xFFFFFFF8u + i));
}
#endif
}

0 comments on commit 311b482

Please sign in to comment.