xref: /illumos-gate/usr/src/lib/libc/port/i18n/wsscanf.c (revision d48be21240dfd051b689384ce2b23479d757f2d8)
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 "file64.h"
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <widec.h>
36 #include <string.h>
37 #include "libc.h"
38 #include "stdiom.h"
39 
40 /*
41  * 	wsscanf -- this function will read wchar_t characters from
42  *		    wchar_t string according to the conversion format.
43  *		    Note that the performance degrades if the intermediate
44  *		    result of conversion exceeds 1024 bytes due to the
45  *		    use of malloc() on each call.
46  *		    We should implement wchar_t version of doscan()
47  *		    for better performance.
48  */
49 #define	MAXINSTR	1024
50 
51 int
52 wsscanf(wchar_t *string, const char *format, ...)
53 {
54 	va_list		ap;
55 	size_t		i;
56 	char		stackbuf[MAXINSTR];
57 	char		*tempstring = stackbuf;
58 	size_t		malloced = 0;
59 	int		j;
60 
61 	i = wcstombs(tempstring, string, MAXINSTR);
62 	if (i == (size_t)-1)
63 		return (-1);
64 
65 	if (i == MAXINSTR) { /* The buffer was too small.  Malloc it. */
66 		tempstring = malloc(malloced = MB_CUR_MAX*wcslen(string)+1);
67 		if (tempstring == 0)
68 			return (-1);
69 		i = wcstombs(tempstring, string, malloced); /* Try again. */
70 		if (i == (size_t)-1) {
71 			free(tempstring);
72 			return (-1);
73 		}
74 	}
75 
76 	va_start(ap, format);
77 	j = vsscanf(tempstring, format, ap);
78 	va_end(ap);
79 	if (malloced) free(tempstring);
80 	return (j);
81 }
82