Skip to content

Commit 3c1bb4a

Browse files
ptrOffset and ptrDiff do not truncate uint64_t to uintptr_t
Change-Id: I0dcaf058ae3244ca0168580d972a19f9e4692e05 Signed-off-by: Venevtsev, Igor <igor.venevtsev@intel.com>
1 parent 233e3d7 commit 3c1bb4a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

runtime/helpers/ptr_math.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,23 @@ inline T ptrOffset(T ptrBefore, size_t offset) {
2323
return (T)addrAfter;
2424
}
2525

26+
template <>
27+
inline uint64_t ptrOffset(uint64_t ptrBefore, size_t offset) {
28+
return ptrBefore + offset;
29+
}
30+
2631
template <typename TA, typename TB>
2732
inline size_t ptrDiff(TA ptrAfter, TB ptrBefore) {
2833
auto addrBefore = (uintptr_t)ptrBefore;
2934
auto addrAfter = (uintptr_t)ptrAfter;
3035
return addrAfter - addrBefore;
3136
}
3237

38+
template <typename T>
39+
inline uint64_t ptrDiff(uint64_t ptrAfter, T ptrBefore) {
40+
return ptrAfter - ptrBefore;
41+
}
42+
3343
template <typename IntegerAddressType>
3444
inline void *addrToPtr(IntegerAddressType addr) {
3545
uintptr_t correctBitnessAddress = static_cast<uintptr_t>(addr);

unit_tests/helpers/ptr_math_tests.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,23 @@ TEST(PtrMath, givenCastToUint64FunctionWhenItIsCalledThenProperValueIsReturned)
4545
auto uintAddress = castToUint64(addressWithTrailingBitSet);
4646
EXPECT_EQ(uintAddress, expectedUint64Address);
4747
}
48+
49+
TEST(ptrOffset, preserve64Bit) {
50+
uint64_t ptrBefore = 0x800000000;
51+
size_t offset = 0x1234;
52+
auto ptrAfter = ptrOffset(ptrBefore, offset);
53+
EXPECT_EQ(0x800001234ull, ptrAfter);
54+
}
55+
56+
TEST(ptrDiff, preserve64Bit) {
57+
auto ptrAfter = 0x800001234ull;
58+
59+
auto ptrBefore = ptrDiff(ptrAfter, (size_t)0x1234);
60+
EXPECT_EQ(0x800000000ull, ptrBefore);
61+
62+
auto ptrBefore2 = ptrDiff(ptrAfter, 0x1234);
63+
EXPECT_EQ(0x800000000ull, ptrBefore2);
64+
65+
auto ptrBefore3 = ptrDiff(ptrAfter, 0x1234ull);
66+
EXPECT_EQ(0x800000000ull, ptrBefore3);
67+
}

0 commit comments

Comments
 (0)