ipc/chromium/src/base/rand_util.cc

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 // Copyright (c) 2008 The Chromium Authors. All rights reserved.
michael@0 2 // Use of this source code is governed by a BSD-style license that can be
michael@0 3 // found in the LICENSE file.
michael@0 4
michael@0 5 #include "base/rand_util.h"
michael@0 6
michael@0 7 #include <math.h>
michael@0 8
michael@0 9 #include <limits>
michael@0 10
michael@0 11 #include "base/basictypes.h"
michael@0 12 #include "base/logging.h"
michael@0 13
michael@0 14 namespace base {
michael@0 15
michael@0 16 int RandInt(int min, int max) {
michael@0 17 DCHECK(min <= max);
michael@0 18
michael@0 19 uint64_t range = static_cast<int64_t>(max) - min + 1;
michael@0 20 uint64_t number = base::RandUint64();
michael@0 21 int result = min + static_cast<int>(number % range);
michael@0 22 DCHECK(result >= min && result <= max);
michael@0 23 return result;
michael@0 24 }
michael@0 25
michael@0 26 double RandDouble() {
michael@0 27 // We try to get maximum precision by masking out as many bits as will fit
michael@0 28 // in the target type's mantissa, and raising it to an appropriate power to
michael@0 29 // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa
michael@0 30 // is expected to accommodate 53 bits.
michael@0 31
michael@0 32 COMPILE_ASSERT(std::numeric_limits<double>::radix == 2, otherwise_use_scalbn);
michael@0 33 static const int kBits = std::numeric_limits<double>::digits;
michael@0 34 uint64_t random_bits = base::RandUint64() & ((GG_UINT64_C(1) << kBits) - 1);
michael@0 35 double result = ldexp(static_cast<double>(random_bits), -1 * kBits);
michael@0 36 DCHECK(result >= 0.0 && result < 1.0);
michael@0 37 return result;
michael@0 38 }
michael@0 39
michael@0 40 } // namespace base

mercurial