File: utils.h

package info (click to toggle)
cppcheck 2.17.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 25,384 kB
  • sloc: cpp: 263,341; python: 19,737; ansic: 7,953; sh: 1,018; makefile: 996; xml: 994; cs: 291
file content (432 lines) | stat: -rw-r--r-- 11,131 bytes parent folder | download
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
/* -*- C++ -*-
 * Cppcheck - A tool for static C/C++ code analysis
 * Copyright (C) 2007-2025 Cppcheck team.
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

//---------------------------------------------------------------------------
#ifndef utilsH
#define utilsH
//---------------------------------------------------------------------------

#include "config.h"

#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

struct SelectMapKeys {
    template<class Pair>
    // NOLINTNEXTLINE(readability-const-return-type) - false positive
    typename Pair::first_type operator()(const Pair& p) const {
        return p.first;
    }
};

struct SelectMapValues {
    template<class Pair>
    typename Pair::second_type operator()(const Pair& p) const {
        return p.second;
    }
};

struct OnExit {
    std::function<void()> f;

    ~OnExit() {
        f();
    }
};

template<class Range, class T>
bool contains(const Range& r, const T& x)
{
    return std::find(r.cbegin(), r.cend(), x) != r.cend();
}

template<class T>
bool contains(const std::initializer_list<T>& r, const T& x)
{
    return std::find(r.begin(), r.end(), x) != r.end();
}

template<class T, class U>
bool contains(const std::initializer_list<T>& r, const U& x)
{
    return std::find(r.begin(), r.end(), x) != r.end();
}

template<class T, class ... Ts>
inline std::array<T, sizeof...(Ts) + 1> makeArray(T x, Ts... xs)
{
    return {std::move(x), std::move(xs)...};
}

// Enum hash for C++11. This is not needed in C++14
struct EnumClassHash {
    template<typename T>
    std::size_t operator()(T t) const
    {
        return static_cast<std::size_t>(t);
    }
};

inline bool startsWith(const std::string& str, const char start[], std::size_t startlen)
{
    return str.compare(0, startlen, start) == 0;
}

template<std::size_t N>
bool startsWith(const std::string& str, const char (&start)[N])
{
    return startsWith(str, start, N - 1);
}

inline bool startsWith(const std::string& str, const std::string& start)
{
    return startsWith(str, start.c_str(), start.length());
}

inline bool endsWith(const std::string &str, char c)
{
    return !str.empty() && str.back() == c;
}

inline bool endsWith(const std::string &str, const char end[], std::size_t endlen)
{
    return (str.size() >= endlen) && (str.compare(str.size()-endlen, endlen, end)==0);
}

template<std::size_t N>
bool endsWith(const std::string& str, const char (&end)[N])
{
    return endsWith(str, end, N - 1);
}

inline static bool isPrefixStringCharLiteral(const std::string &str, char q, const std::string& p)
{
    // str must be at least the prefix plus the start and end quote
    if (str.length() < p.length() + 2)
        return false;

    // check for end quote
    if (!endsWith(str, q))
        return false;

    // check for start quote
    if (str[p.size()] != q)
        return false;

    // check for prefix
    if (str.compare(0, p.size(), p) != 0)
        return false;

    return true;
}

inline static bool isStringCharLiteral(const std::string &str, char q)
{
    // early out to avoid the loop
    if (!endsWith(str, q))
        return false;

    static const std::array<std::string, 5> suffixes{"", "u8", "u", "U", "L"};
    return std::any_of(suffixes.cbegin(), suffixes.cend(), [&](const std::string& p) {
        return isPrefixStringCharLiteral(str, q, p);
    });
}

inline static bool isStringLiteral(const std::string &str)
{
    return isStringCharLiteral(str, '"');
}

inline static bool isCharLiteral(const std::string &str)
{
    return isStringCharLiteral(str, '\'');
}

inline static std::string getStringCharLiteral(const std::string &str, char q)
{
    const std::size_t quotePos = str.find(q);
    return str.substr(quotePos + 1U, str.size() - quotePos - 2U);
}

inline static std::string getStringLiteral(const std::string &str)
{
    if (isStringLiteral(str))
        return getStringCharLiteral(str, '"');
    return "";
}

inline static std::string getCharLiteral(const std::string &str)
{
    if (isCharLiteral(str))
        return getStringCharLiteral(str, '\'');
    return "";
}

inline static const char *getOrdinalText(int i)
{
    if (i == 1)
        return "st";
    if (i == 2)
        return "nd";
    if (i == 3)
        return "rd";
    return "th";
}

CPPCHECKLIB int caseInsensitiveStringCompare(const std::string& lhs, const std::string& rhs);

CPPCHECKLIB bool isValidGlobPattern(const std::string& pattern);

CPPCHECKLIB bool matchglob(const std::string& pattern, const std::string& name);

CPPCHECKLIB bool matchglobs(const std::vector<std::string> &patterns, const std::string &name);

CPPCHECKLIB void strTolower(std::string& str);

template<typename T, typename std::enable_if<std::is_signed<T>::value, bool>::type=true>
bool strToInt(const std::string& str, T &num, std::string* err = nullptr)
{
    long long tmp;
    try {
        std::size_t idx = 0;
        tmp = std::stoll(str, &idx);
        if (idx != str.size()) {
            if (err)
                *err = "not an integer";
            return false;
        }
    } catch (const std::out_of_range&) {
        if (err)
            *err = "out of range (stoll)";
        return false;
    } catch (const std::invalid_argument &) {
        if (err)
            *err = "not an integer";
        return false;
    }
    if (str.front() == '-' && std::numeric_limits<T>::min() == 0) {
        if (err)
            *err = "needs to be positive";
        return false;
    }
    if (tmp < std::numeric_limits<T>::min() || tmp > std::numeric_limits<T>::max()) {
        if (err)
            *err = "out of range (limits)";
        return false;
    }
    num = static_cast<T>(tmp);
    return true;
}

template<typename T, typename std::enable_if<std::is_unsigned<T>::value, bool>::type=true>
bool strToInt(const std::string& str, T &num, std::string* err = nullptr)
{
    unsigned long long tmp;
    try {
        std::size_t idx = 0;
        tmp = std::stoull(str, &idx);
        if (idx != str.size()) {
            if (err)
                *err = "not an integer";
            return false;
        }
    } catch (const std::out_of_range&) {
        if (err)
            *err = "out of range (stoull)";
        return false;
    } catch (const std::invalid_argument &) {
        if (err)
            *err = "not an integer";
        return false;
    }
    if (str.front() == '-') {
        if (err)
            *err = "needs to be positive";
        return false;
    }
    if (tmp > std::numeric_limits<T>::max()) {
        if (err)
            *err = "out of range (limits)";
        return false;
    }
    num = tmp;
    return true;
}

template<typename T>
T strToInt(const std::string& str)
{
    T tmp = 0;
    std::string err;
    if (!strToInt(str, tmp, &err))
        throw std::runtime_error("converting '" + str + "' to integer failed - " + err);
    return tmp;
}

/**
 *  Simple helper function:
 * \return size of array
 * */
template<typename T, int size>
// cppcheck-suppress unusedFunction - only used in conditional code
std::size_t getArrayLength(const T (& /*unused*/)[size])
{
    return size;
}

/**
 * @brief get id string. i.e. for dump files
 * it will be a hexadecimal output.
 */
static inline std::string id_string_i(std::uintptr_t l)
{
    if (!l)
        return "0";

    static constexpr int ptr_size = sizeof(void*);

    // two characters of each byte / contains terminating \0
    static constexpr int buf_size = (ptr_size * 2) + 1;

    char buf[buf_size];

    // needs to be signed so we don't underflow in padding loop
    int idx = buf_size - 1;
    buf[idx] = '\0';

    while (l != 0)
    {
        char c;
        const std::uintptr_t temp = l % 16; // get the remainder
        if (temp < 10) {
            // 0-9
            c = '0' + temp;
        }
        else {
            // a-f
            c = 'a' + (temp - 10);
        }
        buf[--idx] = c; // store in reverse order
        l = l / 16;
    }

    return &buf[idx];
}

static inline std::string id_string(const void* p)
{
    return id_string_i(reinterpret_cast<std::uintptr_t>(p));
}

static inline const char* bool_to_string(bool b)
{
    return b ? "true" : "false";
}

/**
 * Remove heading and trailing whitespaces from the input parameter.
 * If string is all spaces/tabs, return empty string.
 * @param s The string to trim.
 * @param t The characters to trim.
 */
CPPCHECKLIB std::string trim(const std::string& s, const std::string& t = " \t");

/**
 * Replace all occurrences of searchFor with replaceWith in the
 * given source.
 * @param source The string to modify
 * @param searchFor What should be searched for
 * @param replaceWith What will replace the found item
 */
CPPCHECKLIB void findAndReplace(std::string &source, const std::string &searchFor, const std::string &replaceWith);

/**
 * Replace all escape sequences in the given string.
 * @param source The string that contains escape sequences
 */
CPPCHECKLIB std::string replaceEscapeSequences(const std::string &source);

namespace cppcheck
{
    NORETURN inline void unreachable()
    {
#if defined(__GNUC__)
        __builtin_unreachable();
#elif defined(_MSC_VER)
        __assume(false);
#else
#error "no unreachable implementation"
#endif
    }
}

template<typename T>
static inline T* default_if_null(T* p, T* def)
{
    return p ? p : def;
}

template<typename T>
static inline T* empty_if_null(T* p)
{
    return default_if_null(p, "");
}

/**
 * Split string by given sperator.
 * @param str The string to split
 * @param sep The seperator
 * @return The list of seperate strings (including empty ones). The whole input string if no seperator found.
 */
CPPCHECKLIB std::vector<std::string> splitString(const std::string& str, char sep);

namespace utils {
    template<class T>
    constexpr typename std::add_const<T>::type & as_const(T& t) noexcept
    {
        // NOLINTNEXTLINE(bugprone-return-const-ref-from-parameter) - potential false positive
        return t;
    }

    // Thread-unsafe memoization
    template<class F, class R=decltype(std::declval<F>()())>
    static inline std::function<R()> memoize(F f)
    {
        bool init = false;
        R result{};
        return [=]() mutable -> R {
            if (init)
                return result;
            result = f();
            init = true;
            return result;
        };
    }
}

#endif