Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions libc/src/__support/wchar/character_converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ constexpr uint32_t MASK_ENCODED_BITS =
mask_trailing_ones<uint32_t, ENCODED_BITS_PER_UTF8>();
// Maximum value for utf-32 for a utf-8 sequence of a given length
constexpr char32_t MAX_VALUE_PER_UTF8_LEN[] = {0x7f, 0x7ff, 0xffff, 0x10ffff};
constexpr int MAX_UTF8_LENGTH = 4;

CharacterConverter::CharacterConverter(mbstate *mbstate) { state = mbstate; }

Expand All @@ -43,12 +44,14 @@ bool CharacterConverter::isFull() {
bool CharacterConverter::isEmpty() { return state->bytes_stored == 0; }

bool CharacterConverter::isValidState() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this seems useful, can you use this in any of the other functions to simplify their logic?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see an obvious place to use this in any of the other functions, especially since the single character conversion functions (mbrtowc and wcrtomb) don't require checking this.

if (state->total_bytes > 4)
return false;

const char32_t max_utf32_value =
state->total_bytes == 0 ? 0
: MAX_VALUE_PER_UTF8_LEN[state->total_bytes - 1];
return state->bytes_stored <= state->total_bytes &&
state->bytes_stored >= 0 && state->total_bytes <= 4 &&
state->partial <= max_utf32_value;
state->bytes_stored >= 0 && state->partial <= max_utf32_value;
}

int CharacterConverter::push(char8_t utf8_byte) {
Expand Down Expand Up @@ -101,8 +104,7 @@ int CharacterConverter::push(char32_t utf32) {
state->partial = utf32;

// determine number of utf-8 bytes needed to represent this utf32 value
constexpr int NUM_RANGES = 4;
for (uint8_t i = 0; i < NUM_RANGES; i++) {
for (uint8_t i = 0; i < MAX_UTF8_LENGTH; i++) {
if (state->partial <= MAX_VALUE_PER_UTF8_LEN[i]) {
state->total_bytes = i + 1;
state->bytes_stored = i + 1;
Expand Down
Loading