HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
narrow.h
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License.
3 
4 #pragma once
5 
6 // onnxruntime::narrow() is like gsl::narrow() but it is also available when exceptions are disabled.
7 
8 #if !defined(ORT_NO_EXCEPTIONS)
9 
10 #include "gsl/narrow"
11 
12 namespace onnxruntime {
13 using gsl::narrow;
14 } // namespace onnxruntime
15 
16 #else // ^^ !defined(ORT_NO_EXCEPTIONS) ^^ / vv defined(ORT_NO_EXCEPTIONS) vv
17 
18 #include <cstdio> // std::fprintf
19 #include <exception> // std::terminate
20 #include <type_traits>
21 
22 #include "gsl/util" // gsl::narrow_cast
23 
24 namespace onnxruntime {
25 
26 namespace detail {
27 [[noreturn]] inline void OnNarrowingError() noexcept {
28  std::fprintf(stderr, "%s", "narrowing error\n");
29  std::terminate();
30 }
31 } // namespace detail
32 
33 // This implementation of onnxruntime::narrow was copied and adapted from:
34 // https://github.com/microsoft/GSL/blob/a3534567187d2edc428efd3f13466ff75fe5805c/include/gsl/narrow
35 
36 // narrow() : a checked version of narrow_cast() that terminates if the cast changed the value
38 // clang-format off
39 GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
40  // clang-format on
41  constexpr T narrow(U u) noexcept {
42  constexpr const bool is_different_signedness =
44 
45  // clang-format off
46 GSL_SUPPRESS(es.103) // NO-FORMAT: attribute // don't overflow
47 GSL_SUPPRESS(es.104) // NO-FORMAT: attribute // don't underflow
48 GSL_SUPPRESS(p.2) // NO-FORMAT: attribute // don't rely on undefined behavior
49  // clang-format on
50  const T t = gsl::narrow_cast<T>(u); // While this is technically undefined behavior in some cases (i.e., if the source value is of floating-point type
51  // and cannot fit into the destination integral type), the resultant behavior is benign on the platforms
52  // that we target (i.e., no hardware trap representations are hit).
53 
54  if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{})))) {
55  detail::OnNarrowingError();
56  }
57 
58  return t;
59 }
60 
62 // clang-format off
63 GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
64  // clang-format on
65  constexpr T narrow(U u) noexcept {
66  const T t = gsl::narrow_cast<T>(u);
67 
68  if (static_cast<U>(t) != u) {
69  detail::OnNarrowingError();
70  }
71 
72  return t;
73 }
74 
75 } // namespace onnxruntime
76 
77 #endif // defined(ORT_NO_EXCEPTIONS)
GLsizei const GLfloat * value
Definition: glcorearb.h:824
auto fprintf(std::FILE *f, const S &fmt, const T &...args) -> int
Definition: printf.h:602
GLdouble t
Definition: glad.h:2397
if(num_boxed_items<=0)
Definition: UT_RTreeImpl.h:697
#define const
Definition: zconf.h:214
type
Definition: core.h:1059