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#include <stdexcept>
17
18#include "test_macros.h"
19
20template <std::size_t N>
21TEST_CONSTEXPR_CXX23 void test_to_ullong() {
22 const std::size_t M = sizeof(unsigned long long) * CHAR_BIT < N ? sizeof(unsigned long long) * CHAR_BIT : N;
23 const bool is_M_zero = std::integral_constant < bool, M == 0 > ::value; // avoid compiler warnings
24 const std::size_t X =
25 is_M_zero ? sizeof(unsigned long long) * CHAR_BIT - 1 : sizeof(unsigned long long) * CHAR_BIT - M;
26 const unsigned long long max = is_M_zero ? 0 : (unsigned long long)(-1) >> X;
27 unsigned long long tests[] = {
28 0,
29 std::min<unsigned long long>(1, max),
30 std::min<unsigned long long>(2, max),
31 std::min<unsigned long long>(3, max),
32 std::min(max, max - 3),
33 std::min(max, max - 2),
34 std::min(max, max - 1),
35 max};
36 for (unsigned long long j : tests) {
37 std::bitset<N> v(j);
38 assert(j == v.to_ullong());
39 }
40 { // test values bigger than can fit into the bitset
41 const unsigned long long val = 0x55AAAAFFFFAAAA55ULL;
42 const bool canFit = N < sizeof(unsigned long long) * CHAR_BIT;
43 const unsigned long long mask =
44 canFit ? (1ULL << (canFit ? N : 0)) - 1 : (unsigned long long)(-1); // avoid compiler warnings
45 std::bitset<N> v(val);
46 assert(v.to_ullong() == (val & mask)); // we shouldn't return bit patterns from outside the limits of the bitset.
47 }
48}
49
50TEST_CONSTEXPR_CXX23 bool test() {
51 test_to_ullong<0>();
52 test_to_ullong<1>();
53 test_to_ullong<31>();
54 test_to_ullong<32>();
55 test_to_ullong<33>();
56 test_to_ullong<63>();
57 test_to_ullong<64>();
58 test_to_ullong<65>();
59 test_to_ullong<1000>();
60
61#ifndef TEST_HAS_NO_EXCEPTIONS
62 if (!TEST_IS_CONSTANT_EVALUATED) {
63 // bitset has true bits beyond the size of unsigned long long
64 std::bitset<std::numeric_limits<unsigned long long>::digits + 1> q(0);
65 q.flip();
66 try {
67 q.to_ullong(); // throws
68 assert(false);
69 } catch (const std::overflow_error&) {
70 // expected
71 } catch (...) {
72 assert(false);
73 }
74 }
75#endif // TEST_HAS_NO_EXCEPTIONS
76
77 return true;
78}
79
80int main(int, char**) {
81 test();
82#if TEST_STD_VER > 20
83 static_assert(test());
84#endif
85
86 return 0;
87}
88

source code of libcxx/test/std/utilities/template.bitset/bitset.members/to_ullong.pass.cpp