Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/system/lib/wasmfs/fuzzer/random.cpp
6175 views
1
// Copyright 2021 The Emscripten Authors. All rights reserved.
2
// Emscripten is available under two separate licenses, the MIT license and the
3
// University of Illinois/NCSA Open Source License. Both these licenses can be
4
// found in the LICENSE file.
5
6
// Original Source that was modified:
7
// https://github.com/WebAssembly/binaryen/blob/main/src/tools/fuzzing/random.cpp
8
9
#include "random.h"
10
11
namespace wasmfs {
12
13
int8_t Random::get() {
14
if (pos == bytes.size()) {
15
// We ran out of input; go back to the start for more.
16
finishedInput = true;
17
pos = 0;
18
xorFactor++;
19
}
20
return bytes[pos++] ^ xorFactor;
21
}
22
23
int16_t Random::get16() {
24
auto temp = uint16_t(get()) << 8;
25
return temp | uint16_t(get());
26
}
27
28
int32_t Random::get32() {
29
auto temp = uint32_t(get16()) << 16;
30
return temp | uint32_t(get16());
31
}
32
33
int64_t Random::get64() {
34
auto temp = uint64_t(get32()) << 32;
35
return temp | uint64_t(get32());
36
}
37
38
uint32_t Random::upTo(uint32_t x) {
39
if (x == 0) {
40
return 0;
41
}
42
uint32_t raw;
43
if (x <= 255) {
44
raw = get();
45
} else if (x <= 65535) {
46
raw = get16();
47
} else {
48
raw = get32();
49
}
50
auto ret = raw % x;
51
// use extra bits as "noise" for later
52
xorFactor += raw / x;
53
return ret;
54
}
55
56
// Returns a random length string of random characters.
57
std::string Random::getString(int8_t size) {
58
static const char alphanum[] = "0123456789"
59
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
60
"abcdefghijklmnopqrstuvwxyz";
61
std::string ret;
62
ret.reserve(size);
63
for (int i = 0; i < size; ++i) {
64
ret += alphanum[upTo(sizeof(alphanum) - 1)];
65
}
66
return ret;
67
}
68
69
// Returns a random length string of the same character.
70
std::string Random::getSingleSymbolString(uint32_t length) {
71
return std::string(length, getString(1)[0]);
72
}
73
74
} // namespace wasmfs
75
76