Skip to content

Commit

Permalink
[libc] Add string construct/assign from string_view
Browse files Browse the repository at this point in the history
  • Loading branch information
gchatelet committed Aug 3, 2023
1 parent 055893b commit 51f91e1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions libc/src/__support/CPP/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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_);
Expand Down
21 changes: 21 additions & 0 deletions libc/test/src/__support/CPP/string_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 51f91e1

Please sign in to comment.