]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
enhance: Add util::to_span and util::to_string_view functions
authorJoel Rosdahl <joel@rosdahl.net>
Mon, 5 Sep 2022 11:19:03 +0000 (13:19 +0200)
committerJoel Rosdahl <joel@rosdahl.net>
Tue, 6 Sep 2022 06:13:29 +0000 (08:13 +0200)
src/util/string.hpp

index 5ee9716d6dee7364171437e7a4bf5057ff766d5c..d9c7fe59575d1e01d109bf7c653f48792cb4b8a5 100644 (file)
 #pragma once
 
 #include <third_party/nonstd/expected.hpp>
+#include <third_party/nonstd/span.hpp>
 
 #include <sys/stat.h> // for mode_t
 
+#include <cstdint>
 #include <cstring>
 #include <optional>
 #include <string>
@@ -110,10 +112,16 @@ bool starts_with(std::string_view string, std::string_view prefix);
 // Strip whitespace from left and right side of a string.
 [[nodiscard]] std::string strip_whitespace(std::string_view string);
 
+// Convert `value` to a `nonstd::span<const uint8_t>`.
+nonstd::span<const uint8_t> to_span(std::string_view value);
+
 // Convert `value` to a string. This function is used when joining
 // `std::string`s with `util::join`.
 template<typename T> std::string to_string(const T& value);
 
+// Convert `data` to a `std::string_view`.
+std::string_view to_string_view(nonstd::span<const uint8_t> data);
+
 // --- Inline implementations ---
 
 inline bool
@@ -158,6 +166,13 @@ starts_with(const std::string_view string, const std::string_view prefix)
   return string.substr(0, prefix.size()) == prefix;
 }
 
+inline nonstd::span<const uint8_t>
+to_span(std::string_view data)
+{
+  return nonstd::span<const uint8_t>(
+    reinterpret_cast<const uint8_t*>(data.data()), data.size());
+}
+
 template<typename T>
 inline std::string
 to_string(const T& t)
@@ -180,4 +195,11 @@ to_string(const std::string_view& sv)
   return std::string(sv);
 }
 
+inline std::string_view
+to_string_view(nonstd::span<const uint8_t> data)
+{
+  return std::string_view(reinterpret_cast<const char*>(data.data()),
+                          data.size());
+}
+
 } // namespace util