RESTinio

safe_uint_truncate.hpp
Go to the documentation of this file.
1/*
2 * restinio
3 */
4
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>
25 struct safe_uint64_to_size_t {};
26
27 template<>
28 struct safe_uint64_to_size_t<true> {
29 static std::size_t
30 truncate(std::uint64_t v)
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
58 inline std::size_t
59 uint64_to_size_t(std::uint64_t v)
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 */
69
restinio::utils::impl::uint64_to_size_t
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...
Definition: safe_uint_truncate.hpp:59
restinio
Definition: asio_include.hpp:21
restinio::utils::impl::safe_uint64_to_size_t< false >::truncate
static std::size_t truncate(std::uint64_t v)
Definition: safe_uint_truncate.hpp:42
restinio::utils::impl::safe_uint64_to_size_t< true >::truncate
static std::size_t truncate(std::uint64_t v)
Definition: safe_uint_truncate.hpp:30
restinio::utils::impl::safe_uint64_to_size_t
Definition: safe_uint_truncate.hpp:25