From 5560e8dee6b87f89a2324dd90b89c2c233ab32a2 Mon Sep 17 00:00:00 2001 From: Tor Brede Vekterli Date: Thu, 24 Mar 2022 12:58:27 +0000 Subject: Use vespalib::string in TestAndSetCondition Avoids some implicit conversions. Add `starts_with` to `vespalib::string` and `vespalib::stringref` to allow drop-in replacement for Document API code. --- vespalib/src/tests/stllike/string_test.cpp | 19 +++++++++++++++++++ vespalib/src/vespa/vespalib/stllike/string.h | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+) (limited to 'vespalib') diff --git a/vespalib/src/tests/stllike/string_test.cpp b/vespalib/src/tests/stllike/string_test.cpp index de384bce9ad..d60380aa3ab 100644 --- a/vespalib/src/tests/stllike/string_test.cpp +++ b/vespalib/src/tests/stllike/string_test.cpp @@ -489,4 +489,23 @@ TEST("test that empty_string is shared and empty") { EXPECT_EQUAL(empty_string(), ""); } +TEST("starts_with has expected semantics for small_string") { + vespalib::string a("foobar"); + EXPECT_TRUE(a.starts_with("")); + EXPECT_TRUE(a.starts_with("foo")); + EXPECT_TRUE(a.starts_with("foobar")); + EXPECT_FALSE(a.starts_with("foobarf")); + EXPECT_FALSE(a.starts_with("oobar")); +} + +TEST("starts_with has expected semantics for stringref") { + vespalib::string a("foobar"); + vespalib::stringref ar(a); + EXPECT_TRUE(ar.starts_with("")); + EXPECT_TRUE(ar.starts_with("foo")); + EXPECT_TRUE(ar.starts_with("foobar")); + EXPECT_FALSE(ar.starts_with("foobarf")); + EXPECT_FALSE(ar.starts_with("oobar")); +} + TEST_MAIN() { TEST_RUN_ALL(); } diff --git a/vespalib/src/vespa/vespalib/stllike/string.h b/vespalib/src/vespa/vespalib/stllike/string.h index 2c0bb9a85d3..2e61d7ef0e9 100644 --- a/vespalib/src/vespa/vespalib/stllike/string.h +++ b/vespalib/src/vespa/vespalib/stllike/string.h @@ -111,6 +111,7 @@ public: } return npos; } + /** * Find the last occurrence of a substring, starting at e and * searching in reverse order. @@ -126,6 +127,17 @@ public: int diff(memcmp(_s, s, std::min(sz, size()))); return (diff != 0) ? diff : (size() - sz); } + + /** + * Returns true iff input string is a prefix of this string. + */ + [[nodiscard]] bool starts_with(stringref prefix) const noexcept { + if (prefix.size() > size()) { + return false; + } + return (memcmp(data(), prefix.data(), prefix.size()) == 0); + } + const char & operator [] (size_t i) const { return _s[i]; } operator std::string () const { return std::string(_s, _sz); } bool operator < (const char * s) const noexcept { return compare(s, strlen(s)) < 0; } @@ -256,6 +268,16 @@ public: _resize(size() - 1); } + /** + * Returns true iff input string is a prefix of this string. + */ + [[nodiscard]] bool starts_with(stringref prefix) const noexcept { + if (prefix.size() > size()) { + return false; + } + return (memcmp(buffer(), prefix.data(), prefix.size()) == 0); + } + /** * Find the last occurrence of a substring, starting at e and * searching in reverse order. -- cgit v1.2.3