OpenVPN 3 Core Library
Loading...
Searching...
No Matches
numeric_cast.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2023- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12
13
14#pragma once
15
16#include "numeric_util.hpp"
17
18#include <stdexcept>
19#include <cstdint>
20
21#include <openvpn/common/exception.hpp> // For OPENVPN_EXCEPTION_INHERIT
22
23/***
24 * @brief Exception type for numeric conversion failures
25 */
26OPENVPN_EXCEPTION_INHERIT(std::range_error, numeric_out_of_range);
27
28namespace openvpn::numeric_util {
29
30/* ============================================================================================================= */
31// numeric_cast
32/* ============================================================================================================= */
33
53template <typename OutT, typename InT>
54OutT numeric_cast(InT inVal)
55{
56 if constexpr (!numeric_util::is_int_rangesafe<OutT, InT>() && numeric_util::is_int_u2s<OutT, InT>())
57 {
58 // Conversion to uintmax_t should be safe for ::max() in all integral cases
59 if (static_cast<uintmax_t>(inVal) > static_cast<uintmax_t>(std::numeric_limits<OutT>::max()))
60 {
61 throw numeric_out_of_range("Range exceeded for unsigned --> signed integer conversion");
62 }
63 }
64 else if constexpr (!numeric_util::is_int_rangesafe<OutT, InT>() && numeric_util::is_int_s2u<OutT, InT>())
65 {
66 // This is certainly bad
67 if (inVal < 0)
68 throw numeric_out_of_range("Cannot store negative value for signed --> unsigned integer conversion");
69
70 // Is it possibly unsafe? If so do the runtime positive val range test
71 if constexpr (std::numeric_limits<OutT>::digits - 1 < std::numeric_limits<InT>::digits)
72 if (static_cast<uintmax_t>(inVal) > static_cast<uintmax_t>(std::numeric_limits<OutT>::max()))
73 throw numeric_out_of_range("Range exceeded for signed --> unsigned integer conversion");
74 }
75 else if constexpr (!numeric_util::is_int_rangesafe<OutT, InT>())
76 {
77 // We already know the in and out are sign compatible
78 if (std::numeric_limits<OutT>::min() > inVal || std::numeric_limits<OutT>::max() < inVal)
79 {
80 throw numeric_out_of_range("Range exceeded for integer conversion");
81 }
82 }
83
84 return static_cast<OutT>(inVal);
85}
86
87} // namespace openvpn::numeric_util
#define OPENVPN_EXCEPTION_INHERIT(B, C)
OutT numeric_cast(InT inVal)
Tests attempted casts to ensure the input value does not exceed the capacity of the output type.