1 /*
2 * Copyright (c) 2015 Ingo Schwarze <schwarze@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 #include <err.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <wchar.h>
21
22 int
mbsavis(char ** outp,const char * mbs)23 mbsavis(char** outp, const char *mbs)
24 {
25 const char *src; /* Iterate mbs. */
26 char *dst; /* Iterate *outp. */
27 wchar_t wc;
28 int total_width; /* Display width of the whole string. */
29 int width; /* Display width of a single Unicode char. */
30 int len; /* Length in bytes of UTF-8 encoded string. */
31
32 len = strlen(mbs);
33 if ((*outp = malloc(len + 1)) == NULL)
34 err(1, NULL);
35
36 if (MB_CUR_MAX == 1) {
37 memcpy(*outp, mbs, len + 1);
38 return len;
39 }
40
41 src = mbs;
42 dst = *outp;
43 total_width = 0;
44 while (*src != '\0') {
45 if ((len = mbtowc(&wc, src, MB_CUR_MAX)) == -1) {
46 total_width++;
47 *dst++ = '?';
48 src++;
49 } else if ((width = wcwidth(wc)) == -1) {
50 total_width++;
51 *dst++ = '?';
52 src += len;
53 } else {
54 total_width += width;
55 while (len-- > 0)
56 *dst++ = *src++;
57 }
58 }
59 *dst = '\0';
60 return total_width;
61 }
62