Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(131)

Side by Side Diff: base/rand_util.cc

Issue 6904118: Add a rand_util method for generating a random string. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: '' Created 9 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/rand_util.h" 5 #include "base/rand_util.h"
6 6
7 #include <math.h> 7 #include <math.h>
8 8
9 #include <limits> 9 #include <limits>
10 10
(...skipping 23 matching lines...) Expand all
34 double result = ldexp(static_cast<double>(random_bits), -1 * kBits); 34 double result = ldexp(static_cast<double>(random_bits), -1 * kBits);
35 DCHECK(result >= 0.0 && result < 1.0); 35 DCHECK(result >= 0.0 && result < 1.0);
36 return result; 36 return result;
37 } 37 }
38 38
39 uint64 RandGenerator(uint64 max) { 39 uint64 RandGenerator(uint64 max) {
40 DCHECK_GT(max, 0ULL); 40 DCHECK_GT(max, 0ULL);
41 return base::RandUint64() % max; 41 return base::RandUint64() % max;
42 } 42 }
43 43
44 std::string RandString(int length) {
45 const size_t kBitsPerChar = 8;
46 const int kCharsPerInt64 = sizeof(uint64)/sizeof(char);
47
48 std::string result(length, '\0');
49 uint64 entropy = 0;
50 for (size_t i = 0; i < result.size(); ++i) {
51 if (i % kCharsPerInt64 == 0)
52 entropy = RandUint64();
darin (slow to review) 2011/04/29 16:15:36 nit: indentation
53 result[i] = static_cast<char>(entropy);
54 entropy >>= kBitsPerChar;
55 }
56
57 return result;
58 }
59
44 } // namespace base 60 } // namespace base
OLDNEW
« base/rand_util.h ('K') | « base/rand_util.h ('k') | base/rand_util_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698