1 ///////////////////////////////////////////////////////////////////////////////
3 /// \file tuklib_mstr_width.c
4 /// \brief Calculate width of a multibyte string
6 // Author: Lasse Collin
8 // This file has been put into the public domain.
9 // You can do whatever you want with this file.
11 ///////////////////////////////////////////////////////////////////////////////
13 #include "tuklib_mbstr.h"
15 #if defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
21 tuklib_mbstr_width(const char *str, size_t *bytes)
23 const size_t len = strlen(str);
27 #if !(defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH))
28 // In single-byte mode, the width of the string is the same
34 memset(&state, 0, sizeof(state));
39 // Convert one multibyte character at a time to wchar_t
40 // and get its width using wcwidth().
43 const size_t ret = mbrtowc(&wc, str + i, len - i, &state);
44 if (ret < 1 || ret > len)
49 const int wc_width = wcwidth(wc);
56 // Require that the string ends in the initial shift state.
57 // This way the caller can be combine the string with other
58 // strings without needing to worry about the shift states.