2013-11-06 00:59:46 +00:00
|
|
|
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
|
|
|
|
// for details. All rights reserved. Use of this source code is governed by a
|
|
|
|
// BSD-style license that can be found in the LICENSE file.
|
|
|
|
|
2016-10-26 07:26:03 +00:00
|
|
|
#ifndef RUNTIME_VM_RANDOM_H_
|
|
|
|
#define RUNTIME_VM_RANDOM_H_
|
2013-11-06 00:59:46 +00:00
|
|
|
|
2021-02-04 11:12:47 +00:00
|
|
|
#include <atomic>
|
|
|
|
|
2013-11-06 00:59:46 +00:00
|
|
|
#include "vm/allocation.h"
|
2017-11-23 00:07:56 +00:00
|
|
|
#include "vm/flags.h"
|
2017-07-13 15:08:33 +00:00
|
|
|
#include "vm/globals.h"
|
2013-11-06 00:59:46 +00:00
|
|
|
|
|
|
|
namespace dart {
|
|
|
|
|
2017-11-23 00:07:56 +00:00
|
|
|
DECLARE_FLAG(uint64_t, random_seed);
|
|
|
|
|
2014-03-28 23:39:36 +00:00
|
|
|
class Random {
|
2013-11-06 00:59:46 +00:00
|
|
|
public:
|
|
|
|
Random();
|
2015-09-16 19:11:47 +00:00
|
|
|
// Seed must be non-zero.
|
|
|
|
explicit Random(uint64_t seed);
|
2013-11-06 00:59:46 +00:00
|
|
|
~Random();
|
|
|
|
|
|
|
|
uint32_t NextUInt32();
|
2014-04-23 19:44:03 +00:00
|
|
|
uint64_t NextUInt64() {
|
|
|
|
return (static_cast<uint64_t>(NextUInt32()) << 32) |
|
2016-11-08 21:54:47 +00:00
|
|
|
static_cast<uint64_t>(NextUInt32());
|
2014-04-23 19:44:03 +00:00
|
|
|
}
|
2013-11-06 00:59:46 +00:00
|
|
|
|
2023-08-01 15:50:11 +00:00
|
|
|
// Returns a random number that's a valid JS integer.
|
|
|
|
//
|
|
|
|
// All IDs that can be returned over the service protocol should be
|
|
|
|
// representable as JS integers and should be generated using this method.
|
|
|
|
//
|
|
|
|
// See https://github.com/dart-lang/sdk/issues/53081.
|
|
|
|
uint64_t NextJSInt() {
|
|
|
|
// Number.MAX_SAFE_INTEGER (2 ^ 53 - 1)
|
|
|
|
const uint64_t kMaxJsInt = 0x1FFFFFFFFFFFFF;
|
|
|
|
return NextUInt64() & kMaxJsInt;
|
|
|
|
}
|
|
|
|
|
2022-07-22 19:13:47 +00:00
|
|
|
static uint64_t GlobalNextUInt64();
|
|
|
|
static void Init();
|
|
|
|
static void Cleanup();
|
|
|
|
|
2022-11-22 18:05:24 +00:00
|
|
|
// Generates a uniform random variable in the range [0,1].
|
|
|
|
double NextDouble();
|
|
|
|
|
2013-11-06 00:59:46 +00:00
|
|
|
private:
|
2021-02-04 11:12:47 +00:00
|
|
|
uint64_t NextState();
|
2015-09-16 19:11:47 +00:00
|
|
|
void Initialize(uint64_t seed);
|
2013-11-06 00:59:46 +00:00
|
|
|
|
2021-02-04 11:12:47 +00:00
|
|
|
std::atomic<uint64_t> _state;
|
2013-11-06 00:59:46 +00:00
|
|
|
|
|
|
|
DISALLOW_COPY_AND_ASSIGN(Random);
|
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace dart
|
|
|
|
|
2016-10-26 07:26:03 +00:00
|
|
|
#endif // RUNTIME_VM_RANDOM_H_
|