forked from jclehner/bcm2-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.h
456 lines (369 loc) · 10.4 KB
/
util.h
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
/**
* bcm2-utils
* Copyright (C) 2016 Joseph Lehner <[email protected]>
*
* bcm2-utils is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* bcm2-utils is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bcm2-utils. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BCM2UTILS_UTIL_H
#define BCM2UTILS_UTIL_H
#include <boost/endian/conversion.hpp>
#include <boost/crc.hpp>
#include <system_error>
#include <type_traits>
#include <functional>
#include <stdexcept>
#include <typeinfo>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cstdarg>
#include <chrono>
#include <memory>
#include <cerrno>
#include <vector>
#include <string>
#include <list>
#include <ios>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <ws2def.h>
#else
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#endif
#ifdef BCM2CFG_WINXP
#define inet_ntop(af, src, dst, size) (*dst = '\0')
#define inet_pton(af, src, dst) 0
#endif
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(x) (std::extent<decltype(x)>::value)
#endif
namespace bcm2dump {
typedef void (*sigh_type)(int);
std::string trim(std::string str);
std::vector<std::string> split(const std::string& str, char delim, bool empties = true, size_t limit = 0);
inline bool contains(const std::string& haystack, const std::string& needle)
{
return haystack.find(needle) != std::string::npos;
}
inline bool starts_with(const std::string& haystack, const std::string& needle)
{
if (haystack.size() < needle.size()) {
return false;
} else {
return haystack.substr(0, needle.size()) == needle;
}
}
inline bool ends_with(const std::string& haystack, const std::string& needle)
{
if (haystack.size() < needle.size()) {
return false;
} else {
return haystack.substr(haystack.size() - needle.size()) == needle;
}
}
template<class T> std::string to_buf(const T& t)
{
return std::string(reinterpret_cast<const char*>(&t), sizeof(T));
}
template<class T> T extract(const std::string& data, std::string::size_type offset = 0)
{
return *reinterpret_cast<const T*>(data.substr(offset, sizeof(data)).c_str());
}
template<class T> void patch(std::string& data, std::string::size_type offset, const T& t)
{
data.replace(offset, sizeof(T), std::string(reinterpret_cast<const char*>(&t), sizeof(T)));
}
class bad_lexical_cast : public std::invalid_argument
{
public:
bad_lexical_cast(const std::string& str) : std::invalid_argument(str) {}
};
template<class T> T lexical_cast(const std::string& str, unsigned base = 10, bool all = true)
{
static std::istringstream istr;
istr.clear();
istr.str(str);
T t;
if (!base) {
if (str.size() > 2 && str.substr(0, 2) == "0x") {
base = 16;
} else {
base = 10;
}
}
if ((istr >> std::setbase(base) >> t)) {
if (!istr.eof() && base == 10) {
switch (istr.get()) {
case 'k':
case 'K':
t *= 1024;
break;
case 'm':
case 'M':
t *= 1024 * 1024;
break;
default:
throw bad_lexical_cast("invalid binary suffix in '" + str + "'");
}
}
int c = istr.get() & 0xff;
if (!all || (istr.eof() || !c)) {
return t;
}
}
throw bad_lexical_cast("conversion failed: '" + str + "' -> " + std::string(typeid(T).name()));
}
// without these, istr >> t will read only one char instead of parsing the number
template<> inline int8_t lexical_cast<int8_t>(const std::string& str, unsigned base, bool all)
{ return lexical_cast<int16_t>(str, base, all) & 0xff; }
template<> inline uint8_t lexical_cast<uint8_t>(const std::string& str, unsigned base, bool all)
{ return lexical_cast<uint16_t>(str, base, all) & 0xff; }
template<class T> std::string to_hex(const T& t, size_t width = sizeof(T) * 2)
{
std::ostringstream ostr;
ostr << std::setfill('0') << std::setw(width) << std::hex << t;
return ostr.str();
}
template<> inline std::string to_hex<char>(const char& c, size_t width)
{
return to_hex(c & 0xff, width);
}
template<> inline std::string to_hex<unsigned char>(const unsigned char& c, size_t width)
{
return to_hex(c & 0xff, width);
}
std::string to_hex(const std::string& buffer);
std::string from_hex(const std::string& hex);
// return the closest number lower than num that matches the requested alignment
template<class T> T align_left(const T& num, size_t alignment)
{
return num - (num % alignment);
}
// return the closest number higher than num that matches the requested alignment
template<class T> T align_right(const T& num, size_t alignment)
{
T rem = num % alignment;
return num + (rem ? alignment - rem : 0);
}
template<class T> typename T::value_type crc_generic(const void* buf, size_t size)
{
T crc;
crc.process_bytes(buf, size);
return crc.checksum();
}
inline uint16_t crc16_ccitt(const void* buf, size_t size)
{
return crc_generic<boost::crc_ccitt_type>(buf, size);
}
inline uint16_t crc16_ccitt(const std::string& buf)
{ return crc16_ccitt(buf.data(), buf.size()); }
inline uint32_t crc32(const std::string& buf)
{
return crc_generic<boost::crc_32_type>(buf.data(), buf.size());
}
class mstimer
{
public:
mstimer() { reset(); }
auto elapsed() const
{
return std::chrono::duration_cast<std::chrono::milliseconds>
(now() - m_start).count();
}
void reset()
{ m_start = now(); }
private:
typedef std::chrono::time_point<std::chrono::steady_clock> tpt;
tpt now() const
{ return std::chrono::steady_clock::now(); }
tpt m_start;
};
std::string transform(const std::string& str, std::function<int(int)> f);
std::string escape(std::string str, bool escape_quote = false);
template<class T> inline T be_to_h(T n)
{
return boost::endian::big_to_native(n);
}
template<class T> inline T le_to_h(T n)
{
return boost::endian::little_to_native(n);
}
template<class T> inline T h_to_be(T n)
{
return boost::endian::native_to_big(n);
}
template<class T> inline T h_to_le(T n)
{
return boost::endian::native_to_little(n);
}
template<typename T> using sp = std::shared_ptr<T>;
template<typename T> using csp = std::shared_ptr<const T>;
class scoped_ios_exceptions
{
public:
~scoped_ios_exceptions()
{
try {
m_ios.exceptions(m_saved);
} catch (...) {}
}
static scoped_ios_exceptions failbad(std::ios& ios)
{ return scoped_ios_exceptions(ios, std::ios::failbit | std::ios::badbit, false); }
static scoped_ios_exceptions none(std::ios& ios)
{ return scoped_ios_exceptions(ios, std::ios::goodbit, true); }
private:
scoped_ios_exceptions(std::ios& ios, std::ios::iostate except, bool replace)
: m_ios(ios), m_saved(ios.exceptions())
{
ios.exceptions(replace ? except : (m_saved | except));
}
std::ios& m_ios;
std::ios::iostate m_saved;
};
class cleaner
{
public:
cleaner(std::function<void()> init, std::function<void()> cleanup)
: m_cleanup(cleanup)
{
if (init) {
init();
}
}
cleaner(std::function<void()> cleanup) : cleaner(nullptr, cleanup) {}
~cleaner()
{ m_cleanup(); }
private:
std::function<void()> m_cleanup;
};
#define BCM2UTILS_LOGF_BODY(severity, format) \
va_list args; \
va_start(args, format); \
log(severity, format, args); \
va_end(args)
#define BCM2UTILS_DEF_LOGF(name, severity) \
static void name(const char* format, ...) __attribute__((format(printf, 1, 2))) \
{ \
BCM2UTILS_LOGF_BODY(severity, format); \
}
class logger
{
public:
static constexpr int trace = 0;
static constexpr int debug = 1;
static constexpr int verbose = 2;
static constexpr int info = 3;
static constexpr int warn = 4;
static constexpr int err = 5;
static std::ostream& log(int severity);
static void log(int severity, const char* format, va_list args);
static void log_io(const std::string& line, bool in);
static std::ostream& t()
{ return log(trace); }
static std::ostream& v()
{ return log(verbose); }
static std::ostream& d()
{ return log(debug); }
static std::ostream& i()
{ return log(info); }
static std::ostream& w()
{ return log(warn); }
static std::ostream& e()
{ return log(err); }
BCM2UTILS_DEF_LOGF(i, info);
BCM2UTILS_DEF_LOGF(v, verbose);
BCM2UTILS_DEF_LOGF(d, debug);
BCM2UTILS_DEF_LOGF(t, trace);
static void loglevel(int level)
{ s_loglevel = level; }
static int loglevel()
{ return s_loglevel; }
static void no_stdout(bool no_stdout = true)
{ s_no_stdout = no_stdout; }
static void set_logfile(const std::string& filename);
static std::list<std::string> get_last_io_lines()
{ return s_lines; }
private:
static std::list<std::string> s_lines;
static int s_loglevel;
static bool s_no_stdout;
};
class user_error : public std::runtime_error
{
public:
user_error(const std::string& what)
: std::runtime_error(what)
{}
};
class errno_error : public std::system_error
{
public:
errno_error(const std::string& what, int error = errno)
: std::system_error(error, std::system_category(), what), m_interrupted(error == EINTR)
{}
bool interrupted() const noexcept
{ return m_interrupted; }
private:
bool m_interrupted;
};
class getaddrinfo_category : public std::error_category
{
virtual const char* name() const noexcept override
{ return "getaddrinfo_category"; };
virtual std::string message(int condition) const override;
};
#ifdef _WIN32
class winapi_category : public std::error_category
{
virtual const char* name() const noexcept override
{ return "winapi_category"; };
virtual std::string message(int condition) const override;
};
class winapi_error : public std::system_error
{
public:
winapi_error(const std::string& what, DWORD error = GetLastError())
: std::system_error(error, winapi_category(), what)
{}
};
class winsock_error : public winapi_error
{
public:
winsock_error(const std::string& what, DWORD error = WSAGetLastError())
: winapi_error(what, error) {}
};
#endif
}
template<class T> struct bcm2dump_def_comparison_operators
{
friend bool operator!=(const T& lhs, const T& rhs)
{ return !(lhs == rhs); }
friend bool operator <=(const T& lhs, const T& rhs)
{ return lhs < rhs || lhs == rhs; }
friend bool operator>(const T& lhs, const T& rhs)
{ return !(lhs <= rhs); }
friend bool operator>=(const T& lhs, const T& rhs)
{ return !(lhs < rhs); }
};
#endif