} | } | ||||
inline bool ends_with(std::string_view s, std::string_view key) { | inline bool ends_with(std::string_view s, std::string_view key) { | ||||
auto found = s.find(key); | |||||
auto found = s.rfind(key); | |||||
return found != s.npos && found == s.size() - key.size(); | return found != s.npos && found == s.size() - key.size(); | ||||
} | } | ||||
inline bool starts_with(std::string_view s, std::string_view key) { return s.find(key) == 0; } | |||||
inline bool contains(std::string_view s, std::string_view key) { return s.find(key) != s.npos; } | |||||
inline std::vector<std::string> split(std::string_view str, std::string_view sep) { | |||||
std::vector<std::string> ret; | |||||
std::string_view::size_type prev_pos = 0; | |||||
auto pos = prev_pos; | |||||
while ((pos = str.find(sep, prev_pos)) != str.npos) { | |||||
ret.emplace_back(str.substr(prev_pos, pos - prev_pos)); | |||||
prev_pos = pos + sep.length(); | |||||
} | |||||
ret.emplace_back(str.substr(prev_pos)); | |||||
return ret; | |||||
} | |||||
template <typename Container, typename Predicate> | template <typename Container, typename Predicate> | ||||
void erase_if(Container& c, Predicate&& p) { | void erase_if(Container& c, Predicate&& p) { | ||||
auto erase_point = std::remove_if(c.begin(), c.end(), p); | auto erase_point = std::remove_if(c.begin(), c.end(), p); |
#include <dds/util.hpp> | |||||
#include <dds/util.test.hpp> | |||||
using namespace dds; | |||||
namespace { | |||||
#define CHECK_SPLIT(str, key, ...) \ | |||||
do { \ | |||||
CHECK(dds::split(str, key) == std::vector<std::string>(__VA_ARGS__)); \ | |||||
} while (0) | |||||
void test_starts_with() { | |||||
CHECK(starts_with("foo", "foo")); | |||||
CHECK(starts_with("foo.bar", "foo")); | |||||
CHECK(starts_with("foo", "f")); | |||||
CHECK(starts_with("foo", "")); | |||||
CHECK(starts_with("", "")); | |||||
CHECK(!starts_with("foo", "foot")); | |||||
CHECK(!starts_with("", "cat")); | |||||
CHECK(!starts_with("foo.bar", "bar")); | |||||
} | |||||
void test_ends_with() { | |||||
CHECK(ends_with("foo", "foo")); | |||||
CHECK(ends_with("foo.bar", "bar")); | |||||
CHECK(ends_with("foo", "o")); | |||||
CHECK(ends_with("foo", "")); | |||||
CHECK(ends_with("", "")); | |||||
CHECK(!ends_with("foo", "foot")); | |||||
CHECK(!ends_with("", "cat")); | |||||
CHECK(!ends_with("foo.bar", "foo")); | |||||
} | |||||
void test_contains() { | |||||
CHECK(contains("foo", "foo")); | |||||
CHECK(contains("foo", "")); | |||||
CHECK(contains("foo", "o")); | |||||
CHECK(!contains("foo", "bar")); | |||||
} | |||||
void test_split() { | |||||
CHECK_SPLIT("foo.bar", ".", {"foo", "bar"}); | |||||
CHECK_SPLIT("foo.bar.baz", ".", {"foo", "bar", "baz"}); | |||||
CHECK_SPLIT(".", ".", {"", ""}); | |||||
CHECK_SPLIT("", ",", {""}); | |||||
} | |||||
void run_tests() { | |||||
test_starts_with(); | |||||
test_ends_with(); | |||||
test_contains(); | |||||
test_split(); | |||||
} | |||||
} // namespace | |||||
DDS_TEST_MAIN; |