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 GSL_SUPPRESS(type.1) constexpr T narrow(U u) noexcept {
39  constexpr const bool is_different_signedness =
41 
42  GSL_SUPPRESS(es.103) // don't overflow
43  GSL_SUPPRESS(es.104) // don't underflow
44  GSL_SUPPRESS(p.2) // don't rely on undefined behavior
45  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
46  // and cannot fit into the destination integral type), the resultant behavior is benign on the platforms
47  // that we target (i.e., no hardware trap representations are hit).
48 
49  if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{})))) {
50  detail::OnNarrowingError();
51  }
52 
53  return t;
54 }
55 
57 GSL_SUPPRESS(type.1) constexpr T narrow(U u) noexcept {
58  const T t = gsl::narrow_cast<T>(u);
59 
60  if (static_cast<U>(t) != u) {
61  detail::OnNarrowingError();
62  }
63 
64  return t;
65 }
66 
67 } // namespace onnxruntime
68 
69 #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
type
Definition: core.h:1059