1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/ipc/chromium/src/base/rand_util.cc Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,40 @@ 1.4 +// Copyright (c) 2008 The Chromium Authors. All rights reserved. 1.5 +// Use of this source code is governed by a BSD-style license that can be 1.6 +// found in the LICENSE file. 1.7 + 1.8 +#include "base/rand_util.h" 1.9 + 1.10 +#include <math.h> 1.11 + 1.12 +#include <limits> 1.13 + 1.14 +#include "base/basictypes.h" 1.15 +#include "base/logging.h" 1.16 + 1.17 +namespace base { 1.18 + 1.19 +int RandInt(int min, int max) { 1.20 + DCHECK(min <= max); 1.21 + 1.22 + uint64_t range = static_cast<int64_t>(max) - min + 1; 1.23 + uint64_t number = base::RandUint64(); 1.24 + int result = min + static_cast<int>(number % range); 1.25 + DCHECK(result >= min && result <= max); 1.26 + return result; 1.27 +} 1.28 + 1.29 +double RandDouble() { 1.30 + // We try to get maximum precision by masking out as many bits as will fit 1.31 + // in the target type's mantissa, and raising it to an appropriate power to 1.32 + // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa 1.33 + // is expected to accommodate 53 bits. 1.34 + 1.35 + COMPILE_ASSERT(std::numeric_limits<double>::radix == 2, otherwise_use_scalbn); 1.36 + static const int kBits = std::numeric_limits<double>::digits; 1.37 + uint64_t random_bits = base::RandUint64() & ((GG_UINT64_C(1) << kBits) - 1); 1.38 + double result = ldexp(static_cast<double>(random_bits), -1 * kBits); 1.39 + DCHECK(result >= 0.0 && result < 1.0); 1.40 + return result; 1.41 +} 1.42 + 1.43 +} // namespace base