tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
bit_cast.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2020 Tobias Hienzsch
3
4#ifndef TETL_BIT_BIT_CAST_HPP
5#define TETL_BIT_BIT_CAST_HPP
6
7#include <etl/_config/all.hpp>
8
9#include <etl/_cstddef/size_t.hpp>
10#include <etl/_strings/cstr.hpp>
11#include <etl/_type_traits/is_trivially_constructible.hpp>
12#include <etl/_type_traits/is_trivially_copyable.hpp>
13
14namespace etl {
15
16namespace detail {
17
18template <typename To, typename From>
19concept bitcastable = (sizeof(To) == sizeof(From)) and is_trivially_copyable_v<From> and is_trivially_copyable_v<To>;
20
21} // namespace detail
22
23/// Obtain a value of type To by reinterpreting the object representation
24/// of from. Every bit in the value representation of the returned To object is
25/// equal to the corresponding bit in the object representation of from.
26///
27/// The values of padding bits in the returned To object are
28/// unspecified. If there is no value of type To corresponding to the value
29/// representation produced, the behavior is undefined. If there are multiple
30/// such values, which value is produced is unspecified. This overload only
31/// participates in overload resolution if sizeof(To) == sizeof(From) and both
32/// To and From are TriviallyCopyable types.
33///
34/// https://en.cppreference.com/w/cpp/numeric/bit_cast
35///
36/// \ingroup bit
37template <typename To, typename From>
38 requires detail::bitcastable<To, From>
39constexpr auto bit_cast(From const& src) noexcept -> To
40{
41#if __has_builtin(__builtin_bit_cast) or (defined(_MSC_VER) and not defined(__clang__))
42 return __builtin_bit_cast(To, src);
43#else
44 To dst{};
45 etl::detail::memcpy<char, etl::size_t>(&dst, &src, sizeof(To));
46 return dst;
47#endif
48}
49
50} // namespace etl
51
52#endif // TETL_BIT_BIT_CAST_HPP
constexpr auto bit_cast(From const &src) noexcept -> To
Obtain a value of type To by reinterpreting the object representation of from. Every bit in the value...
Definition bit_cast.hpp:39
Definition adjacent_find.hpp:9