LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
secure_cast.h
Go to the documentation of this file.
1// Copyright 2002-2022 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#ifndef DEEPLIMA_INCLUDE_SECURE_CAST_H
7#define DEEPLIMA_INCLUDE_SECURE_CAST_H
8
9#include <limits>
10#include <stdexcept>
11
12namespace deeplima
13{
14namespace utils
15{
16
17template <typename To, typename From>
18inline To cast_to_signed(const From arg)
19{
20 static_assert(std::numeric_limits<To>::min() < 0,
21 "cast_to_signed used in incorrect context (To, min)");
22
23 static_assert(std::numeric_limits<From>::min() == 0,
24 "cast_to_signed used in incorrect context (From, min)");
25
26 static_assert(std::numeric_limits<To>::max() < std::numeric_limits<From>::max(),
27 "cast_to_signed used in incorrect context (max)");
28
29 if (arg <= static_cast<From>(std::numeric_limits<To>::max()))
30 {
31 return static_cast<To>(arg);
32 }
33
34 throw std::overflow_error("cast_to_signed: argument is too big");
35}
36
37} // namespace utils
38} // namespace deeplima
39
40#endif
To cast_to_signed(const From arg)
Definition secure_cast.h:18