Line data Source code
1 : // Copyright (c) 2018-2025 Made to Order Software Corp. All Rights Reserved
2 : //
3 : // https://snapwebsites.org/project/snapdev
4 : // contact@m2osw.com
5 : //
6 : // This program is free software: you can redistribute it and/or modify
7 : // it under the terms of the GNU General Public License as published by
8 : // the Free Software Foundation, either version 3 of the License, or
9 : // (at your option) any later version.
10 : //
11 : // This program is distributed in the hope that it will be useful,
12 : // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 : // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 : // GNU General Public License for more details.
15 : //
16 : // You should have received a copy of the GNU General Public License
17 : // along with this program. If not, see <https://www.gnu.org/licenses/>.
18 :
19 : /** \file
20 : * \brief Verify that the log2() function.
21 : *
22 : * This file implements test for the log2() function.
23 : */
24 :
25 : // self
26 : //
27 : #include "catch_main.h"
28 :
29 :
30 :
31 : // snapdev
32 : //
33 : #include <snapdev/log2.h>
34 :
35 :
36 : // last include
37 : //
38 : #include <snapdev/poison.h>
39 :
40 :
41 :
42 :
43 :
44 :
45 3 : CATCH_TEST_CASE("log2", "[math]")
46 : {
47 3 : CATCH_START_SECTION("log2: zero")
48 : {
49 1 : CATCH_REQUIRE(snapdev::log2(0) == -1);
50 : }
51 3 : CATCH_END_SECTION()
52 :
53 3 : CATCH_START_SECTION("log2: powers of 2")
54 : {
55 65 : for(int i = 0; i < 64; ++i)
56 : {
57 64 : std::uint64_t const v = 1ULL << i;
58 64 : CATCH_REQUIRE(snapdev::log2(v) == i);
59 : }
60 : }
61 3 : CATCH_END_SECTION()
62 :
63 3 : CATCH_START_SECTION("log2: random numbers")
64 : {
65 65 : for(int i = 0; i < 64; ++i)
66 : {
67 64 : std::uint64_t r = (static_cast<std::uint64_t>(rand()) << 32) ^ static_cast<std::uint64_t>(rand());
68 64 : r &= (1ULL << i) - 1ULL;
69 64 : std::uint64_t const v = (1ULL << i) | r;
70 :
71 : // same difference, all the lower bits are ignored in the
72 : // computation
73 : //
74 64 : CATCH_REQUIRE(snapdev::log2(v) == i);
75 : }
76 : }
77 3 : CATCH_END_SECTION()
78 3 : }
79 :
80 :
81 :
82 : // vim: ts=4 sw=4 et
|