-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.hpp
100 lines (74 loc) · 1.92 KB
/
util.hpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#ifndef UTIL_HPP
#define UTIL_HPP
#include <string>
#include <fstream>
#include <memory>
#include <exception>
#include <functional>
#include <cstdint>
#include <string.h>
namespace sys {
#if defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
#define UNIX
#include <unistd.h>
#include <sys/param.h>
#elif defined(_WIN32)
#define WINDOWS
#include <windows.h>
#include <direct.h>
#else
#error "Operating system unsupported."
#endif
}
uint32_t GetRandom(std::uint32_t lt = 0);
uint32_t GetRandom(std::uint32_t from, std::uint32_t to);
static inline void FreeString(char *string) {std::free((void *)string);}
template <class T>
class ImplicitPtr : public std::shared_ptr<T> {
public:
using std::shared_ptr<T>::shared_ptr;
using std::shared_ptr<T>::operator =;
using std::shared_ptr<T>::operator ->;
using std::shared_ptr<T>::operator bool;
operator T *() const {
return std::shared_ptr<T>::get();
}
ImplicitPtr<T> operator =(T *ptr) {
std::shared_ptr<T>::reset(ptr);
return *this;
}
};
void ChangeDir(const char *path);
std::ifstream FileOpenIn(const char *path, bool binary = false);
static inline std::ifstream FileOpenIn(const std::string &path, bool binary = false) {
return FileOpenIn(path.c_str());
}
class FileError : public std::exception {
private:
std::string reason;
public:
FileError(const char *path);
virtual const char *what() const noexcept {return reason.c_str();}
};
template <class Value>
class Lazy {
private:
typedef std::function<Value()> Getter;
Getter get;
Value value;
bool ready = false;
public:
Lazy(const Getter &get) : get(get) {};
operator Value() {
if (ready)
return value;
return value = get();
}
Value *operator->() {
return &value;
}
void reset() {
ready = false;
}
};
#endif