bit_cast.h 1.3 KB

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