Skip to content

Commit cbd8a2f

Browse files
committed
fix: add vector parser util func
1 parent 8ad7f39 commit cbd8a2f

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

include/plg/string.hpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3935,7 +3935,7 @@ std::ostream& operator<<(std::ostream& os, const plg::basic_string<Char, Traits,
39353935
return os;
39363936
}
39373937

3938-
#ifndef PLUGIFY_STRING_NO_STD_FORMAT
3938+
#ifndef PLUGIFY_STRING_NO_STD_UTIL
39393939
#include <functional>
39403940

39413941
namespace plg {
@@ -4024,4 +4024,4 @@ namespace plg {
40244024
return result;
40254025
}
40264026
} // namespace plugify
4027-
#endif // PLUGIFY_STRING_NO_STD_FORMAT
4027+
#endif // PLUGIFY_STRING_NO_STD_UTIL

include/plg/vector.hpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1572,3 +1572,53 @@ namespace plg {
15721572
using vector = ::plg::vector<T, std::pmr::polymorphic_allocator<T>>;
15731573
} // namespace pmr
15741574
} // namespace plg
1575+
1576+
#ifndef PLUGIFY_VECTOR_NO_STD_UTIL
1577+
#include <optional>
1578+
#include <string_view>
1579+
#include <charconv>
1580+
1581+
namespace plg {
1582+
constexpr vector<std::string_view> split(std::string_view str, std::string_view delims = " ") {
1583+
vector<std::string_view> output;
1584+
size_t first = 0;
1585+
1586+
while (first < str.size()) {
1587+
const size_t second = str.find_first_of(delims, first);
1588+
1589+
if (first != second)
1590+
output.emplace_back(str.substr(first, second - first));
1591+
1592+
if (second == std::string_view::npos)
1593+
break;
1594+
1595+
first = second + 1;
1596+
}
1597+
1598+
return output;
1599+
}
1600+
1601+
template<typename T>
1602+
constexpr std::optional<T> cast_to(std::string_view str) {
1603+
T value;
1604+
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
1605+
if (ec == std::errc()) {
1606+
return value;
1607+
}
1608+
return std::nullopt;
1609+
}
1610+
1611+
template<typename T>
1612+
constexpr vector<T> parse(std::string_view str, std::string_view delims = " ") {
1613+
vector<T> vec;
1614+
auto items = split(str, delims);
1615+
vec.reserve(items.size());
1616+
for (const auto& item : items) {
1617+
if (auto value = cast_to<T>(item)) {
1618+
vec.emplace_back(*value);
1619+
}
1620+
}
1621+
return vec;
1622+
}
1623+
} // namespace plugify
1624+
#endif // PLUGIFY_VECTOR_NO_STD_UTIL

0 commit comments

Comments
 (0)