smallobj_ut.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "smallobj.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/generic/hash_set.h>
  4. class TSmallObjAllocTest: public TTestBase {
  5. struct TClass: public TObjectFromPool<TClass> {
  6. char buf[125];
  7. };
  8. struct TErrClass: public TObjectFromPool<TErrClass> {
  9. inline TErrClass(bool t) {
  10. if (t) {
  11. throw 1;
  12. }
  13. }
  14. };
  15. struct TClass64: public TObjectFromPool<TClass64> {
  16. alignas(64) ui64 Data = 0;
  17. };
  18. UNIT_TEST_SUITE(TSmallObjAllocTest);
  19. UNIT_TEST(TestAlign)
  20. UNIT_TEST(TestError)
  21. UNIT_TEST(TestAllocate)
  22. UNIT_TEST_SUITE_END();
  23. private:
  24. void TestAlign() {
  25. TClass64::TPool pool(TDefaultAllocator::Instance());
  26. TClass64* f1 = new (&pool) TClass64;
  27. TClass64* f2 = new (&pool) TClass64;
  28. TClass64* f3 = new (&pool) TClass64;
  29. TClass64* f4 = new (&pool) TClass64;
  30. UNIT_ASSERT_VALUES_EQUAL(64u, alignof(TClass64));
  31. UNIT_ASSERT_VALUES_EQUAL((size_t)0, (size_t)(f1) & (alignof(TClass64) - 1));
  32. UNIT_ASSERT_VALUES_EQUAL((size_t)0, (size_t)(f2) & (alignof(TClass64) - 1));
  33. UNIT_ASSERT_VALUES_EQUAL((size_t)0, (size_t)(f3) & (alignof(TClass64) - 1));
  34. UNIT_ASSERT_VALUES_EQUAL((size_t)0, (size_t)(f4) & (alignof(TClass64) - 1));
  35. }
  36. inline void TestError() {
  37. TErrClass::TPool pool(TDefaultAllocator::Instance());
  38. TErrClass* f = new (&pool) TErrClass(false);
  39. delete f;
  40. bool wasError = false;
  41. try {
  42. new (&pool) TErrClass(true);
  43. } catch (...) {
  44. wasError = true;
  45. }
  46. UNIT_ASSERT(wasError);
  47. UNIT_ASSERT_EQUAL(f, new (&pool) TErrClass(false));
  48. }
  49. inline void TestAllocate() {
  50. TClass::TPool pool(TDefaultAllocator::Instance());
  51. THashSet<TClass*> alloced;
  52. for (size_t i = 0; i < 10000; ++i) {
  53. TClass* c = new (&pool) TClass;
  54. UNIT_ASSERT_EQUAL(alloced.find(c), alloced.end());
  55. alloced.insert(c);
  56. }
  57. for (auto it : alloced) {
  58. delete it;
  59. }
  60. for (size_t i = 0; i < 10000; ++i) {
  61. TClass* c = new (&pool) TClass;
  62. UNIT_ASSERT(alloced.find(c) != alloced.end());
  63. }
  64. UNIT_ASSERT_EQUAL(alloced.find(new (&pool) TClass), alloced.end());
  65. }
  66. };
  67. UNIT_TEST_SUITE_REGISTRATION(TSmallObjAllocTest);