Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
official-stockfish
GitHub Repository: official-stockfish/Stockfish
Path: blob/master/src/misc.h
376 views
1
/*
2
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
5
Stockfish is free software: you can redistribute it and/or modify
6
it under the terms of the GNU General Public License as published by
7
the Free Software Foundation, either version 3 of the License, or
8
(at your option) any later version.
9
10
Stockfish is distributed in the hope that it will be useful,
11
but WITHOUT ANY WARRANTY; without even the implied warranty of
12
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
GNU General Public License for more details.
14
15
You should have received a copy of the GNU General Public License
16
along with this program. If not, see <http://www.gnu.org/licenses/>.
17
*/
18
19
#ifndef MISC_H_INCLUDED
20
#define MISC_H_INCLUDED
21
22
#include <algorithm>
23
#include <array>
24
#include <cassert>
25
#include <chrono>
26
#include <cstddef>
27
#include <cstdint>
28
#include <cstdio>
29
#include <iosfwd>
30
#include <optional>
31
#include <string>
32
#include <string_view>
33
#include <vector>
34
35
#define stringify2(x) #x
36
#define stringify(x) stringify2(x)
37
38
namespace Stockfish {
39
40
std::string engine_version_info();
41
std::string engine_info(bool to_uci = false);
42
std::string compiler_info();
43
44
// Preloads the given address in L1/L2 cache. This is a non-blocking
45
// function that doesn't stall the CPU waiting for data to be loaded from memory,
46
// which can be quite slow.
47
void prefetch(const void* addr);
48
49
void start_logger(const std::string& fname);
50
51
size_t str_to_size_t(const std::string& s);
52
53
#if defined(__linux__)
54
55
struct PipeDeleter {
56
void operator()(FILE* file) const {
57
if (file != nullptr)
58
{
59
pclose(file);
60
}
61
}
62
};
63
64
#endif
65
66
// Reads the file as bytes.
67
// Returns std::nullopt if the file does not exist.
68
std::optional<std::string> read_file_to_string(const std::string& path);
69
70
void dbg_hit_on(bool cond, int slot = 0);
71
void dbg_mean_of(int64_t value, int slot = 0);
72
void dbg_stdev_of(int64_t value, int slot = 0);
73
void dbg_extremes_of(int64_t value, int slot = 0);
74
void dbg_correl_of(int64_t value1, int64_t value2, int slot = 0);
75
void dbg_print();
76
void dbg_clear();
77
78
using TimePoint = std::chrono::milliseconds::rep; // A value in milliseconds
79
static_assert(sizeof(TimePoint) == sizeof(int64_t), "TimePoint should be 64 bits");
80
inline TimePoint now() {
81
return std::chrono::duration_cast<std::chrono::milliseconds>(
82
std::chrono::steady_clock::now().time_since_epoch())
83
.count();
84
}
85
86
inline std::vector<std::string_view> split(std::string_view s, std::string_view delimiter) {
87
std::vector<std::string_view> res;
88
89
if (s.empty())
90
return res;
91
92
size_t begin = 0;
93
for (;;)
94
{
95
const size_t end = s.find(delimiter, begin);
96
if (end == std::string::npos)
97
break;
98
99
res.emplace_back(s.substr(begin, end - begin));
100
begin = end + delimiter.size();
101
}
102
103
res.emplace_back(s.substr(begin));
104
105
return res;
106
}
107
108
void remove_whitespace(std::string& s);
109
bool is_whitespace(std::string_view s);
110
111
enum SyncCout {
112
IO_LOCK,
113
IO_UNLOCK
114
};
115
std::ostream& operator<<(std::ostream&, SyncCout);
116
117
#define sync_cout std::cout << IO_LOCK
118
#define sync_endl std::endl << IO_UNLOCK
119
120
void sync_cout_start();
121
void sync_cout_end();
122
123
// True if and only if the binary is compiled on a little-endian machine
124
static inline const std::uint16_t Le = 1;
125
static inline const bool IsLittleEndian = *reinterpret_cast<const char*>(&Le) == 1;
126
127
128
template<typename T, std::size_t MaxSize>
129
class ValueList {
130
131
public:
132
std::size_t size() const { return size_; }
133
void push_back(const T& value) { values_[size_++] = value; }
134
const T* begin() const { return values_; }
135
const T* end() const { return values_ + size_; }
136
const T& operator[](int index) const { return values_[index]; }
137
138
private:
139
T values_[MaxSize];
140
std::size_t size_ = 0;
141
};
142
143
144
template<typename T, std::size_t Size, std::size_t... Sizes>
145
class MultiArray;
146
147
namespace Detail {
148
149
template<typename T, std::size_t Size, std::size_t... Sizes>
150
struct MultiArrayHelper {
151
using ChildType = MultiArray<T, Sizes...>;
152
};
153
154
template<typename T, std::size_t Size>
155
struct MultiArrayHelper<T, Size> {
156
using ChildType = T;
157
};
158
159
template<typename To, typename From>
160
constexpr bool is_strictly_assignable_v =
161
std::is_assignable_v<To&, From> && (std::is_same_v<To, From> || !std::is_convertible_v<From, To>);
162
163
}
164
165
// MultiArray is a generic N-dimensional array.
166
// The template parameters (Size and Sizes) encode the dimensions of the array.
167
template<typename T, std::size_t Size, std::size_t... Sizes>
168
class MultiArray {
169
using ChildType = typename Detail::MultiArrayHelper<T, Size, Sizes...>::ChildType;
170
using ArrayType = std::array<ChildType, Size>;
171
ArrayType data_;
172
173
public:
174
using value_type = typename ArrayType::value_type;
175
using size_type = typename ArrayType::size_type;
176
using difference_type = typename ArrayType::difference_type;
177
using reference = typename ArrayType::reference;
178
using const_reference = typename ArrayType::const_reference;
179
using pointer = typename ArrayType::pointer;
180
using const_pointer = typename ArrayType::const_pointer;
181
using iterator = typename ArrayType::iterator;
182
using const_iterator = typename ArrayType::const_iterator;
183
using reverse_iterator = typename ArrayType::reverse_iterator;
184
using const_reverse_iterator = typename ArrayType::const_reverse_iterator;
185
186
constexpr auto& at(size_type index) noexcept { return data_.at(index); }
187
constexpr const auto& at(size_type index) const noexcept { return data_.at(index); }
188
189
constexpr auto& operator[](size_type index) noexcept { return data_[index]; }
190
constexpr const auto& operator[](size_type index) const noexcept { return data_[index]; }
191
192
constexpr auto& front() noexcept { return data_.front(); }
193
constexpr const auto& front() const noexcept { return data_.front(); }
194
constexpr auto& back() noexcept { return data_.back(); }
195
constexpr const auto& back() const noexcept { return data_.back(); }
196
197
auto* data() { return data_.data(); }
198
const auto* data() const { return data_.data(); }
199
200
constexpr auto begin() noexcept { return data_.begin(); }
201
constexpr auto end() noexcept { return data_.end(); }
202
constexpr auto begin() const noexcept { return data_.begin(); }
203
constexpr auto end() const noexcept { return data_.end(); }
204
constexpr auto cbegin() const noexcept { return data_.cbegin(); }
205
constexpr auto cend() const noexcept { return data_.cend(); }
206
207
constexpr auto rbegin() noexcept { return data_.rbegin(); }
208
constexpr auto rend() noexcept { return data_.rend(); }
209
constexpr auto rbegin() const noexcept { return data_.rbegin(); }
210
constexpr auto rend() const noexcept { return data_.rend(); }
211
constexpr auto crbegin() const noexcept { return data_.crbegin(); }
212
constexpr auto crend() const noexcept { return data_.crend(); }
213
214
constexpr bool empty() const noexcept { return data_.empty(); }
215
constexpr size_type size() const noexcept { return data_.size(); }
216
constexpr size_type max_size() const noexcept { return data_.max_size(); }
217
218
template<typename U>
219
void fill(const U& v) {
220
static_assert(Detail::is_strictly_assignable_v<T, U>,
221
"Cannot assign fill value to entry type");
222
for (auto& ele : data_)
223
{
224
if constexpr (sizeof...(Sizes) == 0)
225
ele = v;
226
else
227
ele.fill(v);
228
}
229
}
230
231
constexpr void swap(MultiArray<T, Size, Sizes...>& other) noexcept { data_.swap(other.data_); }
232
};
233
234
235
// xorshift64star Pseudo-Random Number Generator
236
// This class is based on original code written and dedicated
237
// to the public domain by Sebastiano Vigna (2014).
238
// It has the following characteristics:
239
//
240
// - Outputs 64-bit numbers
241
// - Passes Dieharder and SmallCrush test batteries
242
// - Does not require warm-up, no zeroland to escape
243
// - Internal state is a single 64-bit integer
244
// - Period is 2^64 - 1
245
// - Speed: 1.60 ns/call (Core i7 @3.40GHz)
246
//
247
// For further analysis see
248
// <http://vigna.di.unimi.it/ftp/papers/xorshift.pdf>
249
250
class PRNG {
251
252
uint64_t s;
253
254
uint64_t rand64() {
255
256
s ^= s >> 12, s ^= s << 25, s ^= s >> 27;
257
return s * 2685821657736338717LL;
258
}
259
260
public:
261
PRNG(uint64_t seed) :
262
s(seed) {
263
assert(seed);
264
}
265
266
template<typename T>
267
T rand() {
268
return T(rand64());
269
}
270
271
// Special generator used to fast init magic numbers.
272
// Output values only have 1/8th of their bits set on average.
273
template<typename T>
274
T sparse_rand() {
275
return T(rand64() & rand64() & rand64());
276
}
277
};
278
279
inline uint64_t mul_hi64(uint64_t a, uint64_t b) {
280
#if defined(__GNUC__) && defined(IS_64BIT)
281
__extension__ using uint128 = unsigned __int128;
282
return (uint128(a) * uint128(b)) >> 64;
283
#else
284
uint64_t aL = uint32_t(a), aH = a >> 32;
285
uint64_t bL = uint32_t(b), bH = b >> 32;
286
uint64_t c1 = (aL * bL) >> 32;
287
uint64_t c2 = aH * bL + c1;
288
uint64_t c3 = aL * bH + uint32_t(c2);
289
return aH * bH + (c2 >> 32) + (c3 >> 32);
290
#endif
291
}
292
293
294
struct CommandLine {
295
public:
296
CommandLine(int _argc, char** _argv) :
297
argc(_argc),
298
argv(_argv) {}
299
300
static std::string get_binary_directory(std::string argv0);
301
static std::string get_working_directory();
302
303
int argc;
304
char** argv;
305
};
306
307
namespace Utility {
308
309
template<typename T, typename Predicate>
310
void move_to_front(std::vector<T>& vec, Predicate pred) {
311
auto it = std::find_if(vec.begin(), vec.end(), pred);
312
313
if (it != vec.end())
314
{
315
std::rotate(vec.begin(), it, it + 1);
316
}
317
}
318
}
319
320
#if defined(__GNUC__) && !defined(__clang__)
321
#if __GNUC__ >= 13
322
#define sf_assume(cond) __attribute__((assume(cond)))
323
#else
324
#define sf_assume(cond) \
325
do \
326
{ \
327
if (!(cond)) \
328
__builtin_unreachable(); \
329
} while (0)
330
#endif
331
#else
332
// do nothing for other compilers
333
#define sf_assume(cond)
334
#endif
335
336
} // namespace Stockfish
337
338
#endif // #ifndef MISC_H_INCLUDED
339
340