Skip to content

Commit

Permalink
Fix mbstowcs_nonfatal() that might convert string shorter than desired
Browse files Browse the repository at this point in the history
The "n" parameter of mbstowcs_nonfatal() refers to number of wide
characters. But the logic seemed to be confused with "n" parameter of
mbrtowc() (the number of bytes).

Signed-off-by: Kang-Che Sung <[email protected]>
  • Loading branch information
Explorer09 committed Jan 13, 2025
1 parent 64e9142 commit ffcc552
Showing 1 changed file with 3 additions and 4 deletions.
7 changes: 3 additions & 4 deletions RichString.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ in the source distribution for its full text.
#include <assert.h>
#include <ctype.h>
#include <limits.h> // IWYU pragma: keep
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

Expand Down Expand Up @@ -75,16 +76,15 @@ static size_t mbstowcs_nonfatal(wchar_t* restrict dest, const char* restrict src
mbstate_t ps = { 0 };
bool broken = false;

while (n > 0) {
size_t ret = mbrtowc(dest, src, n, &ps);
while (written < n) {
size_t ret = mbrtowc(dest, src, SIZE_MAX, &ps);
if (ret == (size_t)-1 || ret == (size_t)-2) {
if (!broken) {
broken = true;
*dest++ = L'\xFFFD';
written++;
}
src++;
n--;
continue;
}

Expand All @@ -97,7 +97,6 @@ static size_t mbstowcs_nonfatal(wchar_t* restrict dest, const char* restrict src
dest++;
written++;
src += ret;
n -= ret;
}

return written;
Expand Down

0 comments on commit ffcc552

Please sign in to comment.