numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
safe_cast.h
Go to the documentation of this file.
1/*
2 * Copyright 2021 MusicScience37 (Kenta Kabashima)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
20#pragma once
21
22// IWYU pragma: no_include <string_view>
23// IWYU pragma: no_include "num_collect/util/source_info_view.h"
24
25#include <limits>
26#include <type_traits> // IWYU pragma: keep
27#include <typeinfo>
28
29#include <fmt/format.h> // IWYU pragma: keep
30
34
35namespace num_collect::util {
36
41public:
42 using num_collect_exception::num_collect_exception;
43};
44
53template <base::concepts::integral To, base::concepts::integral From>
54[[nodiscard]] inline auto safe_cast(const From& value) -> To {
55 // Check upper bound.
56 if constexpr (std::numeric_limits<To>::digits <
57 std::numeric_limits<From>::digits) {
58 if (value > static_cast<From>(std::numeric_limits<To>::max())) {
60 "unsafe cast of value {} from {} to {} (upper bound)", value,
61 typeid(From).name(), typeid(To).name());
62 }
63 }
64
65 // Check lower bound.
66 if constexpr (std::is_signed_v<From> && std::is_unsigned_v<To>) {
67 if (value < static_cast<From>(0)) {
69 "unsafe cast of value {} from {} to {} (lower bound)", value,
70 typeid(From).name(), typeid(To).name());
71 }
72 }
73 if constexpr (std::is_signed_v<From> && std::is_signed_v<To> &&
74 (std::numeric_limits<To>::digits < std::numeric_limits<From>::digits)) {
75 if (value < static_cast<From>(std::numeric_limits<To>::min())) {
77 "unsafe cast of value {} from {} to {} (lower bound)", value,
78 typeid(From).name(), typeid(To).name());
79 }
80 }
81
82 return static_cast<To>(value);
83}
84
85} // namespace num_collect::util
Class of exception in this project.
Definition exception.h:53
Class of exception on unsafe casts.
Definition safe_cast.h:40
Definition of exceptions.
Definition of integral concept.
Definition of macros for logging.
#define NUM_COLLECT_LOG_AND_THROW(EXCEPTION_TYPE,...)
Write an error log and throw an exception for an error.
Namespace of utilities.
Definition assert.h:30
auto safe_cast(const From &value) -> To
Cast safely.
Definition safe_cast.h:54