1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_BIT_CAST_H_
6 #define BASE_BIT_CAST_H_
10 #include "base/template_util.h"
12 // bit_cast<Dest,Source> is a template function that implements the equivalent
13 // of "*reinterpret_cast<Dest*>(&source)". We need this in very low-level
14 // functions like the protobuf library and fast math support.
16 // float f = 3.14159265358979;
17 // int i = bit_cast<int32_t>(f);
20 // The classical address-casting method is:
23 // float f = 3.14159265358979; // WRONG
24 // int i = * reinterpret_cast<int*>(&f); // WRONG
26 // The address-casting method actually produces undefined behavior according to
27 // the ISO C++98 specification, section 3.10 ("basic.lval"), paragraph 15.
28 // (This did not substantially change in C++11.) Roughly, this section says: if
29 // an object in memory has one type, and a program accesses it with a different
30 // type, then the result is undefined behavior for most values of "different
33 // This is true for any cast syntax, either *(int*)&f or
34 // *reinterpret_cast<int*>(&f). And it is particularly true for conversions
35 // between integral lvalues and floating-point lvalues.
37 // The purpose of this paragraph is to allow optimizing compilers to assume that
38 // expressions with different types refer to different memory. Compilers are
39 // known to take advantage of this. So a non-conforming program quietly
40 // produces wildly incorrect output.
42 // The problem is not the use of reinterpret_cast. The problem is type punning:
43 // holding an object in memory of one type and reading its bits back using a
46 // The C++ standard is more subtle and complex than this, but that is the basic
51 // bit_cast<> calls memcpy() which is blessed by the standard, especially by the
52 // example in section 3.9 . Also, of course, bit_cast<> wraps up the nasty
53 // logic in one place.
55 // Fortunately memcpy() is very fast. In optimized mode, compilers replace
56 // calls to memcpy() with inline object code when the size argument is a
57 // compile-time constant. On a 32-bit system, memcpy(d,s,4) compiles to one
58 // load and one store, and memcpy(d,s,8) compiles to two loads and two stores.
60 template <class Dest, class Source>
61 inline Dest bit_cast(const Source& source) {
62 static_assert(sizeof(Dest) == sizeof(Source),
63 "bit_cast requires source and destination to be the same size");
64 static_assert(base::is_trivially_copyable<Dest>::value,
65 "bit_cast requires the destination type to be copyable");
66 static_assert(base::is_trivially_copyable<Source>::value,
67 "bit_cast requires the source type to be copyable");
70 memcpy(&dest, &source, sizeof(dest));
74 #endif // BASE_BIT_CAST_H_