-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.h
194 lines (159 loc) · 7.19 KB
/
utils.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
/* clang-format off */
/*****************************************************************************
The MIT License
Copyright © 2013 Pavel Karelin (hkarel), <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
В модуле собраны сервисные функции общего назначения.
*****************************************************************************/
#pragma once
#include <cctype>
#include <ctime>
#include <atomic>
#include <string>
#include <cstdarg>
#include <streambuf>
#include <vector>
#include <numeric>
#include <algorithm>
#if __cplusplus >= 201703L
#include <charconv>
#endif
namespace utl {
using namespace std;
/**
Сервисная структура, позволяет ассоциировать линейный буфер в памяти
с потоковыми механизмами.
*/
struct MemBuff : std::streambuf
{
MemBuff(char* base, size_t size)
{
//char* p((char*>(base));
this->setg(base, base, base + size);
}
};
// Функции удаления пробелов в начале и конце строки
string& ltrim(string&);
string& rtrim(string&);
string& trim(string&);
// Устанавливает текущую директорию по имени исполняемого файла.
bool setCurrentDir(char* binaryPath);
// Записывает PID в файл.
void savePidFile(const string& fileName);
// Аналог функции sprintf, в качестве результата возвращает отформатированную
// строку
#ifdef __GNUC__
template<typename std::size_t BuffSize = 1024>
string formatMessage(const char* format, ...) __attribute__ ((format (printf, 1, 2)));
#else
template<typename std::size_t BuffSize = 1024>
string formatMessage(const char* format, ...);
#endif
// Функция изменяет значение атомарного флага, используется в тех случаях,
// когда нужно избежать постоянного присвоения одного и того же значения
// атомарной переменной. В примере ниже переменной atomic_val постоянно
// присваивается значения true. Каждое присвоение приводит к сбросу линии
// кеша процессора, что снижает производительность.
// while (true) {
// ...
// if (true)
// atomic_val = true
// }
inline bool assign(atomic_bool& a, bool value)
{
bool b = !value;
return a.compare_exchange_strong(b, value);
}
// Выполняет преобразование в строку
#if __cplusplus >= 201703L
template<typename T>
string toString(T val, enable_if_t<is_integral<T>::value, int> = 0)
{
char buff[32];
to_chars_result res = to_chars(buff, buff + sizeof(buff), val);
if (res.ec == std::errc())
{
*res.ptr = '\0';
return buff;
}
return {};
}
#else
string toString(short val);
string toString(unsigned short val);
string toString(int val);
string toString(unsigned int val);
string toString(long val);
string toString(unsigned long val);
string toString(long long val);
string toString(unsigned long long val);
#endif
// Выполняет преобразование UUID в строковое представление.
string uuidToString(const uint8_t uuid[16]);
// Аналогична функции uuidToString(const uint8_t uuid[16]), но результат пишется
// в параметр result.
void uuidToString(const uint8_t uuid[16], uint8_t result[40]);
// Выполняет преобразование UUID в шестнадцатеричное строковое представление.
// Параметр addHexPrefix определяет будет ли в начало результирующей строки
// добавлен признак шестнадцатеричного представления '0x'.
string uuidToHexString(const uint8_t uuid[16], bool addHexPrefix = true);
// Аналог функции uuidToHexString(const uint8_t uuid[16], bool addHexPrefix),
// но результат пишется в параметр result.
void uuidToHexString(const uint8_t uuid[16], uint8_t result[40], bool addHexPrefix);
// Разделяет строку на список строк согласно указанному разделителю.
// str - исходная строка;
// delim - разделитель;
// keepEmptyParts - сохранять в результирующем списке пустые строки.
vector<string> split(const string& str, char delim, bool keepEmptyParts = false);
// Выполняет примитивное (не математическое) округление действительного числа
// number до signCount знаков после запятой
double round(double number, int signCount);
// Функции сложения/вычитания структур timeval. Они повторяют макросы
// timeradd/timersub, но в MinGW эти макросы не реализованы.
void timeAdd(const timespec& a, const timespec& b, timespec& result);
void timeSub(const timespec& a, const timespec& b, timespec& result);
// Возвращает сумму элементов списка
template<typename T>
typename T::value_type sum(const T& elements);
// Возвращает среднее арифметическое элементов списка
template<typename T>
double average(const T& elements);
//----------------------------- Implementation -------------------------------
template<typename std::size_t BuffSize>
string formatMessage(const char* format, ...)
{
char buff[BuffSize] = {0};
va_list argptr;
va_start(argptr, format);
vsnprintf(buff, BuffSize - 1, format, argptr);
va_end(argptr);
return buff;
}
template<typename T>
typename T::value_type sum(const T& elements)
{
return std::accumulate(elements.begin(), elements.end(), typename T::value_type(0));
}
template<typename T>
double average(const T& elements)
{
double s = sum(elements);
return (s / elements.size());
}
} // namespace utl