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
5 #include <string>
6
7 #include "find_by_first.h"
8 #include "test_platform.h"
9
10 namespace v8_crdtp {
11 // =============================================================================
12 // FindByFirst - Efficient retrieval from a sorted vector.
13 // =============================================================================
TEST(FindByFirst,SpanBySpan)14 TEST(FindByFirst, SpanBySpan) {
15 std::vector<std::pair<span<uint8_t>, span<uint8_t>>> sorted_span_by_span = {
16 {SpanFrom("foo1"), SpanFrom("bar1")},
17 {SpanFrom("foo2"), SpanFrom("bar2")},
18 {SpanFrom("foo3"), SpanFrom("bar3")},
19 };
20 {
21 auto result = FindByFirst(sorted_span_by_span, SpanFrom("foo1"),
22 SpanFrom("not_found"));
23 EXPECT_EQ("bar1", std::string(result.begin(), result.end()));
24 }
25 {
26 auto result = FindByFirst(sorted_span_by_span, SpanFrom("foo3"),
27 SpanFrom("not_found"));
28 EXPECT_EQ("bar3", std::string(result.begin(), result.end()));
29 }
30 {
31 auto result = FindByFirst(sorted_span_by_span, SpanFrom("baz"),
32 SpanFrom("not_found"));
33 EXPECT_EQ("not_found", std::string(result.begin(), result.end()));
34 }
35 }
36
37 namespace {
38 class TestObject {
39 public:
TestObject(const std::string & message)40 explicit TestObject(const std::string& message) : message_(message) {}
41
message() const42 const std::string& message() const { return message_; }
43
44 private:
45 std::string message_;
46 };
47 } // namespace
48
TEST(FindByFirst,ObjectBySpan)49 TEST(FindByFirst, ObjectBySpan) {
50 std::vector<std::pair<span<uint8_t>, std::unique_ptr<TestObject>>>
51 sorted_object_by_span;
52 sorted_object_by_span.push_back(
53 std::make_pair(SpanFrom("foo1"), std::make_unique<TestObject>("bar1")));
54 sorted_object_by_span.push_back(
55 std::make_pair(SpanFrom("foo2"), std::make_unique<TestObject>("bar2")));
56 sorted_object_by_span.push_back(
57 std::make_pair(SpanFrom("foo3"), std::make_unique<TestObject>("bar3")));
58 {
59 TestObject* result =
60 FindByFirst<TestObject>(sorted_object_by_span, SpanFrom("foo1"));
61 ASSERT_TRUE(result);
62 ASSERT_EQ("bar1", result->message());
63 }
64 {
65 TestObject* result =
66 FindByFirst<TestObject>(sorted_object_by_span, SpanFrom("foo3"));
67 ASSERT_TRUE(result);
68 ASSERT_EQ("bar3", result->message());
69 }
70 {
71 TestObject* result =
72 FindByFirst<TestObject>(sorted_object_by_span, SpanFrom("baz"));
73 ASSERT_FALSE(result);
74 }
75 }
76 } // namespace v8_crdtp
77