util/string: Add cStr function
Change-Id: Ice2887f49cd4499b12c852943fde33374f87428f
Signed-off-by: William A. Kennington III <wak@google.com>
diff --git a/src/stdplus/util/string.hpp b/src/stdplus/util/string.hpp
index 4e37e3b..fad0d7a 100644
--- a/src/stdplus/util/string.hpp
+++ b/src/stdplus/util/string.hpp
@@ -20,6 +20,27 @@
} // namespace detail
+/** @brief Converts the string into its underlying nul-terminated c-str
+ *
+ * @param[in] str - The string reference
+ * @return The c-str
+ */
+template <typename Str, typename = std::enable_if_t<
+ std::is_same_v<std::remove_cv_t<Str>, std::string>>>
+auto cStr(Str& str)
+{
+ return str.data();
+}
+template <
+ typename Str,
+ typename = std::enable_if_t<
+ std::is_pointer_v<Str> &&
+ std::is_same_v<std::remove_cv_t<std::remove_pointer_t<Str>>, char>>>
+auto cStr(Str str)
+{
+ return str;
+}
+
/** @brief Appends multiple strings to the end of the destination string
* in the most optimal way for the given inputs.
*
diff --git a/test/util/string.cpp b/test/util/string.cpp
index 8ab4e81..26658a5 100644
--- a/test/util/string.cpp
+++ b/test/util/string.cpp
@@ -13,6 +13,18 @@
using namespace std::string_literals;
using namespace std::string_view_literals;
+TEST(CStr, Basic)
+{
+ std::string s1 = "a";
+ EXPECT_EQ(s1, cStr(s1));
+ const std::string s2 = "b";
+ EXPECT_EQ(s2, cStr(s2));
+ char s3[] = "c";
+ EXPECT_EQ(s3, cStr(s3));
+ const char* s4 = "d";
+ EXPECT_EQ(s4, cStr(s4));
+}
+
TEST(StrCat, NoStr)
{
EXPECT_EQ("", strCat());