Fix undefined behaviour in float<->int conversion
authorMarcus Holland-Moritz <mhx@fb.com>
Thu, 23 Jun 2016 03:28:36 +0000 (20:28 -0700)
committerFacebook Github Bot 3 <facebook-github-bot-3-bot@fb.com>
Thu, 23 Jun 2016 03:38:32 +0000 (20:38 -0700)
commit47868e4911bee74582d605195525bafa889252d9
tree6376ff00dc3ac1c2fe76ffd87fb8c87a80c8a22e
parentc1d4dcfe934f7c902b7a38a8c9fbd02c9d7b0640
Fix undefined behaviour in float<->int conversion

Summary:
This change fixes a case of undefined behaviour when converting between
floating point and integral values using folly::to<>. Undefined behaviour
is triggered when a floating point value is cast into an integral value
that cannot represent the source value. This happens in both cases,
float-to-int and int-to-float conversion, with folly::to<> due to the
check for loss of precision.

The new test cases expose the undefined behaviour.

The fix is a series of extra checks, the majority of which will only
kick in if the value to be converted is close to the boundary of the
range of the target type. These checks ensure that the conversion will
only be performed if the source value is within the range representable
by the target type.

The extra checks /will/ make the code slower. However, a later change
in this series, which refactors the implementation of folly::to<>, will
restore some of the performance.

Reviewed By: yfeldblum

Differential Revision: D3433757

fbshipit-source-id: 43495d18f831206ef48f74332663263d789a4f8a
folly/Conv.h
folly/test/ConvTest.cpp