aboutsummaryrefslogtreecommitdiff
path: root/include/gsl/gsl_narrow
blob: 7027b58854fbf18519331c497c5420d0f21a1866 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////

#ifndef GSL_NARROW_H
#define GSL_NARROW_H
#include <gsl/gsl_assert> // for Expects
#include <gsl/gsl_util> // for narrow_cast
namespace gsl
{
struct narrowing_error : public std::exception
{
};

// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template <class T, class U>
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // TODO: MSVC /analyze does not recognise noexcept(false)
constexpr
T narrow(U u) noexcept(false)
{
    constexpr const bool is_different_signedness = (std::is_signed<T>::value != std::is_signed<U>::value);

    const T t = narrow_cast<T>(u);

    if (static_cast<U>(t) != u
        || (is_different_signedness
            && ((t < T{}) != (u < U{}))))
    {
        throw narrowing_error{};
    }

    return t;
}
}
#endif // GSL_NARROW_H