diff --git a/include/fmt/core.h b/include/fmt/core.h index a4b200d7..bc87b2f5 100644 --- a/include/fmt/core.h +++ b/include/fmt/core.h @@ -486,6 +486,18 @@ template class basic_string_view { size_ -= n; } + FMT_CONSTEXPR_CHAR_TRAITS bool starts_with( + basic_string_view sv) const noexcept { + return size_ >= sv.size_ && + std::char_traits::compare(data_, sv.data_, sv.size_) == 0; + } + FMT_CONSTEXPR_CHAR_TRAITS bool starts_with(Char c) const noexcept { + return size_ >= 1 && std::char_traits::eq(*data_, c); + } + FMT_CONSTEXPR_CHAR_TRAITS bool starts_with(const Char* s) const { + return starts_with(basic_string_view(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_; diff --git a/test/core-test.cc b/test/core-test.cc index 96cde1ed..6d1309fe 100644 --- a/test/core-test.cc +++ b/test/core-test.cc @@ -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(); check_op(); check_op();