kmp_ut.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "kmp.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/stream/output.h>
  4. static TVector<int> FindAll(const TString& pattern, const TString& string) {
  5. TVector<int> result;
  6. TKMPMatcher kmp(pattern);
  7. const char* pResult;
  8. const char* begin = string.begin();
  9. const char* end = string.end();
  10. while (kmp.SubStr(begin, end, pResult)) {
  11. result.push_back(int(pResult - string.data()));
  12. begin = pResult + pattern.size();
  13. }
  14. return result;
  15. }
  16. class TTestKMP: public TTestBase {
  17. UNIT_TEST_SUITE(TTestKMP);
  18. UNIT_TEST(Test);
  19. UNIT_TEST(TestStream);
  20. UNIT_TEST_SUITE_END();
  21. public:
  22. void Test() {
  23. TVector<int> ans = {0, 2};
  24. UNIT_ASSERT_EQUAL(FindAll("a", "aba"), ans);
  25. ans = {0};
  26. UNIT_ASSERT_EQUAL(FindAll("aba", "aba"), ans);
  27. ans.clear();
  28. UNIT_ASSERT_EQUAL(FindAll("abad", "aba"), ans);
  29. ans = {0, 2};
  30. UNIT_ASSERT_EQUAL(FindAll("ab", "abab"), ans);
  31. }
  32. class TKMPSimpleCallback: public TKMPStreamMatcher<int>::ICallback {
  33. private:
  34. int* Begin;
  35. int* End;
  36. int Count;
  37. public:
  38. TKMPSimpleCallback(int* begin, int* end)
  39. : Begin(begin)
  40. , End(end)
  41. , Count(0)
  42. {
  43. }
  44. void OnMatch(const int* begin, const int* end) override {
  45. UNIT_ASSERT_EQUAL(end - begin, End - Begin);
  46. const int* p0 = Begin;
  47. const int* p1 = begin;
  48. while (p0 < End) {
  49. UNIT_ASSERT_EQUAL(*p0, *p1);
  50. ++p0;
  51. ++p1;
  52. }
  53. ++Count;
  54. }
  55. int GetCount() const {
  56. return Count;
  57. }
  58. };
  59. void TestStream() {
  60. int pattern[] = {2, 3};
  61. int data[] = {1, 2, 3, 5, 2, 2, 3, 2, 4, 3, 2};
  62. TKMPSimpleCallback callback(pattern, pattern + 2);
  63. TKMPStreamMatcher<int> matcher(pattern, pattern + 2, &callback);
  64. for (auto& i : data)
  65. matcher.Push(i);
  66. UNIT_ASSERT_EQUAL(2, callback.GetCount());
  67. }
  68. };
  69. UNIT_TEST_SUITE_REGISTRATION(TTestKMP);