-
Notifications
You must be signed in to change notification settings - Fork 495
Expand file tree
/
Copy pathMiscUtils.h
More file actions
598 lines (524 loc) · 16.3 KB
/
MiscUtils.h
File metadata and controls
598 lines (524 loc) · 16.3 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2012 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "Export.h"
#include <algorithm>
#include <cctype>
#include <climits>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdint.h>
#include <vector>
#if defined(_MSC_VER)
#define DFHACK_FUNCTION_SIG __FUNCSIG__
#elif defined(__GNUC__)
#define DFHACK_FUNCTION_SIG __PRETTY_FUNCTION__
#else
#define DFHACK_FUNCTION_SIG __func__
#endif
#ifdef _WIN32
// On x86 MSVC, __thiscall passes |this| in ECX. On x86_64, __thiscall is the
// same as the standard calling convention.
// See https://docs.microsoft.com/en-us/cpp/cpp/thiscall for more info.
#define THISCALL __thiscall
#else
// On other platforms, there's no special calling convention for calling member
// functions.
#define THISCALL
#endif
namespace DFHack {
class color_ostream;
}
DFHACK_EXPORT int random_int(int max);
template <typename T>
void print_bits ( T val, std::ostream& out )
{
std::stringstream strs;
T n_bits = sizeof ( val ) * CHAR_BIT;
int cnt;
for ( unsigned i = 0; i < n_bits; ++i )
{
cnt = i/10;
strs << cnt << " ";
}
strs << std::endl;
for ( unsigned i = 0; i < n_bits; ++i )
{
cnt = i%10;
strs << cnt << " ";
}
strs << std::endl;
for ( unsigned i = 0; i < n_bits; ++i )
{
strs << "--";
}
strs << std::endl;
for ( unsigned i = 0; i < n_bits; ++i )
{
strs<< !!( val & 1 ) << " ";
val >>= 1;
}
strs << std::endl;
out << strs.str();
}
/*
* Binary search in vectors.
*/
template <typename FT>
int linear_index(const std::vector<FT> &vec, FT key)
{
for (unsigned i = 0; i < vec.size(); i++)
if (vec[i] == key)
return i;
return -1;
}
template <typename FT>
int linear_index(const std::vector<FT*> &vec, const FT &key)
{
for (unsigned i = 0; i < vec.size(); i++)
if (vec[i] && *vec[i] == key)
return i;
return -1;
}
template <typename FT>
int binsearch_index(const std::vector<FT> &vec, FT key, bool exact = true)
{
// Returns the index of the value >= the key
int min = -1, max = (int)vec.size();
const FT *p = vec.data();
for (;;)
{
int mid = (min + max)>>1;
if (mid == min)
return exact ? -1 : max;
FT midv = p[mid];
if (midv == key)
return mid;
else if (midv < key)
min = mid;
else
max = mid;
}
}
template <typename CT, typename FT>
int linear_index(const std::vector<CT*> &vec, FT CT::*field, FT key)
{
for (unsigned i = 0; i < vec.size(); i++)
if (vec[i]->*field == key)
return i;
return -1;
}
template <typename CT, typename FT, typename MT>
int binsearch_index(const std::vector<CT*> &vec, FT MT::*field, FT key, bool exact = true)
{
// Returns the index of the value >= the key
int min = -1, max = (int)vec.size();
CT *const *p = vec.data();
for (;;)
{
int mid = (min + max)>>1;
if (mid == min)
return exact ? -1 : max;
FT midv = p[mid]->*field;
if (midv == key)
return mid;
else if (midv < key)
min = mid;
else
max = mid;
}
}
template <typename CT>
inline int binsearch_index(const std::vector<CT*> &vec, typename CT::key_field_type key, bool exact = true)
{
return CT::binsearch_index(vec, key, exact);
}
template <typename CT>
inline int binsearch_index(const std::vector<CT*> &vec, typename CT::key_pointer_type key, bool exact = true)
{
return CT::binsearch_index(vec, key, exact);
}
template <typename FT>
int random_index(const std::vector<FT>& vec)
{
if (vec.empty())
return -1;
else if (vec.size() == 1)
return 0;
return random_int(vec.size());
}
template<typename FT, typename KT>
inline bool vector_contains(const std::vector<FT> &vec, KT key)
{
return binsearch_index(vec, key) >= 0;
}
template<typename CT, typename FT>
inline bool vector_contains(const std::vector<CT*> &vec, FT CT::*field, FT key)
{
return binsearch_index(vec, field, key) >= 0;
}
template<typename T>
inline T vector_get(const std::vector<T> &vec, unsigned idx, const T &defval = T())
{
if (idx < vec.size())
return vec[idx];
else
return defval;
}
template<typename T>
inline T vector_get_random(const std::vector<T>& vec, const T& defval = T())
{
return vector_get(vec, random_index(vec), defval);
}
template<typename T>
inline void vector_insert_at(std::vector<T> &vec, unsigned idx, const T &val)
{
vec.insert(vec.begin()+idx, val);
}
template<typename T>
inline void vector_erase_at(std::vector<T> &vec, unsigned idx)
{
if (idx < vec.size())
vec.erase(vec.begin()+idx);
}
template<typename FT>
unsigned insert_into_vector(std::vector<FT> &vec, FT key, bool *inserted = NULL)
{
unsigned pos = (unsigned)binsearch_index(vec, key, false);
bool to_ins = (pos >= vec.size() || vec[pos] != key);
if (inserted) *inserted = to_ins;
if (to_ins)
vector_insert_at(vec, pos, key);
return pos;
}
template<typename CT, typename FT, typename MT>
unsigned insert_into_vector(std::vector<CT*> &vec, FT MT::*field, CT *obj, bool *inserted = NULL)
{
unsigned pos = (unsigned)binsearch_index(vec, field, obj->*field, false);
bool to_ins = (pos >= vec.size() || vec[pos] != obj);
if (inserted) *inserted = to_ins;
if (to_ins)
vector_insert_at(vec, pos, obj);
return pos;
}
template<typename FT>
bool erase_from_vector(std::vector<FT> &vec, FT key)
{
int pos = binsearch_index(vec, key);
vector_erase_at(vec, pos);
return pos >= 0;
}
template<typename CT, typename FT>
bool erase_from_vector(std::vector<CT*> &vec, FT CT::*field, FT key)
{
int pos = binsearch_index(vec, field, key);
vector_erase_at(vec, pos);
return pos >= 0;
}
template <typename CT, typename KT>
CT *binsearch_in_vector(const std::vector<CT*> &vec, KT value)
{
int idx = binsearch_index(vec, value);
return idx < 0 ? NULL : vec[idx];
}
template <typename CT, typename FT>
CT *binsearch_in_vector(const std::vector<CT*> &vec, FT CT::*field, FT value)
{
int idx = binsearch_index(vec, field, value);
return idx < 0 ? NULL : vec[idx];
}
/*
* List
*/
template<typename Link>
Link *linked_list_append(Link *head, Link *tail)
{
while (head->next)
head = head->next;
head->next = tail;
tail->prev = head;
return tail;
}
template<typename Link>
Link *linked_list_insert_after(Link *pos, Link *link)
{
link->next = pos->next;
if (pos->next)
pos->next->prev = link;
link->prev = pos;
pos->next = link;
return link;
}
/**
* Returns true if an item that matches the given function was found, deleted,
* and removed from the list. Otherwise returns false. Only removes the first
* match.
*
* Example usage:
*
* linked_list_remove(&world->projectiles.all, [&](df::projectile *proj) {
* if (proj->getType() != df::enums::projectile_type::Unit)
* return false;
* if (auto unit_proj = virtual_cast<df::proj_unitst>(proj))
* return unit_proj->unit == unit;
* return false;
* });
*/
template <typename L, typename V = L::iterator::value_type, std::invocable<V> F>
bool linked_list_remove(L *list, F matches) {
auto matches_wrapper = [&](L::iterator::value_type item) {
return item && matches(item);
};
typename L::const_iterator it = std::find_if(list->cbegin(), list->cend(), matches_wrapper);
if (it == list->cend())
return false;
auto item = *it;
list->erase(it);
delete item;
return true;
}
/**
* Returns true if the item with id idToRemove was found, deleted, and
* removed from the list. Otherwise returns false.
*/
template<typename L>
bool linked_list_remove(L *list, int32_t idToRemove) {
return linked_list_remove(list, [&](L::iterator::value_type item) {
return item->id == idToRemove;
});
}
template<typename T>
inline typename T::mapped_type map_find(
const T &map, const typename T::key_type &key,
const typename T::mapped_type &defval = typename T::mapped_type()
) {
auto it = map.find(key);
return (it == map.end()) ? defval : it->second;
}
template <class T, typename Fn>
static void for_each_(std::vector<T> &v, Fn func)
{
std::for_each(v.begin(), v.end(), func);
}
template <class T, class V, typename Fn>
static void for_each_(std::map<T, V> &v, Fn func)
{
std::for_each(v.begin(), v.end(), func);
}
template <class T, class V, typename Fn>
static void transform_(const std::vector<T> &src, std::vector<V> &dst, Fn func)
{
std::transform(src.begin(), src.end(), std::back_inserter(dst), func);
}
DFHACK_EXPORT bool prefix_matches(const std::string &prefix, const std::string &key, std::string *tail = NULL);
template<typename T>
typename T::mapped_type findPrefixInMap(
const T &table, const std::string &key,
const typename T::mapped_type& defval = typename T::mapped_type()
) {
auto it = table.lower_bound(key);
if (it != table.end() && it->first == key)
return it->second;
if (it != table.begin()) {
--it;
if (prefix_matches(it->first, key))
return it->second;
}
return defval;
}
#ifdef __GNUC__
#define VARIABLE_IS_NOT_USED __attribute__ ((unused))
#else
#define VARIABLE_IS_NOT_USED
#endif
template<class CT>
inline bool static_add_to_map(CT *pmap, typename CT::key_type key, typename CT::mapped_type value) {
(*pmap)[key] = value;
return true;
}
#define CONCAT_TOKENS2(a,b) a##b
#define CONCAT_TOKENS(a,b) CONCAT_TOKENS2(a,b)
#define DFHACK_STATIC_ADD_TO_MAP(pmap,key,value) \
static bool VARIABLE_IS_NOT_USED CONCAT_TOKENS(static_add_to_map_,__LINE__)\
= static_add_to_map(pmap,key,value)
/*
* MISC
*/
template<
std::ranges::input_range Range,
std::invocable<std::ostream&, std::ranges::range_reference_t<Range>> Callable>
void print_range(
std::ostream &out,
const Range &elements,
Callable&& print_element,
const std::string &prefix = "[",
const std::string &separator = ", ",
const std::string &suffix = "]"
){
out << prefix;
auto it = std::ranges::begin(elements);
auto end = std::ranges::end(elements);
if (it != end) {
print_element(out, *it);
for (++it; it != end; ++it) {
out << separator;
print_element(out, *it);
}
}
out << suffix;
}
template<std::ranges::input_range Range>
void print_range(
std::ostream &out,
const Range& elements,
const std::string &prefix = "[",
const std::string &separator = ", ",
const std::string &suffix = "]"
){
auto print_element = [](std::ostream &out, auto& e) { out << e; };
print_range(out, elements, print_element, prefix, separator, suffix);
}
DFHACK_EXPORT bool split_string(std::vector<std::string> *out,
const std::string &str, const std::string &separator,
bool squash_empty = false);
DFHACK_EXPORT std::string join_strings(const std::string &separator, const std::vector<std::string> &items);
template<typename T>
inline std::string join_strings(const std::string &separator, T &items) {
std::stringstream ss;
bool first = true;
for (auto &item : items) {
if (first)
first = false;
else
ss << separator;
ss << item;
}
return ss.str();
}
DFHACK_EXPORT char toupper_cp437(char c);
DFHACK_EXPORT char tolower_cp437(char c);
DFHACK_EXPORT std::string toUpper_cp437(const std::string &str);
DFHACK_EXPORT std::string toLower_cp437(const std::string &str);
DFHACK_EXPORT std::string to_search_normalized(const std::string &str);
DFHACK_EXPORT std::string capitalize_string_words(const std::string& str);
static inline std::string int_to_string(const int n) {
std::ostringstream ss;
ss << n;
return ss.str();
}
static inline int string_to_int(const std::string s, int default_ = 0) {
try {
return std::stoi(s);
}
catch (std::exception&) {
return default_;
}
}
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](char x){ return !std::isspace(x); }));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](char x){ return !std::isspace(x); }).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
enum struct NumberFormatType : int32_t {
DEFAULT = 0,
ENGLISH,
SYSTEM,
SIG_FIG,
SCIENTIFIC,
};
DFHACK_EXPORT NumberFormatType get_preferred_number_format_type();
DFHACK_EXPORT void set_preferred_number_format_type(NumberFormatType type);
DFHACK_EXPORT void imbue_with_locale(std::ostringstream &ss, NumberFormatType type);
DFHACK_EXPORT std::string format_number_by_sig_fig(double num, size_t sig_figs);
DFHACK_EXPORT std::string format_number_by_sig_fig(int64_t num, size_t sig_figs);
// format a number according to the give formatting type
template<typename T>
static inline std::string format_number(T num, NumberFormatType type) {
std::ostringstream ss;
imbue_with_locale(ss, type);
switch (type) {
case NumberFormatType::SCIENTIFIC:
ss << (double)num;
break;
case NumberFormatType::SIG_FIG:
ss << format_number_by_sig_fig(num, 3);
break;
default:
ss << num;
break;
}
return ss.str();
}
template<typename T>
static inline std::string format_number(T num) {
return format_number(num, get_preferred_number_format_type());
}
enum word_wrap_whitespace_mode {
WSMODE_KEEP_ALL,
WSMODE_COLLAPSE_ALL,
WSMODE_TRIM_LEADING
};
DFHACK_EXPORT bool word_wrap(std::vector<std::string> *out,
const std::string &str,
size_t line_length = 80,
word_wrap_whitespace_mode mode = WSMODE_KEEP_ALL);
/**
* Function to assist in parsing tokens. Returns string from source pos until next compc, ']', or end.
* pos should be set to position after '[' to start with, then incremented by the result's size+1 before subsequent calls.
* compc is usually ':', but can be '.' for parsing number ranges.
* Based on Bay12's g_src/basics.cpp
*/
std::string grab_token_string_pos(const std::string& source, int32_t pos, char compc = ':');
inline bool bits_match(unsigned required, unsigned ok, unsigned mask)
{
return (required & mask) == (required & mask & ok);
}
template<typename T, typename T1, typename T2>
inline T clip_range(T a, T1 minv, T2 maxv) {
if (a < minv) return minv;
if (a > maxv) return maxv;
return a;
}
/**
* Returns the amount of milliseconds elapsed since the UNIX epoch.
* Works on both windows and linux.
* source: http://stackoverflow.com/questions/1861294/how-to-calculate-execution-time-of-a-code-snippet-in-c
*/
DFHACK_EXPORT uint64_t GetTimeMs64();
DFHACK_EXPORT std::string stl_sprintf(const char *fmt, ...) Wformat(printf,1,2);
DFHACK_EXPORT std::string stl_vsprintf(const char *fmt, va_list args) Wformat(printf,1,0);
// Conversion between CP437 and UTF-8
DFHACK_EXPORT std::string UTF2DF(const std::string &in);
DFHACK_EXPORT std::string DF2UTF(const std::string &in);
DFHACK_EXPORT std::string DF2CONSOLE(const std::string &in);
DFHACK_EXPORT std::string DF2CONSOLE(DFHack::color_ostream &out, const std::string &in);
DFHACK_EXPORT std::string cxx_demangle(const std::string &mangled_name, std::string *status_out);