| 1 |
// Copyright (C) 2020-2025 Free Software Foundation, Inc. |
| 2 |
// |
| 3 |
// This file is part of the GNU ISO C++ Library. This library is free |
| 4 |
// software; you can redistribute it and/or modify it under the |
| 5 |
// terms of the GNU General Public License as published by the |
| 6 |
// Free Software Foundation; either version 3, or (at your option) |
| 7 |
// any later version. |
| 8 |
|
| 9 |
// This library is distributed in the hope that it will be useful, |
| 10 |
// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
// GNU General Public License for more details. |
| 13 |
|
| 14 |
// You should have received a copy of the GNU General Public License along |
| 15 |
// with this library; see the file COPYING3. If not see |
| 16 |
// <http://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
// { dg-do compile { target c++20 } } |
| 19 |
// { dg-add-options no_pch } |
| 20 |
|
| 21 |
#include <bit> |
| 22 |
|
| 23 |
#ifndef __cpp_lib_bit_cast |
| 24 |
# error "Feature-test macro for bit_cast missing in <bit>" |
| 25 |
#elif __cpp_lib_bit_cast != 201806L |
| 26 |
# error "Feature-test macro for bit_cast has wrong value in <bit>" |
| 27 |
#endif |
| 28 |
|
| 29 |
#include <cstdint> |
| 30 |
#include <cstring> |
| 31 |
#include <testsuite_hooks.h> |
| 32 |
|
| 33 |
template<typename To, typename From> |
| 34 |
constexpr bool |
| 35 |
check(const From& from) |
| 36 |
{ |
| 37 |
return std::bit_cast<From>(std::bit_cast<To>(from)) == from; |
| 38 |
} |
| 39 |
|
| 40 |
void |
| 41 |
test01() |
| 42 |
{ |
| 43 |
static_assert( std::bit_cast<int>(123) == 123 ); |
| 44 |
static_assert( std::bit_cast<int>(123u) == 123 ); |
| 45 |
static_assert( std::bit_cast<int>(~0u) == ~0 ); |
| 46 |
|
| 47 |
if constexpr (sizeof(int) == sizeof(float)) |
| 48 |
static_assert( check<int>(12.34f) ); |
| 49 |
if constexpr (sizeof(unsigned long long) == sizeof(double)) |
| 50 |
static_assert( check<unsigned long long>(123.456) ); |
| 51 |
if constexpr (sizeof(std::intptr_t) == sizeof(void(*)())) |
| 52 |
VERIFY( check<std::intptr_t>(&test01) ); |
| 53 |
} |
| 54 |
|
| 55 |
void |
| 56 |
test02() |
| 57 |
{ |
| 58 |
struct S |
| 59 |
{ |
| 60 |
int i; |
| 61 |
|
| 62 |
bool operator==(const char* s) const |
| 63 |
{ return std::memcmp(&i, s, sizeof(i)) == 0; } |
| 64 |
}; |
| 65 |
|
| 66 |
char arr[sizeof(int)]; |
| 67 |
char arr2[sizeof(int)]; |
| 68 |
for (int i = 0; i < sizeof(int); ++i) |
| 69 |
{ |
| 70 |
arr[i] = i + 1; |
| 71 |
arr2[i] = (i + 1) * -(i % 2); |
| 72 |
} |
| 73 |
VERIFY( std::bit_cast<S>(arr) == arr ); |
| 74 |
VERIFY( std::bit_cast<S>(arr2) == arr2 ); |
| 75 |
} |
| 76 |
|
| 77 |
int main() |
| 78 |
{ |
| 79 |
test01(); |
| 80 |
test02(); |
| 81 |
} |