Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
narrowing.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
15#include "shambase/string.hpp"
17#include <limits>
18#include <stdexcept>
19
27namespace shambase {
28
53 template<class U, class T>
54 constexpr bool can_narrow(T val) {
55 using lim_T = std::numeric_limits<T>;
56 using lim_U = std::numeric_limits<U>;
57
58 if constexpr (lim_T::is_integer && lim_U::is_integer) {
59 if constexpr (lim_T::is_signed) {
60 if constexpr (lim_U::is_signed) {
61 // signed -> signed
62 return val >= lim_U::min() && val <= lim_U::max();
63 } else {
64 // signed -> unsigned (cast to avoid compiler warning -Wsign-compare)
65 return val >= 0 && static_cast<std::make_unsigned_t<T>>(val) <= lim_U::max();
66 }
67 } else {
68 if constexpr (lim_U::is_signed) {
69 // unsigned -> signed (again cast to avoid warning -Wsign-compare)
71 } else {
72 // unsigned -> unsigned
73 return val <= lim_U::max();
74 }
75 }
76 } else {
77 static_assert(
78 shambase::always_false_v<T>, "can_narrow is not implemented for this type");
79 }
80 }
81
82 template<class U, class T>
83 inline U narrow_or_throw(T val, SourceLocation &&callsite = SourceLocation{}) {
84
86
87 if (can_narrow<U, T>(val)) {
88 return static_cast<U>(val);
89 } else {
90 using lim_U = std::numeric_limits<U>;
91 throw make_except_with_loc<std::runtime_error>(shambase::format(
92 "value {} cannot be narrowed to type U (see signature) static_cast<U>({}) = {} "
93 "(U::min() = {}, U::max() = {})",
94 val,
95 val,
96 static_cast<U>(val),
97 lim_U::min(),
98 lim_U::max()));
99 }
100 }
101
102 // When we will support it narrow_expected or narrow_or_expected would be nice
103
104} // namespace shambase
Source location utility.
This header file contains utility functions related to exception handling in the code.
namespace for basic c++ utilities
void throw_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Throw an exception and append the source location to it.
constexpr bool can_narrow(T val)
Check if an integer value can be safely narrowed to a target type.
Definition narrowing.hpp:54
Traits for C++ types.
This file contains the definition for the stacktrace related functionality.
#define __shamrock_log_callsite(callsite)
Macro to create a stack entry from a given location. Can be used only on SourceLocation &&.
provide information about the source location