]> git-server-git.apps.pok.os.sepia.ceph.com Git - ceph.git/commitdiff
common: add for_each_substr() for cheap string split
authorCasey Bodley <cbodley@redhat.com>
Tue, 7 Nov 2017 15:54:59 +0000 (10:54 -0500)
committerCasey Bodley <cbodley@redhat.com>
Fri, 10 Nov 2017 16:06:35 +0000 (11:06 -0500)
using boost::string_view avoids copies (and potential allocation) of
the substrings

using a callback model avoids baking in the container type, along with
the copies and allocations required for insertion

this interface is ideal for cases where you just want to iterate over
the substrings, and don't actually need to store them in a container

Signed-off-by: Casey Bodley <cbodley@redhat.com>
src/include/str_list.h

index 0a50be7af397aff470595c7c5eafda55ecb1ae77..7f5e71659c03ea266e581d6799f5de4adbbfbde1 100644 (file)
@@ -5,6 +5,26 @@
 #include <set>
 #include <string>
 #include <vector>
+#include <boost/utility/string_view.hpp>
+
+
+namespace ceph {
+
+/// Split a string using the given delimiters, passing each piece as a
+/// (non-null-terminated) boost::string_view to the callback.
+template <typename Func> // where Func(boost::string_view) is a valid call
+void for_each_substr(boost::string_view s, const char *delims, Func&& f)
+{
+  auto pos = s.find_first_not_of(delims);
+  while (pos != s.npos) {
+    s.remove_prefix(pos); // trim delims from the front
+    auto end = s.find_first_of(delims);
+    f(s.substr(0, end));
+    pos = s.find_first_not_of(delims, end);
+  }
+}
+
+} // namespace ceph
 
 /**
  * Split **str** into a list of strings, using the ";,= \t" delimiters and output the result in **str_list**.