[String8] Add string_view ctor
For convenience add a std::string_view ctor to String8.
This allows for easy std::string to String8 conversion.
Test: compiles
Test: atest libutils_binder_test
Bug: none
Flag: EXEMPT trivial
Change-Id: I188362e4045891e1a68ea433a47e08d27490f473
diff --git a/libutils/binder/String8_test.cpp b/libutils/binder/String8_test.cpp
index fc3c329..ff9bc8d 100644
--- a/libutils/binder/String8_test.cpp
+++ b/libutils/binder/String8_test.cpp
@@ -176,3 +176,11 @@
EXPECT_TRUE(pair1 < pair2);
EXPECT_FALSE(pair1 > pair2);
}
+
+TEST_F(String8Test, SvCtor) {
+ const char* expected = "abc";
+ std::string s{expected};
+ EXPECT_STREQ(String8{s}.c_str(), expected);
+ EXPECT_STREQ(String8{std::string_view{s}}.c_str(), expected);
+ EXPECT_STREQ(String8{expected}.c_str(), expected);
+}
diff --git a/libutils/binder/include/utils/String8.h b/libutils/binder/include/utils/String8.h
index e0d7588..11415a1 100644
--- a/libutils/binder/include/utils/String8.h
+++ b/libutils/binder/include/utils/String8.h
@@ -57,6 +57,9 @@
String8(const String8& o);
explicit String8(const char* o);
explicit String8(const char* o, size_t numChars);
+#ifdef HAS_STRING_VIEW
+ explicit String8(std::string_view o);
+#endif
explicit String8(const String16& o);
explicit String8(const char16_t* o);
@@ -374,6 +377,9 @@
}
#ifdef HAS_STRING_VIEW
+
+inline String8::String8(std::string_view o) : String8(o.data(), o.length()) { }
+
inline String8::operator std::string_view() const
{
return {mString, length()};