pstore2
unsigned_cast.hpp
Go to the documentation of this file.
1 //===- include/pstore/support/unsigned_cast.hpp -----------*- mode: C++ -*-===//
2 //* _ _ _ *
3 //* _ _ _ __ ___(_) __ _ _ __ ___ __| | ___ __ _ ___| |_ *
4 //* | | | | '_ \/ __| |/ _` | '_ \ / _ \/ _` | / __/ _` / __| __| *
5 //* | |_| | | | \__ \ | (_| | | | | __/ (_| | | (_| (_| \__ \ |_ *
6 //* \__,_|_| |_|___/_|\__, |_| |_|\___|\__,_| \___\__,_|___/\__| *
7 //* |___/ *
8 //===----------------------------------------------------------------------===//
9 //
10 // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
11 // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
12 // information.
13 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
14 //
15 //===----------------------------------------------------------------------===//
19 #ifndef PSTORE_SUPPORT_UNSIGNED_CAST_HPP
20 #define PSTORE_SUPPORT_UNSIGNED_CAST_HPP
21 
22 #include "pstore/support/error.hpp"
23 
24 namespace pstore {
25 
26  template <typename SrcT, typename DestT = std::make_unsigned_t<typename std::remove_cv_t<SrcT>>,
27  typename = typename std::enable_if<std::is_integral<SrcT>::value &&
28  std::is_unsigned<DestT>::value>::type>
29  constexpr DestT unsigned_cast (SrcT const value) noexcept {
30  static_assert (
31  std::numeric_limits<DestT>::max () >=
32  std::numeric_limits<std::make_unsigned_t<typename std::remove_cv_t<SrcT>>>::max (),
33  "DestT cannot hold all of the values of SrcT");
34  PSTORE_ASSERT (value >= SrcT{0});
35  return static_cast<DestT> (value);
36  }
37 
38  template <typename SrcT, typename DestT = std::make_unsigned_t<typename std::remove_cv_t<SrcT>>,
39  typename = typename std::enable_if<std::is_integral<SrcT>::value &&
40  std::is_unsigned<DestT>::value>::type>
41  constexpr DestT checked_unsigned_cast (SrcT const value) {
42  if (value < SrcT{0}) {
43  raise (std::errc::invalid_argument, "bad cast to unsigned");
44  }
45  return unsigned_cast<SrcT, DestT> (value);
46  }
47 
48 } // end namespace pstore
49 
50 #endif // PSTORE_SUPPORT_UNSIGNED_CAST_HPP
Definition: nonpod2.cpp:40
Provides an pstore-specific error codes and a suitable error category for them.