blob: b548467e7b86ba8b032c331b39abffcb74b21644 [file] [log] [blame]
tapted174fde32016-01-14 06:26:371// 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.
4
5#ifndef BASE_BIT_CAST_H_
6#define BASE_BIT_CAST_H_
7
8#include <string.h>
9
10// bit_cast<Dest,Source> is a template function that implements the equivalent
11// of "*reinterpret_cast<Dest*>(&source)". We need this in very low-level
12// functions like the protobuf library and fast math support.
13//
14// float f = 3.14159265358979;
15// int i = bit_cast<int32_t>(f);
16// // i = 0x40490fdb
17//
18// The classical address-casting method is:
19//
20// // WRONG
21// float f = 3.14159265358979; // WRONG
22// int i = * reinterpret_cast<int*>(&f); // WRONG
23//
24// The address-casting method actually produces undefined behavior according to
25// the ISO C++98 specification, section 3.10 ("basic.lval"), paragraph 15.
26// (This did not substantially change in C++11.) Roughly, this section says: if
27// an object in memory has one type, and a program accesses it with a different
28// type, then the result is undefined behavior for most values of "different
29// type".
30//
31// This is true for any cast syntax, either *(int*)&f or
32// *reinterpret_cast<int*>(&f). And it is particularly true for conversions
33// between integral lvalues and floating-point lvalues.
34//
35// The purpose of this paragraph is to allow optimizing compilers to assume that
36// expressions with different types refer to different memory. Compilers are
37// known to take advantage of this. So a non-conforming program quietly
38// produces wildly incorrect output.
39//
40// The problem is not the use of reinterpret_cast. The problem is type punning:
41// holding an object in memory of one type and reading its bits back using a
42// different type.
43//
44// The C++ standard is more subtle and complex than this, but that is the basic
45// idea.
46//
47// Anyways ...
48//
49// bit_cast<> calls memcpy() which is blessed by the standard, especially by the
50// example in section 3.9 . Also, of course, bit_cast<> wraps up the nasty
51// logic in one place.
52//
53// Fortunately memcpy() is very fast. In optimized mode, compilers replace
54// calls to memcpy() with inline object code when the size argument is a
55// compile-time constant. On a 32-bit system, memcpy(d,s,4) compiles to one
56// load and one store, and memcpy(d,s,8) compiles to two loads and two stores.
57//
58// WARNING: if Dest or Source is a non-POD type, the result of the memcpy
59// is likely to surprise you.
60
61template <class Dest, class Source>
62inline Dest bit_cast(const Source& source) {
63 static_assert(sizeof(Dest) == sizeof(Source),
64 "bit_cast requires source and destination to be the same size");
65
66 Dest dest;
67 memcpy(&dest, &source, sizeof(dest));
68 return dest;
69}
70
71#endif // BASE_BIT_CAST_H_