From 07188fff7f915ac5d084a67a493e424f93fb9621 Mon Sep 17 00:00:00 2001 From: Teon Banek Date: Thu, 30 May 2019 10:23:17 +0200 Subject: [PATCH] Add utils::Substr which can use different allocator Reviewers: mtomic, msantl, mferencevic Reviewed By: msantl Subscribers: pullbot Differential Revision: https://phabricator.memgraph.io/D2103 --- src/utils/string.hpp | 13 +++++++++++++ tests/unit/utils_string.cpp | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/utils/string.hpp b/src/utils/string.hpp index 173a0fadc..7b418843b 100644 --- a/src/utils/string.hpp +++ b/src/utils/string.hpp @@ -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 diff --git a/tests/unit/utils_string.cpp b/tests/unit/utils_string.cpp index 712794116..5d93560c8 100644 --- a/tests/unit/utils_string.cpp +++ b/tests/unit/utils_string.cpp @@ -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)); +}