Add utils::Substr which can use different allocator

Reviewers: mtomic, msantl, mferencevic

Reviewed By: msantl

Subscribers: pullbot

Differential Revision: https://phabricator.memgraph.io/D2103
This commit is contained in:
Teon Banek 2019-05-30 10:23:17 +02:00
parent 38c6625e2c
commit 07188fff7f
2 changed files with 32 additions and 0 deletions

View File

@ -430,4 +430,17 @@ inline std::string Escape(const std::string_view &src) {
return res;
}
/**
* Return a view into substring [pos, pos+count).
* If the bounds extend past the length of the string then both sides are
* clamped to a valid interval. Therefore, this function never throws
* std::out_of_range, unlike std::basic_string::substr.
*/
inline std::string_view Substr(const std::string_view &string, size_t pos = 0,
size_t count = std::string::npos) {
if (pos >= string.size()) return std::string_view(string.data(), 0);
auto len = std::min(string.size() - pos, count);
return std::string_view(string.data() + pos, len);
}
} // namespace utils

View File

@ -145,3 +145,22 @@ TEST(String, RandomString) {
EXPECT_EQ(string_set.size(), 20);
}
// NOLINTNEXTLINE(hicpp-special-member-functions)
TEST(String, Substr) {
const std::string string("memgraph");
EXPECT_EQ(Substr(string), string.substr());
EXPECT_EQ(Substr(string, string.size()), string.substr(string.size()));
EXPECT_THROW(string.substr(string.size() + 1), std::out_of_range);
EXPECT_TRUE(Substr(string, string.size() + 1).empty());
EXPECT_EQ(Substr(string, 1, string.size()), string.substr(1, string.size()));
EXPECT_EQ(Substr(string, 0, string.size()), string.substr(0, string.size()));
EXPECT_EQ(Substr(string, 0, string.size() + 1),
string.substr(0, string.size() + 1));
EXPECT_EQ(Substr(string, 0, string.size() - 1),
string.substr(0, string.size() - 1));
EXPECT_EQ(Substr(string, string.size() - 1, 1),
string.substr(string.size() - 1, 1));
EXPECT_EQ(Substr(string, string.size() - 1, 2),
string.substr(string.size() - 1, 2));
}