1 | /* |
2 | * Copyright 2011-present Facebook, Inc. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | |
17 | #include <folly/container/BitIterator.h> |
18 | |
19 | #include <limits> |
20 | #include <type_traits> |
21 | #include <vector> |
22 | |
23 | #include <folly/portability/GTest.h> |
24 | |
25 | using namespace folly; |
26 | using namespace folly::bititerator_detail; |
27 | |
28 | namespace { |
29 | |
30 | template <class INT, class IT> |
31 | void checkIt(INT exp, IT& it) { |
32 | typedef typename std::make_unsigned<INT>::type utype; |
33 | size_t bits = std::numeric_limits<utype>::digits; |
34 | utype uexp = exp; |
35 | for (size_t i = 0; i < bits; ++i) { |
36 | bool e = uexp & 1; |
37 | EXPECT_EQ(e, *it++); |
38 | uexp >>= 1; |
39 | } |
40 | } |
41 | |
42 | template <class INT, class IT> |
43 | void checkRange(INT exp, IT begin, IT end) { |
44 | typedef typename std::make_unsigned<INT>::type utype; |
45 | utype uexp = exp; |
46 | size_t i = 0; |
47 | auto bitEnd = makeBitIterator(end); |
48 | for (BitIterator<IT> it = makeBitIterator(begin); it != bitEnd; ++it, ++i) { |
49 | bool e = uexp & 1; |
50 | EXPECT_EQ(e, *it); |
51 | uexp >>= 1; |
52 | } |
53 | } |
54 | |
55 | } // namespace |
56 | |
57 | TEST(BitIterator, Simple) { |
58 | std::vector<int> v; |
59 | v.push_back(0x10); |
60 | v.push_back(0x42); |
61 | auto bi(makeBitIterator(v.begin())); |
62 | checkIt(0x10, bi); |
63 | checkIt(0x42, bi); |
64 | checkRange(0x0000004200000010ULL, v.begin(), v.end()); |
65 | |
66 | v[0] = 0; |
67 | bi = v.begin(); |
68 | *bi++ = true; // 1 |
69 | *bi++ = false; |
70 | *bi++ = true; // 4 |
71 | *bi++ = false; |
72 | *bi++ = false; |
73 | *bi++ = true; // 32 |
74 | *++bi = true; // 128 (note pre-increment) |
75 | |
76 | EXPECT_EQ(165, v[0]); |
77 | } |
78 | |
79 | TEST(BitIterator, Const) { |
80 | std::vector<int> v; |
81 | v.push_back(0x10); |
82 | v.push_back(0x42); |
83 | auto bi(makeBitIterator(v.cbegin())); |
84 | checkIt(0x10, bi); |
85 | checkIt(0x42, bi); |
86 | } |
87 | |