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
18namespace restinio {
19
20namespace utils {
21
22namespace impl {
23
24template<bool Is_Uint64_Longer>
26
27template<>
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
39template<>
40struct 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
58inline std::size_t
59uint64_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
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...