Skip to content

Commit

Permalink
string: fix basic_string operator!= and fix compare returning wrong v…
Browse files Browse the repository at this point in the history
…alue

Also add tests for the functionality.
  • Loading branch information
qookei committed Jul 2, 2022
1 parent 51d873b commit 264af2d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
16 changes: 10 additions & 6 deletions include/frg/string.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -292,13 +292,13 @@ class basic_string {
return _buffer + _length;
}

int compare(const basic_string<Char, Allocator> &other) const {
int compare(const basic_string &other) const {
if(_length != other.size())
return _length < other.size() ? -1 : 1;
for(size_t i = 0; i < _length; i++)
if(_buffer[i] != other[i])
return _buffer[i] < other[i] ? -1 : 1;
return true;
return 0;
}

int compare(const char *other) const {
Expand All @@ -307,19 +307,23 @@ class basic_string {
for(size_t i = 0; i < _length; i++)
if(_buffer[i] != other[i])
return _buffer[i] < other[i] ? -1 : 1;
return true;
return 0;
}

bool operator== (const basic_string<Char, Allocator> &other) const {
bool operator== (const basic_string &other) const {
return compare(other) == 0;
}

bool operator== (const char *rhs) const {
return compare(rhs) == 0;
}

bool operator!= (const basic_string_view<Char> &other) const {
return !(*this == other);
bool operator!= (const basic_string &other) const {
return compare(other) != 0;
}

bool operator!= (const char *rhs) const {
return compare(rhs) != 0;
}

operator basic_string_view<Char> () const {
Expand Down
18 changes: 18 additions & 0 deletions tests/tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,21 @@ TEST(strings, view_starts_ends_with) {

common_startsends_tests(ts1);
}

TEST(strings, operator_equals_comparison) {
string s1 { "Hello" }, s2 { "World" }, s3 { "Hello" };

EXPECT_NE(s1, s2);
EXPECT_NE(s2, s3);
EXPECT_EQ(s1, s3);
}

TEST(strings, compare_method_comparison) {
string s1 { "AAA" }, s2 { "AAB" }, s3 { "AA" }, s4 { "AAA" };

EXPECT_EQ(s1.compare(s2), -1);
EXPECT_EQ(s2.compare(s1), 1);
EXPECT_EQ(s1.compare(s3), 1);
EXPECT_EQ(s3.compare(s1), -1);
EXPECT_EQ(s1.compare(s4), 0);
}

0 comments on commit 264af2d

Please sign in to comment.