Debian Codegraph @

src/utils/utils.hpp

raw
1 #ifndef UTILS_HPP
2 #define UTILS_HPP
3
4 #include <algorithm>
5 #include <cstdint>
6 #include <cstdio>
7 #include <cstdlib>
8 #include <cstring>
9 #include <memory>
10 #include <string>
11 #include <type_traits>
12 #include <utility>
13 #include <vector>
14
15 #include "utils/common.hpp"
16 #include "utils/error.hpp"
17 #include "utils/optional.hpp"
18 #include "utils/result.hpp"
19
20 CPPTRACE_BEGIN_NAMESPACE
21 namespace detail {
22 bool isatty(int fd);
23 int fileno(std::FILE* stream);
24
25 void enable_virtual_terminal_processing_if_needed() noexcept;
26
27 inline std::vector<std::string> split(const std::string& str, const std::string& delims) {
28 std::vector<std::string> vec;
29 std::size_t old_pos = 0;
30 std::size_t pos = 0;
31 while((pos = str.find_first_of(delims, old_pos)) != std::string::npos) {
32 vec.emplace_back(str.substr(old_pos, pos - old_pos));
33 old_pos = pos + 1;
34 }
35 vec.emplace_back(str.substr(old_pos));
36 return vec;
37 }
38
39 template<typename C>
40 std::string join(const C& container, const std::string& delim) {
41 auto iter = std::begin(container);
42 auto end = std::end(container);
43 std::string str;
44 if(std::distance(iter, end) > 0) {
45 str += *iter;
46 while(++iter != end) {
47 str += delim;
48 str += *iter;
49 }
50 }
51 return str;
52 }
53
54 // closest value in a sorted range such that *it <= value
55 template<typename ForwardIt, typename T>
56 ForwardIt first_less_than_or_equal(ForwardIt begin, ForwardIt end, const T& value) {
57 auto it = std::upper_bound(begin, end, value);
58 // it is first > value, we want first <= value
59 if(it != begin) {
60 return --it;
61 }
62 return end;
63 }
64
65 // closest value in a sorted range such that *it <= value
66 template<typename ForwardIt, typename T, typename Compare>
67 ForwardIt first_less_than_or_equal(ForwardIt begin, ForwardIt end, const T& value, Compare compare) {
68 auto it = std::upper_bound(begin, end, value, compare);
69 // it is first > value, we want first <= value
70 if(it != begin) {
71 return --it;
72 }
73 return end;
74 }
75
76 constexpr const char* const whitespace = " \t\n\r\f\v";
77
78 inline std::string trim(const std::string& str) {
79 if(str.empty()) {
80 return "";
81 }
82 const std::size_t left = str.find_first_not_of(whitespace);
83 const std::size_t right = str.find_last_not_of(whitespace) + 1;
84 return str.substr(left, right - left);
85 }
86
87 inline bool starts_with(const std::string& str, const std::string& prefix) {
88 return str.size() >= prefix.size() && str.compare(0, prefix.size(), prefix) == 0;
89 }
90
91 inline bool is_little_endian() {
92 std::uint16_t num = 0x1;
93 const auto* ptr = (std::uint8_t*)&num;
94 return ptr[0] == 1;
95 }
96
97 // Modified from
98 // https://stackoverflow.com/questions/105252/how-do-i-convert-between-big-endian-and-little-endian-values-in-c
99 template<typename T, std::size_t N>
100 struct byte_swapper;
101
102 template<typename T>
103 struct byte_swapper<T, 1> {
104 T operator()(T val) {
105 return val;
106 }
107 };
108
109 template<typename T>
110 struct byte_swapper<T, 2> {
111 T operator()(T val) {
112 return (((val >> 8) & 0xff) | ((val & 0xff) << 8));
113 }
114 };
115
116 template<typename T>
117 struct byte_swapper<T, 4> {
118 T operator()(T val) {
119 return (((val & 0xff000000) >> 24) |
120 ((val & 0x00ff0000) >> 8) |
121 ((val & 0x0000ff00) << 8) |
122 ((val & 0x000000ff) << 24));
123 }
124 };
125
126 template<typename T>
127 struct byte_swapper<T, 8> {
128 T operator()(T val) {
129 return (((val & 0xff00000000000000ULL) >> 56) |
130 ((val & 0x00ff000000000000ULL) >> 40) |
131 ((val & 0x0000ff0000000000ULL) >> 24) |
132 ((val & 0x000000ff00000000ULL) >> 8 ) |
133 ((val & 0x00000000ff000000ULL) << 8 ) |
134 ((val & 0x0000000000ff0000ULL) << 24) |
135 ((val & 0x000000000000ff00ULL) << 40) |
136 ((val & 0x00000000000000ffULL) << 56));
137 }
138 };
139
140 template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
141 T byteswap(T value) {
142 return byte_swapper<T, sizeof(T)>{}(value);
143 }
144
145 template<
146 typename T,
147 typename std::enable_if<std::is_arithmetic<T>::value && !std::is_signed<T>::value, int>::type = 0
148 >
149 constexpr bool is_positive_power_of_two(T value) {
150 return (value != 0) && (value & (value - 1)) == 0;
151 }
152
153 template<
154 typename T,
155 typename std::enable_if<std::is_arithmetic<T>::value && std::is_signed<T>::value, int>::type = 0
156 >
157 bool is_positive_power_of_two(T value) {
158 if(value < 0) {
159 return false;
160 }
161 return is_positive_power_of_two(static_cast<typename std::make_unsigned<T>::type>(value));
162 }
163
164 constexpr unsigned n_digits(unsigned value) noexcept {
165 return value < 10 ? 1 : 1 + n_digits(value / 10);
166 }
167
168 #if defined(__GNUC__) && (__GNUC__ < 5) && !defined(__clang__)
169 template<typename T>
170 using is_trivially_copyable = std::is_trivial<T>;
171 #else
172 template<typename T>
173 using is_trivially_copyable = std::is_trivially_copyable<T>;
174 #endif
175
176 // TODO: Re-evaluate use of off_t
177 template<
178 typename T,
179 typename std::enable_if<
180 std::is_standard_layout<T>::value && is_trivially_copyable<T>::value,
181 int
182 >::type = 0
183 >
184 Result<T, internal_error> load_bytes(std::FILE* object_file, off_t offset) {
185 T object;
186 if(std::fseek(object_file, offset, SEEK_SET) != 0) {
187 return internal_error("fseek error");
188 }
189 if(std::fread(&object, sizeof(T), 1, object_file) != 1) {
190 return internal_error("fread error");
191 }
192 return object;
193 }
194
195 // shamelessly stolen from stackoverflow
196 bool directory_exists(cstring_view path);
197
198 inline std::string basename(cstring_view path, bool maybe_windows = false) {
199 // Assumes no trailing /'s
200 auto pos = path.find_last_of(maybe_windows ? "/\\" : "/");
201 if(pos == cstring_view::npos) {
202 return std::string(path);
203 } else {
204 return std::string(path.substr(pos + 1));
205 }
206 }
207
208 // A way to cast to unsigned long long without "warning: useless cast to type"
209 template<typename T>
210 unsigned long long to_ull(T t) {
211 return static_cast<unsigned long long>(t);
212 }
213 template<typename T>
214 frame_ptr to_frame_ptr(T t) {
215 return static_cast<frame_ptr>(t);
216 }
217
218 // A way to cast to U without "warning: useless cast to type"
219 template<typename U, typename V>
220 U to(V v) {
221 return static_cast<U>(v);
222 }
223
224 template<typename T, typename U = T>
225 T exchange(T& obj, U&& value) {
226 T old = std::move(obj);
227 obj = std::forward<U>(value);
228 return old;
229 }
230
231 template<typename...>
232 using void_t = void;
233
234 struct monostate {};
235
236 // TODO: Rework some stuff here. Not sure deleters should be optional or moved.
237 // Also allow file_wrapper file = std::fopen(object_path.c_str(), "rb");
238 template<
239 typename T,
240 typename D,
241 // Note: Previously checked if D was invocable and returned void but this kept causing problems for MSVC
242 // == 19.38-specific msvc bug https://developercommunity.visualstudio.com/t/MSVC-1938331290-preview-fails-to-comp/10505565
243 // <= 19.23 msvc also appears to fail (but for a different reason https://godbolt.org/z/6Y5EvdWPK)
244 // <= 19.39 msvc also has trouble with it for different reasons https://godbolt.org/z/aPPPT7z3z
245 typename std::enable_if<
246 std::is_standard_layout<T>::value && is_trivially_copyable<T>::value,
247 int
248 >::type = 0,
249 typename std::enable_if<
250 std::is_nothrow_move_constructible<T>::value,
251 int
252 >::type = 0
253 >
254 class raii_wrapper {
255 T obj;
256 optional<D> deleter;
257 public:
258 raii_wrapper(T obj, D deleter) : obj(obj), deleter(deleter) {}
259 raii_wrapper(raii_wrapper&& other) noexcept : obj(std::move(other.obj)), deleter(std::move(other.deleter)) {
260 other.deleter = nullopt;
261 }
262 raii_wrapper(const raii_wrapper&) = delete;
263 raii_wrapper& operator=(raii_wrapper&&) = delete;
264 raii_wrapper& operator=(const raii_wrapper&) = delete;
265 ~raii_wrapper() {
266 if(deleter.has_value()) {
267 deleter.unwrap()(obj);
268 }
269 }
270 operator T&() {
271 return obj;
272 }
273 operator const T&() const {
274 return obj;
275 }
276 T& get() {
277 return obj;
278 }
279 const T& get() const {
280 return obj;
281 }
282 };
283
284 template<typename T, typename D>
285 raii_wrapper<typename std::remove_reference<T>::type, D> raii_wrap(T obj, D deleter) {
286 return raii_wrapper<typename std::remove_reference<T>::type, D>(obj, deleter);
287 }
288
289 inline void file_deleter(std::FILE* ptr) {
290 if(ptr) {
291 fclose(ptr);
292 }
293 }
294
295 using file_wrapper = raii_wrapper<std::FILE*, void(*)(std::FILE*)>;
296
297 template<typename T, typename... Args>
298 auto make_unique(Args&&... args) -> typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type {
299 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
300 }
301
302 template<typename T>
303 auto make_unique(T&& arg) -> typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type {
304 return std::unique_ptr<T>(new T(std::forward<T>(arg)));
305 }
306
307 template<typename T>
308 class maybe_owned {
309 std::unique_ptr<T> owned;
310 T* ptr;
311 public:
312 maybe_owned(T* ptr) : ptr(ptr) {}
313 maybe_owned(std::unique_ptr<T>&& owned) : owned(std::move(owned)), ptr(this->owned.get()) {}
314 T* operator->() {
315 return ptr;
316 }
317 T& operator*() {
318 return *ptr;
319 }
320 T* get() {
321 return ptr;
322 }
323 };
324
325 template<typename F>
326 class scope_guard {
327 F f;
328 bool active;
329 public:
330 template<
331 typename G,
332 typename std::enable_if<!std::is_same<typename std::decay<G>::type, scope_guard<F>>::value, int>::type = 0
333 >
334 scope_guard(G&& f) : f(std::forward<F>(f)), active(true) {}
335 ~scope_guard() {
336 if(active) {
337 f();
338 }
339 }
340 scope_guard(const scope_guard&) = delete;
341 scope_guard(scope_guard&& other) : f(std::move(other.f)), active(exchange(other.active, false)) {}
342 scope_guard& operator=(const scope_guard&) = delete;
343 scope_guard& operator=(scope_guard&& other) {
344 f = std::move(other.f);
345 active = exchange(other.active, false);
346 return *this;
347 }
348 };
349
350 template<typename F>
351 NODISCARD auto scope_exit(F&& f) -> scope_guard<F> {
352 return scope_guard<F>(std::forward<F>(f));
353 }
354 }
355 CPPTRACE_END_NAMESPACE
356
357 #endif