[libc-commits] [libc] 51f91e1 - [libc] Add string construct/assign from string_view
Guillaume Chatelet via libc-commits
libc-commits at lists.llvm.org
Thu Aug 3 06:26:07 PDT 2023
Author: Guillaume Chatelet
Date: 2023-08-03T13:25:53Z
New Revision: 51f91e104559a4a59adf09eb54f756c8f7b66a28
URL: https://github.com/llvm/llvm-project/commit/51f91e104559a4a59adf09eb54f756c8f7b66a28
DIFF: https://github.com/llvm/llvm-project/commit/51f91e104559a4a59adf09eb54f756c8f7b66a28.diff
LOG: [libc] Add string construct/assign from string_view
Added:
Modified:
libc/src/__support/CPP/string.h
libc/test/src/__support/CPP/string_test.cpp
Removed:
################################################################################
diff --git a/libc/src/__support/CPP/string.h b/libc/src/__support/CPP/string.h
index f050defe498ced..239fa18eac36d3 100644
--- a/libc/src/__support/CPP/string.h
+++ b/libc/src/__support/CPP/string.h
@@ -58,6 +58,8 @@ class string {
resize(count);
inline_memcpy(buffer_, cstr, count);
}
+ LIBC_INLINE string(const string_view &view)
+ : string(view.data(), view.size()) {}
LIBC_INLINE string(const char *cstr)
: string(cstr, ::__llvm_libc::internal::string_length(cstr)) {}
LIBC_INLINE string(size_t size_, char value) {
@@ -78,6 +80,10 @@ class string {
return *this;
}
+ LIBC_INLINE string &operator=(const string_view &view) {
+ return *this = string(view);
+ }
+
LIBC_INLINE ~string() {
if (buffer_ != get_empty_string())
::free(buffer_);
diff --git a/libc/test/src/__support/CPP/string_test.cpp b/libc/test/src/__support/CPP/string_test.cpp
index f7a18214eb8116..928277fe2e9cc7 100644
--- a/libc/test/src/__support/CPP/string_test.cpp
+++ b/libc/test/src/__support/CPP/string_test.cpp
@@ -62,6 +62,16 @@ TEST(LlvmLibcStringTest, InitializeCStringWithSize) {
ASSERT_EQ(s.back(), 'b');
}
+TEST(LlvmLibcStringTest, InitializeStringView) {
+ const string_view str = "ab";
+ const string s(str);
+ ASSERT_EQ(s.size(), size_t(2));
+ ASSERT_EQ(s[0], 'a');
+ ASSERT_EQ(s[1], 'b');
+ ASSERT_EQ(s.front(), 'a');
+ ASSERT_EQ(s.back(), 'b');
+}
+
TEST(LlvmLibcStringTest, InitializeRepeatedChar) {
const string s(4, '1');
ASSERT_EQ(string_view(s), string_view("1111"));
@@ -114,6 +124,17 @@ TEST(LlvmLibcStringTest, MoveAssign) {
ASSERT_STREQ(a.c_str(), "");
}
+TEST(LlvmLibcStringTest, StringViewAssign) {
+ const string_view str = "ab";
+ string s;
+ s = str;
+ ASSERT_EQ(s.size(), size_t(2));
+ ASSERT_EQ(s[0], 'a');
+ ASSERT_EQ(s[1], 'b');
+ ASSERT_EQ(s.front(), 'a');
+ ASSERT_EQ(s.back(), 'b');
+}
+
TEST(LlvmLibcStringTest, Concat) {
const char *const str = "abc";
string a(str);
More information about the libc-commits
mailing list