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 <utility> // IWYU pragma: keep (for swap)
12 : : #include <vector>
13 : :
14 : : template <typename T>
15 : 463 : constexpr void* gjs_int_to_pointer(T v) {
16 : : static_assert(std::is_integral_v<T>, "Need integer value");
17 : :
18 : : if constexpr (std::is_signed_v<T>)
19 : 324 : return reinterpret_cast<void*>(static_cast<intptr_t>(v));
20 : : else
21 : 139 : return reinterpret_cast<void*>(static_cast<uintptr_t>(v));
22 : : }
23 : :
24 : : template <typename T>
25 : 95 : constexpr T gjs_pointer_to_int(void* p) {
26 : : static_assert(std::is_integral_v<T>, "Need integer value");
27 : :
28 : : if constexpr (std::is_signed_v<T>)
29 : : return static_cast<T>(reinterpret_cast<intptr_t>(p));
30 : : else
31 : 95 : return static_cast<T>(reinterpret_cast<uintptr_t>(p));
32 : : }
33 : :
34 : : template <>
35 : 0 : inline void* gjs_int_to_pointer<bool>(bool v) {
36 : 0 : return gjs_int_to_pointer<int8_t>(!!v);
37 : : }
38 : :
39 : : template <>
40 : : inline bool gjs_pointer_to_int<bool>(void* p) {
41 : : return !!gjs_pointer_to_int<int8_t>(p);
42 : : }
43 : :
44 : : namespace Gjs {
45 : :
46 : : template <typename T>
47 : 13317 : inline bool remove_one_from_unsorted_vector(std::vector<T>* v, const T& value) {
48 : : // This assumes that there's only a copy of the same value in the vector
49 : : // so this needs to be ensured when populating it.
50 : : // We use the swap and pop idiom to avoid moving all the values.
51 : 13317 : auto it = std::find(v->begin(), v->end(), value);
52 [ + + ]: 13317 : if (it != v->end()) {
53 : 12069 : std::swap(*it, v->back());
54 : 12069 : v->pop_back();
55 : 12069 : g_assert(std::find(v->begin(), v->end(), value) == v->end());
56 : 12069 : return true;
57 : : }
58 : :
59 : 1248 : return false;
60 : : }
61 : :
62 : : } // namespace Gjs
|