cb_random_test.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. * SPDX-License-Identifier: Apache-2.0
  3. *
  4. * Change Logs:
  5. * Date Author Notes
  6. * 2023-05-13 tyx first implementation
  7. */
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include <math.h>
  11. #include <time.h>
  12. #include <gtest/gtest.h>
  13. #include "cb_libc.h"
  14. TEST(testCase, cb_random_test01)
  15. {
  16. cb_srandom((unsigned int)(time(NULL) & 0xFFFFFFFF));
  17. EXPECT_NE(cb_random(), cb_random());
  18. }
  19. static int make_random(int* buf, int count)
  20. {
  21. while (count > 8)
  22. {
  23. *buf++ = cb_random();
  24. *buf++ = cb_random();
  25. *buf++ = cb_random();
  26. *buf++ = cb_random();
  27. *buf++ = cb_random();
  28. *buf++ = cb_random();
  29. *buf++ = cb_random();
  30. *buf++ = cb_random();
  31. count -= 8;
  32. }
  33. while (count > 4)
  34. {
  35. *buf++ = cb_random();
  36. *buf++ = cb_random();
  37. *buf++ = cb_random();
  38. *buf++ = cb_random();
  39. count -= 4;
  40. }
  41. while (count > 0)
  42. {
  43. *buf++ = cb_random();
  44. count -= 1;
  45. }
  46. return count;
  47. }
  48. static void inittab(unsigned char *t)
  49. {
  50. for (int i = 0; i < 256; i++)
  51. {
  52. *t = 0;
  53. for (int j = 0; j < 8; j++)
  54. {
  55. if (i & (0x1 << j))
  56. {
  57. *t += 1;
  58. }
  59. }
  60. t += 1;
  61. }
  62. }
  63. static int bit1cnt(unsigned char* buf, int size)
  64. {
  65. unsigned char tab[256];
  66. int cnt = 0;
  67. inittab(tab);
  68. while (size > 8)
  69. {
  70. cnt += tab[*buf++];
  71. cnt += tab[*buf++];
  72. cnt += tab[*buf++];
  73. cnt += tab[*buf++];
  74. cnt += tab[*buf++];
  75. cnt += tab[*buf++];
  76. cnt += tab[*buf++];
  77. cnt += tab[*buf++];
  78. size -= 8;
  79. }
  80. while (size > 4)
  81. {
  82. cnt += tab[*buf++];
  83. cnt += tab[*buf++];
  84. cnt += tab[*buf++];
  85. cnt += tab[*buf++];
  86. size -= 4;
  87. }
  88. while (size > 0)
  89. {
  90. cnt += tab[*buf++];
  91. size -= 1;
  92. }
  93. return cnt;
  94. }
  95. TEST(testCase, cb_random_test02)
  96. {
  97. int* testbuf;
  98. int test_cnt = 1024 *1024;
  99. int bitcnt;
  100. testbuf = new int[test_cnt];
  101. make_random(testbuf, test_cnt);
  102. bitcnt = bit1cnt((unsigned char *)testbuf, sizeof(int) * test_cnt);
  103. EXPECT_LT(fabs((double)bitcnt / (sizeof(int) * test_cnt * 8) - 0.5), 0.05);
  104. delete[] testbuf;
  105. }