BitIteratorTest.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #include <folly/container/BitIterator.h>
  17. #include <limits>
  18. #include <type_traits>
  19. #include <vector>
  20. #include <folly/portability/GTest.h>
  21. using namespace folly;
  22. using namespace folly::bititerator_detail;
  23. namespace {
  24. template <class INT, class IT>
  25. void checkIt(INT exp, IT& it) {
  26. typedef typename std::make_unsigned<INT>::type utype;
  27. size_t bits = std::numeric_limits<utype>::digits;
  28. utype uexp = exp;
  29. for (size_t i = 0; i < bits; ++i) {
  30. bool e = uexp & 1;
  31. EXPECT_EQ(e, *it++);
  32. uexp >>= 1;
  33. }
  34. }
  35. template <class INT, class IT>
  36. void checkRange(INT exp, IT begin, IT end) {
  37. typedef typename std::make_unsigned<INT>::type utype;
  38. utype uexp = exp;
  39. size_t i = 0;
  40. auto bitEnd = makeBitIterator(end);
  41. for (BitIterator<IT> it = makeBitIterator(begin); it != bitEnd; ++it, ++i) {
  42. bool e = uexp & 1;
  43. EXPECT_EQ(e, *it);
  44. uexp >>= 1;
  45. }
  46. }
  47. } // namespace
  48. TEST(BitIterator, Simple) {
  49. std::vector<int> v;
  50. v.push_back(0x10);
  51. v.push_back(0x42);
  52. auto bi(makeBitIterator(v.begin()));
  53. checkIt(0x10, bi);
  54. checkIt(0x42, bi);
  55. checkRange(0x0000004200000010ULL, v.begin(), v.end());
  56. v[0] = 0;
  57. bi = v.begin();
  58. *bi++ = true; // 1
  59. *bi++ = false;
  60. *bi++ = true; // 4
  61. *bi++ = false;
  62. *bi++ = false;
  63. *bi++ = true; // 32
  64. *++bi = true; // 128 (note pre-increment)
  65. EXPECT_EQ(165, v[0]);
  66. }
  67. TEST(BitIterator, Const) {
  68. std::vector<int> v;
  69. v.push_back(0x10);
  70. v.push_back(0x42);
  71. auto bi(makeBitIterator(v.cbegin()));
  72. checkIt(0x10, bi);
  73. checkIt(0x42, bi);
  74. }