1 //--------------------------------------------------------------------------
2 // Copyright (C) 2016-2021 Cisco and/or its affiliates. All rights reserved.
3 //
4 // This program is free software; you can redistribute it and/or modify it
5 // under the terms of the GNU General Public License Version 2 as published
6 // by the Free Software Foundation.  You may not use, modify or distribute
7 // this program under any other version of the GNU General Public License.
8 //
9 // This program is distributed in the hope that it will be useful, but
10 // WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 // General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License along
15 // with this program; if not, write to the Free Software Foundation, Inc.,
16 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17 //--------------------------------------------------------------------------
18 // bitop_test.cc author Joel Cornett <joel.cornett@gmail.com>
19 
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23 
24 #include "catch/catch.hpp"
25 
26 #include "../bitop.h"
27 
num_set(const BitOp & bitop,size_t max)28 static unsigned num_set(const BitOp& bitop, size_t max)
29 {
30     unsigned c = 0;
31 
32     for ( size_t i = 0; i < max; ++i )
33     {
34         if ( bitop.is_set(i) )
35             c++;
36     }
37     return c;
38 }
39 
is_clear(const BitOp & bitop,size_t max)40 static bool is_clear(const BitOp& bitop, size_t max)
41 { return num_set(bitop, max) == 0; }
42 
43 TEST_CASE( "bitop", "[bitop]" )
44 {
45     const size_t max = 16;
46     BitOp bitop(max);
47 
48     SECTION( "zero-initialized" )
49     {
50         CHECK( (is_clear(bitop, max) == true) );
51     }
52 
53     SECTION( "toggle" )
54     {
55         const size_t bit = 7;
56 
57         bitop.set(bit);
58         CHECK(bitop.is_set(bit));
59 
60         CHECK(num_set(bitop, max) == 1);
61 
62         bitop.clear(bit);
63         CHECK(!bitop.is_set(bit));
64 
65         CHECK( (is_clear(bitop, max) == true) );
66     }
67 
68     SECTION( "over size" )
69     {
70         const size_t j = max / 2;
71         const size_t k = max + 2;
72 
73         bitop.set(j);
74         CHECK(bitop.is_set(j));
75 
76         CHECK(!bitop.is_set(k));
77 
78         bitop.set(k);
79         CHECK(bitop.is_set(k));
80 
81         CHECK(num_set(bitop, k + 2) == 2);
82         CHECK(bitop.is_set(j));
83 
84         bitop.clear(k);
85         CHECK(!bitop.is_set(k));
86 
87         CHECK(bitop.is_set(j));
88         bitop.clear(j);
89 
90         CHECK( (is_clear(bitop, k + 2) == true) );
91     }
92 }
93 
94