bitvector_ut.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include "bitvector.h"
  2. #include "readonly_bitvector.h"
  3. #include <library/cpp/testing/unittest/registar.h>
  4. #include <util/memory/blob.h>
  5. #include <util/stream/buffer.h>
  6. Y_UNIT_TEST_SUITE(TBitVectorTest) {
  7. Y_UNIT_TEST(TestEmpty) {
  8. TBitVector<ui64> v64;
  9. UNIT_ASSERT_EQUAL(v64.Size(), 0);
  10. UNIT_ASSERT_EQUAL(v64.Words(), 0);
  11. TBitVector<ui32> v32(0);
  12. UNIT_ASSERT_EQUAL(v32.Size(), 0);
  13. UNIT_ASSERT_EQUAL(v32.Words(), 0);
  14. }
  15. Y_UNIT_TEST(TestOneWord) {
  16. TBitVector<ui32> v;
  17. v.Append(1, 1);
  18. v.Append(0, 1);
  19. v.Append(1, 3);
  20. v.Append(10, 4);
  21. v.Append(100500, 20);
  22. UNIT_ASSERT_EQUAL(v.Get(0, 1), 1);
  23. UNIT_ASSERT(v.Test(0));
  24. UNIT_ASSERT_EQUAL(v.Get(1, 1), 0);
  25. UNIT_ASSERT_EQUAL(v.Get(2, 3), 1);
  26. UNIT_ASSERT_EQUAL(v.Get(5, 4), 10);
  27. UNIT_ASSERT_EQUAL(v.Get(9, 20), 100500);
  28. v.Reset(0);
  29. v.Set(9, 1234, 15);
  30. UNIT_ASSERT_EQUAL(v.Get(0, 1), 0);
  31. UNIT_ASSERT(!v.Test(0));
  32. UNIT_ASSERT_EQUAL(v.Get(9, 15), 1234);
  33. UNIT_ASSERT_EQUAL(v.Size(), 29);
  34. UNIT_ASSERT_EQUAL(v.Words(), 1);
  35. }
  36. Y_UNIT_TEST(TestManyWords) {
  37. static const int BITS = 10;
  38. TBitVector<ui64> v;
  39. for (int i = 0, end = (1 << BITS); i < end; ++i)
  40. v.Append(i, BITS);
  41. UNIT_ASSERT_EQUAL(v.Size(), BITS * (1 << BITS));
  42. UNIT_ASSERT_EQUAL(v.Words(), (v.Size() + 63) / 64);
  43. for (int i = 0, end = (1 << BITS); i < end; ++i)
  44. UNIT_ASSERT_EQUAL(v.Get(i * BITS, BITS), (ui64)i);
  45. }
  46. Y_UNIT_TEST(TestMaxWordSize) {
  47. TBitVector<ui32> v;
  48. for (int i = 0; i < 100; ++i)
  49. v.Append(i, 32);
  50. for (int i = 0; i < 100; ++i)
  51. UNIT_ASSERT_EQUAL(v.Get(i * 32, 32), (ui32)i);
  52. v.Set(10 * 32, 100500, 32);
  53. UNIT_ASSERT_EQUAL(v.Get(10 * 32, 32), 100500);
  54. }
  55. Y_UNIT_TEST(TestReadonlyVector) {
  56. TBitVector<ui64> v(100);
  57. for (ui64 i = 0; i < v.Size(); ++i) {
  58. if (i % 3 == 0) {
  59. v.Set(i);
  60. }
  61. }
  62. TBufferStream bs;
  63. TReadonlyBitVector<ui64>::SaveForReadonlyAccess(&bs, v);
  64. const auto blob = TBlob::FromBuffer(bs.Buffer());
  65. TReadonlyBitVector<ui64> rv;
  66. rv.LoadFromBlob(blob);
  67. for (ui64 i = 0; i < rv.Size(); ++i) {
  68. UNIT_ASSERT_VALUES_EQUAL(rv.Test(i), i % 3 == 0);
  69. }
  70. }
  71. }