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.
This commit is contained in:
Lasse Collin 2024-10-21 18:51:24 +03:00
parent 51081efae4
commit df399c5255
No known key found for this signature in database
GPG Key ID: 38EE757D69184620
2 changed files with 25 additions and 0 deletions

View File

@ -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, /// (size_t)-1 is returned. Possible errors include invalid,
/// partial, or non-printable multibyte character in str. /// 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) #define tuklib_mbstr_fw TUKLIB_SYMBOL(tuklib_mbstr_fw)
extern int tuklib_mbstr_fw(const char *str, int columns_min); extern int tuklib_mbstr_fw(const char *str, int columns_min);
///< ///<

View File

@ -24,9 +24,17 @@ tuklib_mbstr_width(const char *str, size_t *bytes)
if (bytes != NULL) if (bytes != NULL)
*bytes = len; *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 #ifndef HAVE_MBRTOWC
// In single-byte mode, the width of the string is the same // In single-byte mode, the width of the string is the same
// as its length. // as its length.
(void)str;
return len; return len;
#else #else