-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.cpp
71 lines (54 loc) · 1.19 KB
/
util.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "util.hpp"
#include <cstdlib>
#include <fcntl.h>
#ifdef __linux__
#include <linux/random.h>
#endif
using std::uint32_t;
uint32_t GetRandom(uint32_t lt) {
uint32_t rnd;
#ifdef UNIX
/*
* UNIX.
*/
#ifdef BSD
/*
* UNIX: BSD.
*/
rnd = lt > 0 ? arc4random_uniform(lt) : arc4random();
#elif defined(__linux__)
/*
* UNIX: Linux.
*/
rnd = getrandom((void *)&rnd, sizeof(uint32_t), 0) % lt;
#else
/*
* UNIX: Other.
*/
FileOpenIn("/dev/urandom", true).read((char *)&rnd, sizeof(uint32_t));
rnd %= lt;
#endif
#else
/*
* Plain C.
*/
rnd = rand() | rand() << 16;
#endif
return rnd;
}
uint32_t GetRandom(std::uint32_t from, std::uint32_t to) {
return from + GetRandom(to + 1);
}
void ChangeDir(const char *path) {
if (sys::chdir(path))
throw FileError(path);
}
std::ifstream FileOpenIn(const char *path, bool binary) {
std::ifstream fs(path, binary? std::ios::binary : 0);
if (!fs)
throw FileError(path);
return std::move(fs);
}
FileError::FileError(const char *path) {
reason = std::string("Failed to access: '") + path + "'.";
}