1 // Copyright 2016 The Chromium Authors 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 <type_traits> 9 10 #include "base/compiler_specific.h" 11 12 #if !HAS_BUILTIN(__builtin_bit_cast) 13 #include <string.h> // memcpy 14 #endif 15 16 namespace base { 17 18 // This is C++20's std::bit_cast<>(). It morally does what 19 // `*reinterpret_cast<Dest*>(&source)` does, but the cast/deref pair is 20 // undefined behavior, while bit_cast<>() isn't. 21 template <class Dest, class Source> 22 #if HAS_BUILTIN(__builtin_bit_cast) 23 constexpr 24 #else 25 inline 26 #endif 27 Dest bit_cast(const Source & source)28 bit_cast(const Source& source) { 29 #if HAS_BUILTIN(__builtin_bit_cast) 30 // TODO(thakis): Keep only this codepath once nacl is gone or updated. 31 return __builtin_bit_cast(Dest, source); 32 #else 33 static_assert(sizeof(Dest) == sizeof(Source), 34 "bit_cast requires source and destination to be the same size"); 35 static_assert(std::is_trivially_copyable_v<Dest>, 36 "bit_cast requires the destination type to be copyable"); 37 static_assert(std::is_trivially_copyable_v<Source>, 38 "bit_cast requires the source type to be copyable"); 39 40 Dest dest; 41 memcpy(&dest, &source, sizeof(dest)); 42 return dest; 43 #endif 44 } 45 46 } // namespace base 47 48 #endif // BASE_BIT_CAST_H_ 49