Fix some signed overflow errors causing undefined behavior (in theory).
BUG=webrtc:5491
Review URL: https://codereview.webrtc.org/1744183002
Cr-Commit-Position: refs/heads/master@{#11832}
diff --git a/webrtc/base/random_unittest.cc b/webrtc/base/random_unittest.cc
index 3b47a00..ae1a0a2 100644
--- a/webrtc/base/random_unittest.cc
+++ b/webrtc/base/random_unittest.cc
@@ -14,6 +14,7 @@
#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
+#include "webrtc/base/mathutils.h" // unsigned difference
#include "webrtc/base/random.h"
namespace webrtc {
@@ -118,7 +119,7 @@
ASSERT_GE(high, low);
ASSERT_GE(bucket_count, 2u);
- uint32_t interval = static_cast<uint32_t>(high - low + 1);
+ uint32_t interval = unsigned_difference<int32_t>(high, low) + 1;
uint32_t numbers_per_bucket;
if (interval == 0) {
// The computation high - low + 1 should be 2^32 but overflowed
@@ -134,7 +135,7 @@
int32_t sample = prng->Rand(low, high);
EXPECT_LE(low, sample);
EXPECT_GE(high, sample);
- buckets[static_cast<uint32_t>(sample - low) / numbers_per_bucket]++;
+ buckets[unsigned_difference<int32_t>(sample, low) / numbers_per_bucket]++;
}
for (unsigned int i = 0; i < bucket_count; i++) {
@@ -158,7 +159,7 @@
ASSERT_GE(high, low);
ASSERT_GE(bucket_count, 2u);
- uint32_t interval = static_cast<uint32_t>(high - low + 1);
+ uint32_t interval = high - low + 1;
uint32_t numbers_per_bucket;
if (interval == 0) {
// The computation high - low + 1 should be 2^32 but overflowed
@@ -174,7 +175,7 @@
uint32_t sample = prng->Rand(low, high);
EXPECT_LE(low, sample);
EXPECT_GE(high, sample);
- buckets[static_cast<uint32_t>(sample - low) / numbers_per_bucket]++;
+ buckets[(sample - low) / numbers_per_bucket]++;
}
for (unsigned int i = 0; i < bucket_count; i++) {