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:
parent
38c6625e2c
commit
07188fff7f
@ -430,4 +430,17 @@ inline std::string Escape(const std::string_view &src) {
|
|||||||
return res;
|
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
|
} // namespace utils
|
||||||
|
@ -145,3 +145,22 @@ TEST(String, RandomString) {
|
|||||||
|
|
||||||
EXPECT_EQ(string_set.size(), 20);
|
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));
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user