Get += operator to work with negative numbers.

This commit is contained in:
King_DuckZ 2015-08-15 23:52:37 +02:00
parent f5eb76d70f
commit 28fc001540
2 changed files with 47 additions and 10 deletions

View File

@ -89,19 +89,35 @@ namespace dk {
template <uint32_t D>
const TileCoords<D>& TileCoords<D>::operator+= (CoordinateScalarType parValue) {
std::size_t index = 0;
while (parValue) {
//naïve implementation
//parValue += m_pos[index];
//m_pos[index] = parValue % (m_size[index] + 1);
//parValue /= (m_size[index] + 1);
if (parValue > 0) {
while (parValue) {
//naïve implementation
//parValue += m_pos[index];
//m_pos[index] = parValue % (m_size[index] + 1);
//parValue /= (m_size[index] + 1);
//overflow-aware implementation
const auto new_pos = implem::sum_mod(m_pos[index], parValue, m_size[index] + 1);
parValue = implem::sum_div(m_pos[index], parValue, m_size[index] + 1);
m_pos[index] = new_pos;
//overflow-aware implementation
const auto new_pos = implem::sum_mod(m_pos[index], parValue, m_size[index] + 1);
parValue = implem::sum_div(m_pos[index], parValue, m_size[index] + 1);
m_pos[index] = new_pos;
++index;
++index;
}
}
else if (parValue < 0) {
while (parValue) {
//const auto t = (-parValue) % (m_size[index] + 1);
const auto t = -(parValue % (m_size[index] + 1));
DK_ASSERT(t >= 0);
const CoordinateScalarType r = (t > m_pos[index] ? 1 : 0);
m_pos[index] = (m_size[index] + 1) * r + m_pos[index] - t;
parValue /= (m_size[index] + 1);
parValue -= r;
++index;
}
}
return *this;
}

View File

@ -90,4 +90,25 @@ TEST(advance, tilecoords) {
EXPECT_EQ(1201, test[2]);
EXPECT_EQ(710, test[3]);
}
{
const coords4 max_coords(32);
tcoords4 test(max_coords);
test += 33 * 33 * 2;
EXPECT_EQ(0, test[0]);
EXPECT_EQ(0, test[1]);
EXPECT_EQ(2, test[2]);
EXPECT_EQ(0, test[3]);
test += -1;
EXPECT_EQ(32, test[0]);
EXPECT_EQ(32, test[1]);
EXPECT_EQ(1, test[2]);
EXPECT_EQ(0, test[3]);
test++;
test += -33 * 33 * 2;
EXPECT_EQ(tcoords4(max_coords), test);
}
}