xref: /titanic_41/usr/src/lib/libc/port/i18n/wsprintf.c (revision 82629e3015252bf18319ba3815c773df23e21436)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 #include "lint.h"
33 #include <stdio.h>
34 #include <stdarg.h>
35 #include <stdlib.h>
36 #include <widec.h>
37 #include <string.h>
38 #include <limits.h>
39 
40 /*
41  * 	wsprintf -- this function will output a wchar_t string
42  *		    according to the conversion format.
43  *		    Note that the maximum length of the output
44  *		    string is 1024 bytes.
45  */
46 
47 /*VARARGS2*/
48 int
49 wsprintf(wchar_t *wstring, const char *format, ...)
50 {
51 	va_list	ap;
52 	char	tempstring[1024];
53 	char *p2;
54 	size_t len;
55 	int malloced = 0;
56 	char *p1 = (char *)wstring;
57 	int retcode;
58 	int	i;
59 
60 	va_start(ap, format);
61 	if (vsprintf(p1, format, ap) == -1) {
62 		va_end(ap);
63 		return (-1);
64 	}
65 	va_end(ap);
66 	len = strlen(p1) + 1;
67 	if (len > 1024) {
68 		p2 = malloc(len);
69 		if (p2 == NULL)
70 			return (-1);
71 		malloced = 1;
72 	} else
73 		p2 = tempstring;
74 	(void) strcpy(p2, p1);
75 
76 	if (mbstowcs(wstring, p2, len) == (size_t)-1) {
77 		for (i = 0; i < len; i++) {
78 			if ((retcode = mbtowc(wstring, p2, MB_CUR_MAX)) == -1) {
79 				*wstring = (wchar_t)*p2 & 0xff;
80 				p2++;
81 			} else {
82 				p2 += retcode;
83 			}
84 			if (*wstring++ == (wchar_t)0) {
85 				break;
86 			}
87 		}
88 	}
89 
90 	if (malloced == 1)
91 		free(p2);
92 	len = wcslen(wstring);
93 	if (len <= INT_MAX)
94 		return ((int)len);
95 	else
96 		return (EOF);
97 }
98