BLI_string: add BLI_wcwidth_safe to avoid handling error values inline

This commit is contained in:
Campbell Barton
2023-09-18 11:47:33 +10:00
parent 2fac2228d0
commit 3eb30b048d
3 changed files with 13 additions and 11 deletions

View File

@@ -462,7 +462,7 @@ void blf_font_draw(FontBLF *font, const char *str, const size_t str_len, ResultB
int blf_font_draw_mono(FontBLF *font, const char *str, const size_t str_len, int cwidth)
{
GlyphBLF *g;
int col, columns = 0;
int columns = 0;
ft_pix pen_x = 0, pen_y = 0;
ft_pix cwidth_fpx = ft_pix_from_int(cwidth);
@@ -481,11 +481,7 @@ int blf_font_draw_mono(FontBLF *font, const char *str, const size_t str_len, int
/* do not return this loop if clipped, we want every character tested */
blf_glyph_draw(font, gc, g, ft_pix_to_int_floor(pen_x), ft_pix_to_int_floor(pen_y));
col = BLI_wcwidth(char32_t(g->c));
if (col < 0) {
col = 1;
}
const int col = BLI_wcwidth_safe(char32_t(g->c));
columns += col;
pen_x += cwidth_fpx * col;
}

View File

@@ -174,6 +174,7 @@ size_t BLI_strncpy_wchar_from_utf8(wchar_t *__restrict dst_w,
* Count columns that character/string occupies (based on `wcwidth.co`).
*/
int BLI_wcwidth(char32_t ucs) ATTR_WARN_UNUSED_RESULT;
int BLI_wcwidth_safe(char32_t ucs) ATTR_WARN_UNUSED_RESULT;
int BLI_wcswidth(const char32_t *pwcs, size_t n) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
/**

View File

@@ -460,6 +460,15 @@ int BLI_wcwidth(char32_t ucs)
return mk_wcwidth(ucs);
}
int BLI_wcwidth_safe(char32_t ucs)
{
const int columns = BLI_wcwidth(ucs);
if (columns >= 0) {
return columns;
}
return 1;
}
int BLI_wcswidth(const char32_t *pwcs, size_t n)
{
return mk_wcswidth(pwcs, n);
@@ -477,16 +486,12 @@ int BLI_str_utf8_char_width(const char *p)
int BLI_str_utf8_char_width_safe(const char *p)
{
int columns;
uint unicode = BLI_str_utf8_as_unicode(p);
if (unicode == BLI_UTF8_ERR) {
return 1;
}
columns = BLI_wcwidth((char32_t)unicode);
return (columns < 0) ? 1 : columns;
return BLI_wcwidth_safe((char32_t)unicode);
}
/* -------------------------------------------------------------------- */