Skip to content

Commit 29b6c9b

Browse files
committed
Add assertions to check preconditions of functions and unsigned integer arithmetic
1 parent 80dba56 commit 29b6c9b

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

include/rapidjson/internal/diyfp.h

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,9 @@ struct DiyFp {
141141
double d;
142142
uint64_t u64;
143143
}u;
144+
RAPIDJSON_ASSERT(f <= kDpHiddenBit + kDpSignificandMask);
145+
RAPIDJSON_ASSERT(e >= kDpDenormalExponent);
146+
RAPIDJSON_ASSERT(e < kDpMaxExponent);
144147
const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 :
145148
static_cast<uint64_t>(e + kDpExponentBias);
146149
u.u64 = (f & kDpSignificandMask) | (be << kDpSignificandSize);
@@ -220,6 +223,7 @@ inline DiyFp GetCachedPowerByIndex(size_t index) {
220223
641, 667, 694, 720, 747, 774, 800, 827, 853, 880,
221224
907, 933, 960, 986, 1013, 1039, 1066
222225
};
226+
RAPIDJSON_ASSERT(index < 87);
223227
return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]);
224228
}
225229

@@ -238,10 +242,11 @@ inline DiyFp GetCachedPower(int e, int* K) {
238242
}
239243

240244
inline DiyFp GetCachedPower10(int exp, int *outExp) {
241-
unsigned index = (static_cast<unsigned>(exp) + 348u) / 8u;
242-
*outExp = -348 + static_cast<int>(index) * 8;
243-
return GetCachedPowerByIndex(index);
244-
}
245+
RAPIDJSON_ASSERT(exp >= -348);
246+
unsigned index = static_cast<unsigned>(exp + 348) / 8u;
247+
*outExp = -348 + static_cast<int>(index) * 8;
248+
return GetCachedPowerByIndex(index);
249+
}
245250

246251
#ifdef __GNUC__
247252
RAPIDJSON_DIAG_POP

include/rapidjson/internal/strtod.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,12 +233,14 @@ inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t
233233
while (*decimals == '0' && length > 1) {
234234
length--;
235235
decimals++;
236+
RAPIDJSON_ASSERT(decimalPosition > 0);
236237
decimalPosition--;
237238
}
238239

239240
// Trim trailing zeros
240241
while (decimals[length - 1] == '0' && length > 1) {
241242
length--;
243+
RAPIDJSON_ASSERT(decimalPosition > 0);
242244
decimalPosition--;
243245
exp++;
244246
}
@@ -248,6 +250,7 @@ inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t
248250
if (static_cast<int>(length) > kMaxDecimalDigit) {
249251
int delta = (static_cast<int>(length) - kMaxDecimalDigit);
250252
exp += delta;
253+
RAPIDJSON_ASSERT(decimalPosition > static_cast<unsigned>(delta));
251254
decimalPosition -= static_cast<unsigned>(delta);
252255
length = kMaxDecimalDigit;
253256
}

0 commit comments

Comments
 (0)