1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2020 Robert Mustacchi
14  */
15 
16 /*
17  * C11 c32rtomb(3C) support.
18  *
19  * The char32_t type is designed to represent a UTF-32 value, which is what we
20  * can represent with a wchar_t. This is basically a wrapper around wcrtomb().
21  */
22 
23 #include <locale.h>
24 #include <wchar.h>
25 #include <xlocale.h>
26 #include <uchar.h>
27 #include <errno.h>
28 #include "unicode.h"
29 
30 static mbstate_t c32rtomb_state;
31 
32 size_t
c32rtomb(char * restrict str,char32_t c32,mbstate_t * restrict ps)33 c32rtomb(char *restrict str, char32_t c32, mbstate_t *restrict ps)
34 {
35 	if ((c32 >= UNICODE_SUR_MIN && c32 <= UNICODE_SUR_MAX) ||
36 	    c32 > UNICODE_SUP_MAX) {
37 		errno = EILSEQ;
38 		return ((size_t)-1);
39 	}
40 
41 	if (ps == NULL) {
42 		ps = &c32rtomb_state;
43 	}
44 
45 	if (str == NULL) {
46 		c32 = L'\0';
47 	}
48 
49 	return (wcrtomb_l(str, (wchar_t)c32, ps, uselocale((locale_t)0)));
50 }
51