xref: /netbsd-src/external/bsd/tmux/dist/compat/utf8proc.c (revision 4e179ddab96f97aa64efc589ce1918be5318aaaf)
1 /*
2  * Copyright (c) 2016 Joshua Rubin <joshua@rubixconsulting.com>
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 MIND, USE, DATA OR PROFITS, WHETHER
13  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
14  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #include <sys/types.h>
18 
19 #include <utf8proc.h>
20 
21 #include "compat.h"
22 
23 int
utf8proc_wcwidth(wchar_t wc)24 utf8proc_wcwidth(wchar_t wc)
25 {
26 	int	cat;
27 
28 	cat = utf8proc_category(wc);
29 	if (cat == UTF8PROC_CATEGORY_CO) {
30 		/*
31 		 * The private use category is where powerline and similar
32 		 * codepoints are stored, they have "ambiguous" width - use 1.
33 		 */
34 		return (1);
35 	}
36 	return (utf8proc_charwidth(wc));
37 }
38 
39 int
utf8proc_mbtowc(wchar_t * pwc,const char * s,size_t n)40 utf8proc_mbtowc(wchar_t *pwc, const char *s, size_t n)
41 {
42 	utf8proc_ssize_t	slen;
43 
44 	if (s == NULL)
45 		return (0);
46 
47 	/*
48 	 * *pwc == -1 indicates invalid codepoint
49 	 * slen < 0 indicates an error
50 	 */
51 	slen = utf8proc_iterate(s, n, pwc);
52 	if (*pwc == (wchar_t)-1 || slen < 0)
53 		return (-1);
54 	return (slen);
55 }
56 
57 int
utf8proc_wctomb(char * s,wchar_t wc)58 utf8proc_wctomb(char *s, wchar_t wc)
59 {
60 	if (s == NULL)
61 		return (0);
62 
63 	if (!utf8proc_codepoint_valid(wc))
64 		return (-1);
65 	return (utf8proc_encode_char(wc, s));
66 }
67