RESTinio
safe_uint_truncate.hpp
Go to the documentation of this file.
1 /*
2  * restinio
3  */
4 
5 /*!
6  * \file
7  * \brief Helpers for safe truncation of unsigned integers.
8  */
9 
10 #pragma once
11 
12 #include <stdexcept>
13 #include <type_traits>
14 #include <limits>
15 #include <cstddef>
16 #include <cstdint>
17 
18 namespace restinio {
19 
20 namespace utils {
21 
22 namespace impl {
23 
24 template<bool Is_Uint64_Longer>
26 
27 template<>
28 struct safe_uint64_to_size_t<true> {
29  static std::size_t
31  {
32  if( v > static_cast<std::uint64_t>(std::numeric_limits<std::size_t>::max()) )
33  throw std::runtime_error( "64-bit value can't be safely truncated "
34  "into std::size_t type" );
35  return static_cast<std::size_t>(v);
36  }
37 };
38 
39 template<>
40 struct safe_uint64_to_size_t<false> {
41  static std::size_t
42  truncate(std::uint64_t v) { return static_cast<std::size_t>(v); }
43 };
44 
45 /*!
46  * \brief Helper function for truncating uint64 to std::size_t with
47  * exception if that truncation will lead to data loss.
48  *
49  * A check of \a v is performed only if std::size_t has less capacity
50  * than std::uint64_t (for example on 32-bit systems).
51  *
52  * \throw std::runtime_error if the value of \a v can't truncated to
53  * std::size_t without loss of data.
54  *
55  * \since
56  * v.0.4.1
57  */
58 inline std::size_t
60 {
61  return safe_uint64_to_size_t<(sizeof(std::uint64_t) > sizeof(std::size_t))>::truncate(v);
62 }
63 
64 } /* namespace impl */
65 
66 } /* namespace utils */
67 
68 } /* namespace restinio */
string_view_t from_string< string_view_t >(string_view_t s)
Get a value from string_view.
std::size_t uint64_to_size_t(std::uint64_t v)
Helper function for truncating uint64 to std::size_t with exception if that truncation will lead to d...
std::enable_if< std::is_same< Parameter_Container, query_string_params_t >::value||std::is_same< Parameter_Container, router::route_params_t >::value, optional_t< Value_Type > >::type opt_value(const Parameter_Container &params, string_view_t key)
Gets the value of a parameter specified by key wrapped in optional_t<Value_Type> if parameter exists ...
Definition: value_or.hpp:64