find_by_first_test.cc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include <string>
  5. #include "find_by_first.h"
  6. #include "test_platform.h"
  7. namespace crdtp {
  8. // =============================================================================
  9. // FindByFirst - Efficient retrieval from a sorted vector.
  10. // =============================================================================
  11. TEST(FindByFirst, SpanBySpan) {
  12. std::vector<std::pair<span<uint8_t>, span<uint8_t>>> sorted_span_by_span = {
  13. {SpanFrom("foo1"), SpanFrom("bar1")},
  14. {SpanFrom("foo2"), SpanFrom("bar2")},
  15. {SpanFrom("foo3"), SpanFrom("bar3")},
  16. };
  17. {
  18. auto result = FindByFirst(sorted_span_by_span, SpanFrom("foo1"),
  19. SpanFrom("not_found"));
  20. EXPECT_EQ("bar1", std::string(result.begin(), result.end()));
  21. }
  22. {
  23. auto result = FindByFirst(sorted_span_by_span, SpanFrom("foo3"),
  24. SpanFrom("not_found"));
  25. EXPECT_EQ("bar3", std::string(result.begin(), result.end()));
  26. }
  27. {
  28. auto result = FindByFirst(sorted_span_by_span, SpanFrom("baz"),
  29. SpanFrom("not_found"));
  30. EXPECT_EQ("not_found", std::string(result.begin(), result.end()));
  31. }
  32. }
  33. namespace {
  34. class TestObject {
  35. public:
  36. explicit TestObject(const std::string& message) : message_(message) {}
  37. const std::string& message() const { return message_; }
  38. private:
  39. std::string message_;
  40. };
  41. } // namespace
  42. TEST(FindByFirst, ObjectBySpan) {
  43. std::vector<std::pair<span<uint8_t>, std::unique_ptr<TestObject>>>
  44. sorted_object_by_span;
  45. sorted_object_by_span.push_back(
  46. std::make_pair(SpanFrom("foo1"), std::make_unique<TestObject>("bar1")));
  47. sorted_object_by_span.push_back(
  48. std::make_pair(SpanFrom("foo2"), std::make_unique<TestObject>("bar2")));
  49. sorted_object_by_span.push_back(
  50. std::make_pair(SpanFrom("foo3"), std::make_unique<TestObject>("bar3")));
  51. {
  52. TestObject* result =
  53. FindByFirst<TestObject>(sorted_object_by_span, SpanFrom("foo1"));
  54. ASSERT_TRUE(result);
  55. ASSERT_EQ("bar1", result->message());
  56. }
  57. {
  58. TestObject* result =
  59. FindByFirst<TestObject>(sorted_object_by_span, SpanFrom("foo3"));
  60. ASSERT_TRUE(result);
  61. ASSERT_EQ("bar3", result->message());
  62. }
  63. {
  64. TestObject* result =
  65. FindByFirst<TestObject>(sorted_object_by_span, SpanFrom("baz"));
  66. ASSERT_FALSE(result);
  67. }
  68. }
  69. } // namespace crdtp