diff options
-rw-r--r-- | base/rand_util.cc | 16 | ||||
-rw-r--r-- | base/rand_util.h | 5 | ||||
-rw-r--r-- | base/rand_util_unittest.cc | 23 |
3 files changed, 39 insertions, 5 deletions
diff --git a/base/rand_util.cc b/base/rand_util.cc index ea6ffd3..d89f8b7 100644 --- a/base/rand_util.cc +++ b/base/rand_util.cc @@ -41,4 +41,20 @@ uint64 RandGenerator(uint64 max) { return base::RandUint64() % max; } +std::string RandBytesAsString(size_t length) { + const size_t kBitsPerChar = 8; + const int kCharsPerInt64 = sizeof(uint64)/sizeof(char); + + std::string result(length, '\0'); + uint64 entropy = 0; + for (size_t i = 0; i < result.size(); ++i) { + if (i % kCharsPerInt64 == 0) + entropy = RandUint64(); + result[i] = static_cast<char>(entropy); + entropy >>= kBitsPerChar; + } + + return result; +} + } // namespace base diff --git a/base/rand_util.h b/base/rand_util.h index a4ea479..4e902da 100644 --- a/base/rand_util.h +++ b/base/rand_util.h @@ -6,6 +6,8 @@ #define BASE_RAND_UTIL_H_ #pragma once +#include <string> + #include "base/base_api.h" #include "base/basictypes.h" @@ -27,6 +29,9 @@ BASE_API uint64 RandGenerator(uint64 max); // Returns a random double in range [0, 1). Thread-safe. BASE_API double RandDouble(); +// Returns a random string of the specified length. +BASE_API std::string RandBytesAsString(size_t length); + } // namespace base #endif // BASE_RAND_UTIL_H_ diff --git a/base/rand_util_unittest.cc b/base/rand_util_unittest.cc index cbc338a..3bdb815 100644 --- a/base/rand_util_unittest.cc +++ b/base/rand_util_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -22,10 +22,23 @@ TEST(RandUtilTest, SameMinAndMax) { } TEST(RandUtilTest, RandDouble) { - // Force 64-bit precision, making sure we're not in a 80-bit FPU register. - volatile double number = base::RandDouble(); - EXPECT_GT(1.0, number); - EXPECT_LE(0.0, number); + // Force 64-bit precision, making sure we're not in a 80-bit FPU register. + volatile double number = base::RandDouble(); + EXPECT_GT(1.0, number); + EXPECT_LE(0.0, number); +} + +TEST(RandUtilTest, RandBytesAsString) { + std::string random_string = base::RandBytesAsString(0); + EXPECT_EQ(0U, random_string.size()); + random_string = base::RandBytesAsString(145); + EXPECT_EQ(145U, random_string.size()); + char accumulator = 0; + for (size_t i = 0; i < random_string.size(); ++i) + accumulator |= random_string[i]; + // In theory this test can fail, but it won't before the universe dies of + // heat death. + EXPECT_NE(0, accumulator); } // Make sure that it is still appropriate to use RandGenerator in conjunction |