Commit f3dfa82a authored by Yedidya Feldblum's avatar Yedidya Feldblum Committed by Facebook Github Bot

Define to_narrow in terms of implicit conversion

Summary:
[Folly] Define `to_narrow` in terms of implicit conversion to take advantage of ubsan's truncation checks.

Note that integer truncation is not undefined behavior per se but is commonly unintended, so ubsan checks for it. Uses of `to_narrow` should not be subject to truncation; wherever truncation is anticipated, better to use an explicit conversion with a named destination type.

Requires suppressing `-Wconversion` around the implicit conversion to avoid extraneous warnings and errors when the compiler detects narrowing implicit conversions. Since `to_narrow` models explicit conversion while merely being defined in terms of implicit conversion, it is already anticipated by all users that a narrowing conversion may occur; the warning is there to inform users only about unanticipated cases.

Reviewed By: luciang

Differential Revision: D19201430

fbshipit-source-id: b3739d3d9aa05e95f7b3e4dff54e719691c1f04c
parent 186cd823
......@@ -329,7 +329,10 @@ class to_narrow_convertible {
std::is_signed<Dst>::value == std::is_signed<Src>::value,
int> = 0>
/* implicit */ constexpr operator Dst() const noexcept {
return static_cast<Dst>(value_);
FOLLY_PUSH_WARNING
FOLLY_GNU_DISABLE_WARNING("-Wconversion")
return value_;
FOLLY_POP_WARNING
}
private:
......@@ -342,6 +345,13 @@ class to_narrow_convertible {
// without specifying the destination type. Does not permit changing signs.
// Sometimes preferable to static_cast<Dst>(src) to document the intended
// semantics of the cast.
//
// Models explicit conversion with an elided destination type. Sits in between
// a stricter explicit conversion with a named destination type and a more
// lenient implicit conversion. Implemented with implicit conversion in order
// to take advantage of the undefined-behavior sanitizer's inspection of all
// implicit conversions - it checks for truncation, with suppressions in place
// for warnings which guard against narrowing implicit conversions.
template <typename Src>
constexpr auto to_narrow(Src const& src) -> to_narrow_convertible<Src> {
return to_narrow_convertible<Src>{src};
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment