From df399c52554dfdf60259ca2cce97adbcfff39dc0 Mon Sep 17 00:00:00 2001 From: Lasse Collin Date: Mon, 21 Oct 2024 18:51:24 +0300 Subject: [PATCH] tuklib_mbstr_width: Add tuklib_mbstr_width_mem() It's a new function split from tuklib_mbstr_width(). It's useful with partial strings that aren't terminated with \0. --- src/common/tuklib_mbstr.h | 17 +++++++++++++++++ src/common/tuklib_mbstr_width.c | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/src/common/tuklib_mbstr.h b/src/common/tuklib_mbstr.h index 3ab0a82a..5ac06eb3 100644 --- a/src/common/tuklib_mbstr.h +++ b/src/common/tuklib_mbstr.h @@ -37,6 +37,23 @@ extern size_t tuklib_mbstr_width(const char *str, size_t *bytes); /// (size_t)-1 is returned. Possible errors include invalid, /// partial, or non-printable multibyte character in str. +#define tuklib_mbstr_width_mem TUKLIB_SYMBOL(tuklib_mbstr_width_mem) +extern size_t tuklib_mbstr_width_mem(const char *str, size_t len); +///< +/// \brief Get the number of columns needed for the multibyte buffer +/// +/// This is like tuklib_mbstr_width() except that this takes the buffer +/// length in bytes as the second argument. This allows using the function +/// for buffers that aren't terminated with '\0'. +/// +/// \param str String whose width is to be calculated. +/// \param len Number of bytes to read from str. +/// +/// \return On success, the number of columns needed to display the +/// string e.g. in a terminal emulator is returned. On error, +/// (size_t)-1 is returned. Possible errors include invalid, +/// partial, or non-printable multibyte character in str. + #define tuklib_mbstr_fw TUKLIB_SYMBOL(tuklib_mbstr_fw) extern int tuklib_mbstr_fw(const char *str, int columns_min); ///< diff --git a/src/common/tuklib_mbstr_width.c b/src/common/tuklib_mbstr_width.c index f003aed1..98c611d8 100644 --- a/src/common/tuklib_mbstr_width.c +++ b/src/common/tuklib_mbstr_width.c @@ -24,9 +24,17 @@ tuklib_mbstr_width(const char *str, size_t *bytes) if (bytes != NULL) *bytes = len; + return tuklib_mbstr_width_mem(str, len); +} + + +extern size_t +tuklib_mbstr_width_mem(const char *str, size_t len) +{ #ifndef HAVE_MBRTOWC // In single-byte mode, the width of the string is the same // as its length. + (void)str; return len; #else