safe_conversion.hpp
Go to the documentation of this file.
1/*
2 Copyright 2023 SINTEF AS
3
4 This file is part of the Open Porous Media project (OPM).
5
6 OPM is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 OPM is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with OPM. If not, see <http://www.gnu.org/licenses/>.
18*/
19#ifndef OPM_CUISTL_SAFE_CONVERSION_HPP
20#define OPM_CUISTL_SAFE_CONVERSION_HPP
21
22
23
24#include <cstddef>
25#include <fmt/format.h>
26#include <limits>
27#include <opm/common/ErrorMacros.hpp>
28#include <type_traits>
29
30
39namespace Opm::cuistl::detail
40{
41
50inline int
51to_int(std::size_t s)
52{
53 static_assert(
54 std::is_signed_v<int>,
55 "Weird architecture or my understanding of the standard is flawed. Better have a look at this function.");
56 static_assert(
57 !std::is_signed_v<std::size_t>,
58 "Weird architecture or my understanding of the standard is flawed. Better have a look at this function.");
59
60 static_assert(
61 sizeof(int) <= sizeof(std::size_t),
62 "Weird architecture or my understanding of the standard is flawed. Better have a look at this function.");
63
64
65 if (s > std::size_t(std::numeric_limits<int>::max())) {
66 OPM_THROW(std::invalid_argument,
67 fmt::format("Trying to convert {} to int, but it is out of range. Maximum possible int: {}. ",
68 s,
69 std::numeric_limits<int>::max()));
70 }
71
72 // We know it will be in range here:
73 return int(s);
74}
75
84inline std::size_t
86{
87 static_assert(
88 std::is_signed_v<int>,
89 "Weird architecture or my understanding of the standard is flawed. Better have a look at this function.");
90 static_assert(
91 !std::is_signed_v<std::size_t>,
92 "Weird architecture or my understanding of the standard is flawed. Better have a look at this function.");
93
94 static_assert(
95 sizeof(int) <= sizeof(std::size_t),
96 "Weird architecture or my understanding of the standard is flawed. Better have a look at this function.");
97
98
99 if (i < int(0)) {
100 OPM_THROW(std::invalid_argument, fmt::format("Trying to convert the negative number {} to size_t.", i));
101 }
102
103 return std::size_t(i);
104}
105} // namespace Opm::cuistl::detail
106
107#endif
Definition: cublas_safe_call.hpp:32
int to_int(std::size_t s)
to_int converts a (on most relevant platforms) 64 bits unsigned size_t to a signed 32 bits signed int
Definition: safe_conversion.hpp:51
std::size_t to_size_t(int i)
to_size_t converts a (on most relevant platforms) a 32 bit signed int to a 64 bits unsigned int
Definition: safe_conversion.hpp:85