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