stack.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #ifndef __XRCU_TESTS_STACK__
  2. #define __XRCU_TESTS_STACK__ 1
  3. #include "../stack.hpp"
  4. #include "utils.hpp"
  5. #include <thread>
  6. namespace stk_test
  7. {
  8. typedef xrcu::stack<std::string> stack_t;
  9. void test_single_threaded ()
  10. {
  11. {
  12. stack_t stk;
  13. ASSERT (stk.empty ());
  14. ASSERT (!stk.top().has_value ());
  15. }
  16. {
  17. stack_t stk { 3, std::string ("???") };
  18. ASSERT (stk.size () == 3);
  19. for (const auto& s : stk)
  20. ASSERT (s == "???");
  21. }
  22. {
  23. stack_t stk { std::string ("abc"), std::string ("def"),
  24. std::string ("ghi"), std::string ("jkl") };
  25. ASSERT (stk.size () == 4);
  26. }
  27. {
  28. std::string vals[] = { "abc", "def", "ghi" };
  29. stack_t stk { vals, vals + 3 };
  30. size_t i = 0;
  31. for (const auto& s : stk)
  32. ASSERT (s == vals[i++]);
  33. stack_t s2 { stk };
  34. ASSERT (s2 == stk);
  35. stack_t s3 { std::move (s2) };
  36. ASSERT (stk == s3);
  37. }
  38. stack_t stk;
  39. const int NELEM = 100;
  40. for (int i = 0; i < NELEM; ++i)
  41. stk.push (mkstr (i));
  42. ASSERT (*stk.top() == mkstr (NELEM - 1));
  43. stack_t s2;
  44. stk.swap (s2);
  45. ASSERT (stk.empty ());
  46. stk = s2;
  47. ASSERT (!stk.empty ());
  48. ASSERT (stk == s2);
  49. stk.clear ();
  50. ASSERT (stk.empty ());
  51. stk.assign (s2.begin (), s2.end ());
  52. ASSERT (stk == s2);
  53. stk.clear ();
  54. s2.clear ();
  55. stk.push (mkstr (10));
  56. s2.push (mkstr (20));
  57. ASSERT (stk < s2);
  58. stk.pop ();
  59. stk.push (mkstr (30));
  60. ASSERT (stk > s2);
  61. s2.pop ();
  62. s2.push (mkstr (30));
  63. s2.push (mkstr (40));
  64. ASSERT (stk <= s2);
  65. stk.push (mkstr (50));
  66. ASSERT (stk >= s2);
  67. ASSERT (!xrcu::in_cs ());
  68. }
  69. static void
  70. mt_inserter (stack_t *stkp, int index)
  71. {
  72. for (int i = 0; i < INSERTER_LOOPS; ++i)
  73. stkp->push (mkstr (index * INSERTER_LOOPS + i));
  74. }
  75. void test_push_mt ()
  76. {
  77. stack_t stk;
  78. std::vector<std::thread> thrs;
  79. for (int i = 0; i < INSERTER_THREADS; ++i)
  80. thrs.push_back (std::thread (mt_inserter, &stk, i));
  81. for (auto& thr : thrs)
  82. thr.join ();
  83. ASSERT (stk.size () == INSERTER_THREADS * INSERTER_LOOPS);
  84. }
  85. test_module stack_tests
  86. {
  87. "stack",
  88. {
  89. { "API in a single thread", test_single_threaded },
  90. { "multi threaded pushes", test_push_mt }
  91. }
  92. };
  93. } // namespace stk_test
  94. #endif