popcount_ut.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "popcount.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/random/random.h>
  4. Y_UNIT_TEST_SUITE(TestPopCount) {
  5. template <class T>
  6. static inline ui32 SlowPopCount(T t) {
  7. ui32 ret = 0;
  8. while (t) {
  9. if (t & T(1)) {
  10. ++ret;
  11. }
  12. t = t >> 1;
  13. }
  14. return ret;
  15. }
  16. template <class T>
  17. static inline void Test() {
  18. for (size_t i = 0; i < 10000; ++i) {
  19. const T rndv = RandomNumber<T>();
  20. UNIT_ASSERT_VALUES_EQUAL(SlowPopCount(rndv), PopCount(rndv));
  21. }
  22. }
  23. Y_UNIT_TEST(Test8) {
  24. Test<ui8>();
  25. }
  26. Y_UNIT_TEST(Test16) {
  27. Test<ui16>();
  28. }
  29. Y_UNIT_TEST(Test32) {
  30. Test<ui32>();
  31. }
  32. Y_UNIT_TEST(Test64) {
  33. Test<ui64>();
  34. }
  35. Y_UNIT_TEST(TestPopCount) {
  36. UNIT_ASSERT_VALUES_EQUAL(PopCount(0), 0);
  37. UNIT_ASSERT_VALUES_EQUAL(PopCount(1), 1);
  38. UNIT_ASSERT_VALUES_EQUAL(PopCount(1 << 10), 1);
  39. UNIT_ASSERT_VALUES_EQUAL(PopCount((1 << 10) + 1), 2);
  40. UNIT_ASSERT_VALUES_EQUAL(PopCount(0xFFFF), 16);
  41. UNIT_ASSERT_VALUES_EQUAL(PopCount(0xFFFFFFFF), 32);
  42. UNIT_ASSERT_VALUES_EQUAL(PopCount(0x55555555), 16);
  43. UNIT_ASSERT_VALUES_EQUAL(0, PopCount(0ULL));
  44. UNIT_ASSERT_VALUES_EQUAL(1, PopCount(1ULL));
  45. UNIT_ASSERT_VALUES_EQUAL(16, PopCount(0xAAAAAAAAULL));
  46. UNIT_ASSERT_VALUES_EQUAL(32, PopCount(0xFFFFFFFFULL));
  47. UNIT_ASSERT_VALUES_EQUAL(32, PopCount(0xAAAAAAAAAAAAAAAAULL));
  48. UNIT_ASSERT_VALUES_EQUAL(64, PopCount(0xFFFFFFFFFFFFFFFFULL));
  49. ui64 v = 0;
  50. for (int i = 0; i < 64; v |= 1ULL << i, ++i) {
  51. UNIT_ASSERT_VALUES_EQUAL(i, PopCount(v));
  52. }
  53. }
  54. }