Skip to content

Commit

Permalink
Document safe usage of undefined behavior in gsl::narrow (microsoft#1024
Browse files Browse the repository at this point in the history
)
  • Loading branch information
dmitrykobets-msft authored Jan 27, 2022
1 parent ebf0498 commit 99a29ce
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion include/gsl/narrow
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // TODO: MSVC /analyze does not recogn
constexpr const bool is_different_signedness =
(std::is_signed<T>::value != std::is_signed<U>::value);

const T t = narrow_cast<T>(u);
GSL_SUPPRESS(es.103) // NO-FORMAT: attribute // don't overflow
GSL_SUPPRESS(es.104) // NO-FORMAT: attribute // don't underflow
GSL_SUPPRESS(p.2) // NO-FORMAT: attribute // don't rely on undefined behavior
const T t = narrow_cast<T>(u); // While this is technically undefined behavior in some cases (i.e., if the source value is of floating-point type
// and cannot fit into the destination integral type), the resultant behavior is benign on the platforms
// that we target (i.e., no hardware trap representations are hit).

if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{}))))
{
Expand Down

0 comments on commit 99a29ce

Please sign in to comment.