Skip to content

Commit 7906fc0

Browse files
author
Sriya Pratipati
committed
fixed behavior when dst is nullptr and removed magic number
1 parent 6f08d75 commit 7906fc0

File tree

3 files changed

+6
-5
lines changed

3 files changed

+6
-5
lines changed

libc/src/__support/wchar/mbsrtowcs.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,13 @@ namespace internal {
2222
ErrorOr<size_t> mbsrtowcs(wchar_t *__restrict dst, const char **__restrict src,
2323
size_t len, mbstate *__restrict ps) {
2424
size_t i = 0;
25+
constexpr size_t MAX_UTF8_LENGTH = 4;
2526
// Converting characters until we reach error or null terminator
2627
for (; i < len; ++i, ++dst) {
27-
auto check = mbrtowc(dst, *src, 4, ps);
28+
auto check = mbrtowc(dst, *src, MAX_UTF8_LENGTH, ps);
2829
// Encoding error/invalid mbstate
2930
if (!check.has_value())
30-
return Error(check.error());
31+
return check;
3132
// Successfully encoded, check for null terminator
3233
if (*dst == L'\0') {
3334
*src = nullptr;

libc/src/wchar/mbsrtowcs.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ LLVM_LIBC_FUNCTION(size_t, mbsrtowcs,
2727
static internal::mbstate internal_mbstate;
2828
wchar_t temp[len];
2929
auto ret = internal::mbsrtowcs(
30-
dst == nullptr ? temp : dst, src, len,
30+
dst == nullptr ? temp : dst, src, dst == nullptr ? SIZE_MAX : len,
3131
ps == nullptr ? &internal_mbstate
3232
: reinterpret_cast<internal::mbstate *>(ps));
3333
if (!ret.has_value()) {

libc/test/src/wchar/mbsrtowcs_test.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,9 @@ TEST_F(LlvmLibcMBSRToWCSTest, NullDestination) {
102102
// Four laughing cat emojis "😹😹😹😹"
103103
const char *src =
104104
"\xf0\x9f\x98\xb9\xf0\x9f\x98\xb9\xf0\x9f\x98\xb9\xf0\x9f\x98\xb9";
105-
size_t n = LIBC_NAMESPACE::mbsrtowcs(nullptr, &src, 5, nullptr);
105+
size_t n = LIBC_NAMESPACE::mbsrtowcs(nullptr, &src, 2, nullptr);
106106
ASSERT_ERRNO_SUCCESS();
107-
// Null destination should still return correct number of read chars
107+
// Null destination should ignore len and read till end of string
108108
ASSERT_EQ(static_cast<int>(n), 4);
109109
}
110110

0 commit comments

Comments
 (0)