]> git.draconx.ca Git - dxcommon.git/blob - t/nls/mbswidth.c
help_print_optstring: Test fullwidth/halfwidth character output.
[dxcommon.git] / t / nls / mbswidth.c
1 /*
2  * Copyright © 2023 Nick Bowler
3  *
4  * Simplified mbsnwidth for test purposes.
5  *
6  * License WTFPL2: Do What The Fuck You Want To Public License, version 2.
7  * This is free software: you are free to do what the fuck you want to.
8  * There is NO WARRANTY, to the extent permitted by law.
9  */
10
11 #include <string.h>
12 #include <locale.h>
13 #include <wchar.h>
14
15 #include "mbswidth.h"
16
17 int mbsnwidth(const char *buf, size_t buflen, int flags)
18 {
19         static int initialized;
20         mbstate_t ps;
21         int ret = 0;
22
23         if (!initialized) {
24                 setlocale(LC_CTYPE, "");
25                 initialized = 1;
26         }
27
28         memset(&ps, 0, sizeof ps);
29         while (buflen > 0) {
30                 wchar_t wc;
31                 size_t l;
32                 int w;
33
34                 l = mbrtowc(&wc, buf, buflen, &ps);
35                 if (l == (size_t)-1 || l == (size_t)-2)
36                         return -1;
37                 else if (l == 0)
38                         break;
39
40                 buflen -= l;
41                 buf += l;
42
43                 w = wcwidth(wc);
44                 if (w < 0)
45                         return -1;
46                 ret += w;
47         }
48
49         return ret;
50 }