1 ///////////////////////////////////////////////////////////////////////////////
3 /// \file tuklib_mbstr_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"
16 #if defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
22 tuklib_mbstr_width(const char *str
, size_t *bytes
)
24 const size_t len
= strlen(str
);
28 #if !(defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH))
29 // In single-byte mode, the width of the string is the same
35 memset(&state
, 0, sizeof(state
));
40 // Convert one multibyte character at a time to wchar_t
41 // and get its width using wcwidth().
44 const size_t ret
= mbrtowc(&wc
, str
+ i
, len
- i
, &state
);
45 if (ret
< 1 || ret
> len
)
50 const int wc_width
= wcwidth(wc
);
54 width
+= (size_t)wc_width
;
57 // Require that the string ends in the initial shift state.
58 // This way the caller can be combine the string with other
59 // strings without needing to worry about the shift states.