File tree Expand file tree Collapse file tree 2 files changed +40
-8
lines changed Expand file tree Collapse file tree 2 files changed +40
-8
lines changed Original file line number Diff line number Diff line change @@ -50,10 +50,17 @@ public:
50
50
51
51
RBinIndex &operator +=(std::size_t a)
52
52
{
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
+ }
57
64
return *this ;
58
65
}
59
66
@@ -79,10 +86,15 @@ public:
79
86
80
87
RBinIndex &operator -=(std::size_t a)
81
88
{
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
+ }
86
98
return *this ;
87
99
}
88
100
Original file line number Diff line number Diff line change @@ -45,6 +45,17 @@ TEST(RBinIndex, Plus)
45
45
const auto index3 = index1 + 2 ;
46
46
EXPECT_EQ (index3.GetIndex (), 3 );
47
47
}
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 ());
48
59
}
49
60
50
61
TEST (RBinIndex, Minus)
@@ -74,6 +85,15 @@ TEST(RBinIndex, Minus)
74
85
const auto index1 = index3 - 2 ;
75
86
EXPECT_EQ (index1.GetIndex (), 1 );
76
87
}
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 ());
77
97
}
78
98
79
99
TEST (RBinIndex, Equality)
You can’t perform that action at this time.
0 commit comments