xref: /illumos-gate/usr/src/lib/libc/port/i18n/wsprintf.c (revision 1da57d55)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1986 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 #include "lint.h"
31 #include <stdio.h>
32 #include <stdarg.h>
33 #include <stdlib.h>
34 #include <widec.h>
35 #include <string.h>
36 #include <limits.h>
37 
38 /*
39  * 	wsprintf -- this function will output a wchar_t string
40  *		    according to the conversion format.
41  *		    Note that the maximum length of the output
42  *		    string is 1024 bytes.
43  */
44 
45 /*VARARGS2*/
46 int
wsprintf(wchar_t * wstring,const char * format,...)47 wsprintf(wchar_t *wstring, const char *format, ...)
48 {
49 	va_list	ap;
50 	char	tempstring[1024];
51 	char *p2;
52 	size_t len;
53 	int malloced = 0;
54 	char *p1 = (char *)wstring;
55 	int retcode;
56 	int	i;
57 
58 	va_start(ap, format);
59 	if (vsprintf(p1, format, ap) == -1) {
60 		va_end(ap);
61 		return (-1);
62 	}
63 	va_end(ap);
64 	len = strlen(p1) + 1;
65 	if (len > 1024) {
66 		p2 = malloc(len);
67 		if (p2 == NULL)
68 			return (-1);
69 		malloced = 1;
70 	} else
71 		p2 = tempstring;
72 	(void) strcpy(p2, p1);
73 
74 	if (mbstowcs(wstring, p2, len) == (size_t)-1) {
75 		for (i = 0; i < len; i++) {
76 			if ((retcode = mbtowc(wstring, p2, MB_CUR_MAX)) == -1) {
77 				*wstring = (wchar_t)*p2 & 0xff;
78 				p2++;
79 			} else {
80 				p2 += retcode;
81 			}
82 			if (*wstring++ == (wchar_t)0) {
83 				break;
84 			}
85 		}
86 	}
87 
88 	if (malloced == 1)
89 		free(p2);
90 	len = wcslen(wstring);
91 	if (len <= INT_MAX)
92 		return ((int)len);
93 	else
94 		return (EOF);
95 }
96