1 // SPDX-License-Identifier: 0BSD
3 ///////////////////////////////////////////////////////////////////////////////
5 /// \file tuklib_mbstr_width.c
6 /// \brief Calculate width of a multibyte string
8 // Author: Lasse Collin
10 ///////////////////////////////////////////////////////////////////////////////
12 #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
);
53 width
+= (size_t)wc_width
;
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.