Skip to content

Commit

Permalink
StringView: Add StringView::operator==(StringView)
Browse files Browse the repository at this point in the history
Previously we'd implicitly convert the second StringView to a String
when comparing two StringViews, which is obviously not what we wanted.
  • Loading branch information
awesomekling committed Aug 15, 2019
1 parent 77737be commit 2349dc1
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
16 changes: 16 additions & 0 deletions AK/StringView.h
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,22 @@ class StringView {

bool operator==(const String&) const;

bool operator==(const StringView& other) const
{
if (is_null())
return other.is_null();
if (other.is_null())
return false;
if (length() != other.length())
return false;
return !memcmp(m_characters, other.m_characters, m_length);
}

bool operator!=(const StringView& other) const
{
return !(*this == other);
}

private:
friend class String;
const StringImpl* m_impl { nullptr };
Expand Down
4 changes: 3 additions & 1 deletion AK/Tests/Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
PROGRAMS = TestString TestQueue TestVector TestHashMap TestJSON TestWeakPtr TestNonnullRefPtr TestRefPtr TestFixedArray TestFileSystemPath TestURL
PROGRAMS = TestString TestQueue TestVector TestHashMap TestJSON TestWeakPtr TestNonnullRefPtr TestRefPtr TestFixedArray TestFileSystemPath TestURL TestStringView

CXXFLAGS = -std=c++17 -Wall -Wextra -ggdb3 -O2 -I../ -I../../

Expand Down Expand Up @@ -62,6 +62,8 @@ TestFileSystemPath: TestFileSystemPath.o $(SHARED_TEST_OBJS)
TestURL: TestURL.o $(SHARED_TEST_OBJS)
$(PRE_CXX) $(CXX) $(CXXFLAGS) -o $@ TestURL.o $(SHARED_TEST_OBJS)

TestStringView: TestStringView.o $(SHARED_TEST_OBJS)
$(PRE_CXX) $(CXX) $(CXXFLAGS) -o $@ TestStringView.o $(SHARED_TEST_OBJS)

clean:
rm -f $(SHARED_TEST_OBJS)
Expand Down
36 changes: 36 additions & 0 deletions AK/Tests/TestStringView.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include <AK/TestSuite.h>

#include <AK/AKString.h>

TEST_CASE(construct_empty)
{
EXPECT(StringView().is_null());
EXPECT(StringView().is_empty());
EXPECT(!StringView().characters_without_null_termination());
EXPECT_EQ(StringView().length(), 0);
}

TEST_CASE(view_literal)
{
const char* truth = "cats rule dogs drool";
StringView view(truth);
EXPECT_EQ(view.is_null(), false);
EXPECT_EQ(view.characters_without_null_termination(), truth);
EXPECT_EQ(view, view);
EXPECT_EQ(view, truth);
}

TEST_CASE(compare_views)
{
String foo1 = "foo";
String foo2 = "foo";
auto view1 = foo1.view();
auto view2 = foo2.view();

EXPECT_EQ(view1, view2);
EXPECT_EQ(view1, foo1);
EXPECT_EQ(view1, foo2);
EXPECT_EQ(view1, "foo");
}

TEST_MAIN(StringView)

0 comments on commit 2349dc1

Please sign in to comment.