xref: /llvm-project/libcxx/test/std/utilities/template.bitset/bitset.members/to_ulong.pass.cpp (revision 0c90d5f7e967aee8ab6e5e971e25921e631a40ac)
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 to_ulong() const; // constexpr since C++23
10 
11 #include <bitset>
12 #include <algorithm>
13 #include <type_traits>
14 #include <limits>
15 #include <climits>
16 #include <cassert>
17 
18 #include "test_macros.h"
19 
20 template <std::size_t N>
test_to_ulong()21 TEST_CONSTEXPR_CXX23 void test_to_ulong() {
22     const std::size_t M = sizeof(unsigned long) * CHAR_BIT < N ? sizeof(unsigned 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 = is_M_zero ? sizeof(unsigned long) * CHAR_BIT - 1 : sizeof(unsigned long) * CHAR_BIT - M;
25     const std::size_t max = is_M_zero ? 0 : std::size_t(std::numeric_limits<unsigned long>::max()) >> X;
26     std::size_t tests[] = {
27         0,
28         std::min<std::size_t>(1, max),
29         std::min<std::size_t>(2, max),
30         std::min<std::size_t>(3, max),
31         std::min(max, max-3),
32         std::min(max, max-2),
33         std::min(max, max-1),
34         max
35     };
36     for (std::size_t j : tests) {
37         std::bitset<N> v(j);
38         assert(j == v.to_ulong());
39     }
40 
41     { // test values bigger than can fit into the bitset
42         const unsigned long val = 0x5AFFFFA5UL;
43         const bool canFit = N < sizeof(unsigned long) * CHAR_BIT;
44         const unsigned long mask = canFit ? (1UL << (canFit ? N : 0)) - 1 : (unsigned long)(-1); // avoid compiler warnings
45         std::bitset<N> v(val);
46         assert(v.to_ulong() == (val & mask)); // we shouldn't return bit patterns from outside the limits of the bitset.
47     }
48 }
49 
test()50 TEST_CONSTEXPR_CXX23 bool test() {
51   test_to_ulong<0>();
52   test_to_ulong<1>();
53   test_to_ulong<31>();
54   test_to_ulong<32>();
55   test_to_ulong<33>();
56   test_to_ulong<63>();
57   test_to_ulong<64>();
58   test_to_ulong<65>();
59   test_to_ulong<1000>();
60 
61   return true;
62 }
63 
main(int,char **)64 int main(int, char**) {
65   test();
66 #if TEST_STD_VER > 20
67   static_assert(test());
68 #endif
69 
70   return 0;
71 }
72