Skip to content

Commit 009cee2

Browse files
committed
[hist] Remove asserts in RBinIndex operators
Arithmetic operations on special values and if wrapping around, go to InvalidIndex.
1 parent 5a1155c commit 009cee2

File tree

2 files changed

+40
-8
lines changed

2 files changed

+40
-8
lines changed

hist/histv7/inc/ROOT/RBinIndex.hxx

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,17 @@ public:
5050

5151
RBinIndex &operator+=(std::size_t a)
5252
{
53-
assert(IsNormal());
54-
fIndex += a;
55-
// TODO: is it possible to catch overflows?
56-
assert(IsNormal());
53+
if (!IsNormal()) {
54+
// Arithmetic operations on special values go to InvalidIndex.
55+
fIndex = InvalidIndex;
56+
} else {
57+
std::size_t old = fIndex;
58+
fIndex += a;
59+
if (fIndex < old || !IsNormal()) {
60+
// The addition wrapped around, go to InvalidIndex.
61+
fIndex = InvalidIndex;
62+
}
63+
}
5764
return *this;
5865
}
5966

@@ -79,10 +86,15 @@ public:
7986

8087
RBinIndex &operator-=(std::size_t a)
8188
{
82-
assert(IsNormal());
83-
assert(fIndex >= a);
84-
fIndex -= a;
85-
assert(IsNormal());
89+
if (!IsNormal()) {
90+
// Arithmetic operations on special values go to InvalidIndex.
91+
fIndex = InvalidIndex;
92+
} else if (fIndex >= a) {
93+
fIndex -= a;
94+
} else {
95+
// The operation would wrap around, go to InvalidIndex.
96+
fIndex = InvalidIndex;
97+
}
8698
return *this;
8799
}
88100

hist/histv7/test/hist_index.cxx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@ TEST(RBinIndex, Plus)
4545
const auto index3 = index1 + 2;
4646
EXPECT_EQ(index3.GetIndex(), 3);
4747
}
48+
49+
// Arithmetic operations on special values go to InvalidIndex.
50+
for (auto index : {RBinIndex::Underflow(), RBinIndex::Overflow(), RBinIndex()}) {
51+
index++;
52+
EXPECT_TRUE(index.IsInvalid());
53+
}
54+
55+
// Matches RBinIndex::UnderflowIndex
56+
static constexpr std::size_t UnderflowIndex = -3;
57+
EXPECT_TRUE((RBinIndex(0) + UnderflowIndex).IsInvalid());
58+
EXPECT_TRUE((RBinIndex(3) + UnderflowIndex).IsInvalid());
4859
}
4960

5061
TEST(RBinIndex, Minus)
@@ -74,6 +85,15 @@ TEST(RBinIndex, Minus)
7485
const auto index1 = index3 - 2;
7586
EXPECT_EQ(index1.GetIndex(), 1);
7687
}
88+
89+
// Arithmetic operations on special values go to InvalidIndex.
90+
for (auto index : {RBinIndex::Underflow(), RBinIndex::Overflow(), RBinIndex()}) {
91+
index--;
92+
EXPECT_TRUE(index.IsInvalid());
93+
}
94+
95+
EXPECT_TRUE((RBinIndex(0) - 1).IsInvalid());
96+
EXPECT_TRUE((RBinIndex(0) - 4).IsInvalid());
7797
}
7898

7999
TEST(RBinIndex, Equality)

0 commit comments

Comments
 (0)