Skip to content

Commit

Permalink
[Minor] Add utility to iterate over a list of newline separated strings
Browse files Browse the repository at this point in the history
  • Loading branch information
vstakhov committed Jun 24, 2023
1 parent f89a5b7 commit 8c1c1dd
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/libutil/cxx/util.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,35 @@ inline constexpr auto make_string_view_from_it(_It begin, _It end)
};
}

/**
* Iterate over lines in a string, newline characters are dropped
* @tparam S
* @tparam F
* @param input
* @param functor
* @return
*/
template<class S, class F, typename std::enable_if_t<std::is_invocable_v<F, std::string_view> &&
std::is_constructible_v<std::string_view, S>, bool> = true>
inline auto string_foreach_line(const S &input, const F &functor)
{
auto it = input.begin();
auto end = input.end();

while (it != end) {
auto next = std::find(it, end, '\n');
while (next >= it && (*next == '\n' || *next == '\r')) {
--next;
}
functor(make_string_view_from_it(it, next));
it = next;

if (it != end) {
++it;
}
}
}

/**
* Enumerate for range loop
*/
Expand Down

0 comments on commit 8c1c1dd

Please sign in to comment.