| 1 | //===----------------------------------------------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | // unsigned long long to_ullong() const; // constexpr since C++23 |
| 10 | |
| 11 | #include <bitset> |
| 12 | #include <algorithm> |
| 13 | #include <type_traits> |
| 14 | #include <climits> |
| 15 | #include <cassert> |
| 16 | |
| 17 | #include "test_macros.h" |
| 18 | |
| 19 | template <std::size_t N> |
| 20 | TEST_CONSTEXPR_CXX23 void test_to_ullong() { |
| 21 | const std::size_t M = sizeof(unsigned long long) * CHAR_BIT < N ? sizeof(unsigned long long) * CHAR_BIT : N; |
| 22 | const bool is_M_zero = std::integral_constant<bool, M == 0>::value; // avoid compiler warnings |
| 23 | const std::size_t X = is_M_zero ? sizeof(unsigned long long) * CHAR_BIT - 1 : sizeof(unsigned long long) * CHAR_BIT - M; |
| 24 | const unsigned long long max = is_M_zero ? 0 : (unsigned long long)(-1) >> X; |
| 25 | unsigned long long tests[] = { |
| 26 | 0, |
| 27 | std::min<unsigned long long>(1, max), |
| 28 | std::min<unsigned long long>(2, max), |
| 29 | std::min<unsigned long long>(3, max), |
| 30 | std::min(max, max-3), |
| 31 | std::min(max, max-2), |
| 32 | std::min(max, max-1), |
| 33 | max |
| 34 | }; |
| 35 | for (unsigned long long j : tests) { |
| 36 | std::bitset<N> v(j); |
| 37 | assert(j == v.to_ullong()); |
| 38 | } |
| 39 | { // test values bigger than can fit into the bitset |
| 40 | const unsigned long long val = 0x55AAAAFFFFAAAA55ULL; |
| 41 | const bool canFit = N < sizeof(unsigned long long) * CHAR_BIT; |
| 42 | const unsigned long long mask = canFit ? (1ULL << (canFit ? N : 0)) - 1 : (unsigned long long)(-1); // avoid compiler warnings |
| 43 | std::bitset<N> v(val); |
| 44 | assert(v.to_ullong() == (val & mask)); // we shouldn't return bit patterns from outside the limits of the bitset. |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | TEST_CONSTEXPR_CXX23 bool test() { |
| 49 | test_to_ullong<0>(); |
| 50 | test_to_ullong<1>(); |
| 51 | test_to_ullong<31>(); |
| 52 | test_to_ullong<32>(); |
| 53 | test_to_ullong<33>(); |
| 54 | test_to_ullong<63>(); |
| 55 | test_to_ullong<64>(); |
| 56 | test_to_ullong<65>(); |
| 57 | test_to_ullong<1000>(); |
| 58 | |
| 59 | return true; |
| 60 | } |
| 61 | |
| 62 | int main(int, char**) { |
| 63 | test(); |
| 64 | #if TEST_STD_VER > 20 |
| 65 | static_assert(test()); |
| 66 | #endif |
| 67 | |
| 68 | return 0; |
| 69 | } |
| 70 | |