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