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.
5 #ifndef BASE_BIT_CAST_H_
6 #define BASE_BIT_CAST_H_
10 #include "base/compiler_specific.h"
12 #if !HAS_BUILTIN(__builtin_bit_cast)
13 #include <string.h> // memcpy
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)
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);
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");
41 memcpy(&dest, &source, sizeof(dest));
48 #endif // BASE_BIT_CAST_H_