Skip to content

Commit

Permalink
Add starts_with to basic_string_view. (#3080)
Browse files Browse the repository at this point in the history
Signed-off-by: Vladislav Shchapov <[email protected]>

Signed-off-by: Vladislav Shchapov <[email protected]>
  • Loading branch information
phprus authored Sep 4, 2022
1 parent d59b89e commit bac5395
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions include/fmt/core.h
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,18 @@ template <typename Char> class basic_string_view {
size_ -= n;
}

FMT_CONSTEXPR_CHAR_TRAITS bool starts_with(
basic_string_view<Char> sv) const noexcept {
return size_ >= sv.size_ &&
std::char_traits<Char>::compare(data_, sv.data_, sv.size_) == 0;
}
FMT_CONSTEXPR_CHAR_TRAITS bool starts_with(Char c) const noexcept {
return size_ >= 1 && std::char_traits<Char>::eq(*data_, c);
}
FMT_CONSTEXPR_CHAR_TRAITS bool starts_with(const Char* s) const {
return starts_with(basic_string_view<Char>(s));
}

// Lexicographically compare this string reference to other.
FMT_CONSTEXPR_CHAR_TRAITS auto compare(basic_string_view other) const -> int {
size_t str_size = size_ < other.size_ ? size_ : other.size_;
Expand Down
10 changes: 10 additions & 0 deletions test/core-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,16 @@ TEST(string_view_test, compare) {
EXPECT_LT(string_view("foo").compare(string_view("fop")), 0);
EXPECT_GT(string_view("foo").compare(string_view("fo")), 0);
EXPECT_LT(string_view("fo").compare(string_view("foo")), 0);

EXPECT_TRUE(string_view("foo").starts_with('f'));
EXPECT_FALSE(string_view("foo").starts_with('o'));
EXPECT_FALSE(string_view().starts_with('o'));

EXPECT_TRUE(string_view("foo").starts_with("fo"));
EXPECT_TRUE(string_view("foo").starts_with("foo"));
EXPECT_FALSE(string_view("foo").starts_with("fooo"));
EXPECT_FALSE(string_view().starts_with("fooo"));

check_op<std::equal_to>();
check_op<std::not_equal_to>();
check_op<std::less>();
Expand Down

0 comments on commit bac5395

Please sign in to comment.