From bac53951b827ac71abfe6a213be9d1e1a89d50aa Mon Sep 17 00:00:00 2001 From: Vladislav Shchapov Date: Sun, 4 Sep 2022 23:41:16 +0500 Subject: [PATCH] Add starts_with to basic_string_view. (#3080) Signed-off-by: Vladislav Shchapov Signed-off-by: Vladislav Shchapov --- include/fmt/core.h | 12 ++++++++++++ test/core-test.cc | 10 ++++++++++ 2 files changed, 22 insertions(+) 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();