From 7bbef1fafc2ce4d10633ba72bde7c714bee9aef6 Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Wed, 6 Jun 2018 16:03:47 -0700 Subject: [PATCH] Bug 1465981 - Use memcpy instead of union-arm-punning (which has implementation-defined, desired behavior with gcc and presumably clang, and is not known to have problems on MSVC, but potentially could with other compilers) in BitwiseCast. r=froydnj --HG-- extra : rebase_source : 686363576c84710ae0181afc32b05dee8b40a59b --- mfbt/Casting.h | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/mfbt/Casting.h b/mfbt/Casting.h index adf2c90456b4..6648b1488db2 100644 --- a/mfbt/Casting.h +++ b/mfbt/Casting.h @@ -12,7 +12,9 @@ #include "mozilla/Assertions.h" #include "mozilla/TypeTraits.h" +#include #include +#include namespace mozilla { @@ -43,13 +45,19 @@ BitwiseCast(const From aFrom, To* aResult) { static_assert(sizeof(From) == sizeof(To), "To and From must have the same size"); - union - { - From mFrom; - To mTo; - } u; - u.mFrom = aFrom; - *aResult = u.mTo; + + // We could maybe downgrade these to std::is_trivially_copyable, but the + // various STLs we use don't all provide it. + static_assert(std::is_trivial::value, + "shouldn't bitwise-copy a type having non-trivial " + "initialization"); + static_assert(std::is_trivial::value, + "shouldn't bitwise-copy a type having non-trivial " + "initialization"); + + std::memcpy(static_cast(aResult), + static_cast(&aFrom), + sizeof(From)); } template