libluna: Simplify the API for Utf8StateDecoder by splitting it into multiple methods
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-06-18 18:38:01 +02:00
parent 27d9cd0e87
commit d45e9e2a8c
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 25 additions and 10 deletions

View File

@ -127,12 +127,12 @@ namespace TextConsole
{ {
auto guard = make_scope_guard([] { utf8_decoder.reset(); }); auto guard = make_scope_guard([] { utf8_decoder.reset(); });
const Option<wchar_t> maybe_wchar = TRY(utf8_decoder.feed(c)); bool is_ready = TRY(utf8_decoder.feed(c));
if (is_ready) putwchar(TRY(utf8_decoder.extract()));
guard.deactivate(); guard.deactivate();
if (maybe_wchar.has_value()) putwchar(maybe_wchar.value());
return {}; return {};
} }

View File

@ -52,13 +52,16 @@ class Utf8StateDecoder
public: public:
Utf8StateDecoder(); Utf8StateDecoder();
Result<Option<wchar_t>> feed(char c); Result<bool> feed(char c);
Result<wchar_t> extract();
void reset(); void reset();
private: private:
char m_state[4]; char m_state[4];
usize m_state_len = 0; usize m_state_len = 0;
usize m_state_index = 0; usize m_state_index = 0;
wchar_t m_decoded_character;
bool m_has_character_ready { false };
}; };
class Utf8Encoder class Utf8Encoder

View File

@ -217,19 +217,23 @@ Utf8StateDecoder::Utf8StateDecoder() : m_state_len(0), m_state_index(0)
{ {
} }
Result<Option<wchar_t>> Utf8StateDecoder::feed(char c) Result<bool> Utf8StateDecoder::feed(char c)
{ {
check(!m_has_character_ready);
if (m_state_len == 0) if (m_state_len == 0)
{ {
m_state_len = TRY(utf8_char_length(c)); m_state_len = TRY(utf8_char_length(c));
if (m_state_len == 1) if (m_state_len == 1)
{ {
m_state_len = 0; m_state_len = 0;
return Option<wchar_t> { c & 0x7f }; m_decoded_character = c & 0x7f;
m_has_character_ready = true;
return true;
} }
m_state_index = 0; m_state_index = 0;
m_state[m_state_index] = c; m_state[m_state_index] = c;
return { {} }; return false;
} }
m_state_index++; m_state_index++;
@ -238,12 +242,20 @@ Result<Option<wchar_t>> Utf8StateDecoder::feed(char c)
if (m_state_index == m_state_len - 1) if (m_state_index == m_state_len - 1)
{ {
usize len = m_state_len; usize len = m_state_len;
const wchar_t wc = TRY(encode_utf8_as_wide_char(m_state, len)); m_decoded_character = TRY(encode_utf8_as_wide_char(m_state, len));
m_has_character_ready = true;
m_state_len = 0; m_state_len = 0;
return Option<wchar_t> { wc }; return true;
} }
return { {} }; return false;
}
Result<wchar_t> Utf8StateDecoder::extract()
{
check(m_has_character_ready);
m_has_character_ready = false;
return m_decoded_character;
} }
void Utf8StateDecoder::reset() void Utf8StateDecoder::reset()