Branch data Line data Source code
1 : : /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
2 : : // SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
3 : : // SPDX-FileCopyrightText: 2020 Marco Trevisan <marco.trevisan@canonical.com>
4 : :
5 : : #pragma once
6 : :
7 : : #include <config.h>
8 : :
9 : : #include <stdint.h>
10 : :
11 : : #include <algorithm> // IWYU pragma: keep (for find)
12 : : #include <utility> // IWYU pragma: keep (for swap)
13 : : #include <vector>
14 : :
15 : : template <typename T>
16 : 483 : constexpr void* gjs_int_to_pointer(T v) {
17 : : static_assert(std::is_integral_v<T>, "Need integer value");
18 : :
19 : : if constexpr (std::is_signed_v<T>)
20 : 334 : return reinterpret_cast<void*>(static_cast<intptr_t>(v));
21 : : else
22 : 149 : return reinterpret_cast<void*>(static_cast<uintptr_t>(v));
23 : : }
24 : :
25 : : template <typename T>
26 : 100 : constexpr T gjs_pointer_to_int(void* p) {
27 : : static_assert(std::is_integral_v<T>, "Need integer value");
28 : :
29 : : if constexpr (std::is_signed_v<T>)
30 : : return static_cast<T>(reinterpret_cast<intptr_t>(p));
31 : : else
32 : 100 : return static_cast<T>(reinterpret_cast<uintptr_t>(p));
33 : : }
34 : :
35 : : template <>
36 : 0 : inline void* gjs_int_to_pointer<bool>(bool v) {
37 : 0 : return gjs_int_to_pointer<int8_t>(!!v);
38 : : }
39 : :
40 : : template <>
41 : : inline bool gjs_pointer_to_int<bool>(void* p) {
42 : : return !!gjs_pointer_to_int<int8_t>(p);
43 : : }
44 : :
45 : : namespace Gjs {
46 : :
47 : : template <typename T>
48 : 15373 : inline bool remove_one_from_unsorted_vector(std::vector<T>* v, const T& value) {
49 : : // This assumes that there's only a copy of the same value in the vector
50 : : // so this needs to be ensured when populating it.
51 : : // We use the swap and pop idiom to avoid moving all the values.
52 : 15373 : auto it = std::find(v->begin(), v->end(), value);
53 [ + + ]: 15373 : if (it != v->end()) {
54 : 13975 : std::swap(*it, v->back());
55 : 13975 : v->pop_back();
56 : 13975 : g_assert(std::find(v->begin(), v->end(), value) == v->end());
57 : 13975 : return true;
58 : : }
59 : :
60 : 1398 : return false;
61 : : }
62 : :
63 : : } // namespace Gjs
|