xref: /illumos-gate/usr/src/lib/libcurses/screen/mbtowc.c (revision f37b3cbb6f67aaea5eec1c335bdc7bf432867d64)
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) 1988 AT&T */
28 /*    All Rights Reserved   */
29 
30 #include <widec.h>
31 #include <ctype.h>
32 #include <sys/types.h>
33 #include "curses_wchar.h"
34 
35 int
36 _curs_mbtowc(wchar_t *wchar, const char *s, size_t n)
37 {
38 	int length, c;
39 	wchar_t intcode;
40 	char *olds = (char *)s;
41 	wchar_t mask;
42 
43 	if (s == (char *)0)
44 		return (0);
45 	if (n == 0)
46 		return (-1);
47 	c = (unsigned char)*s++;
48 	if (c < 0200) {
49 		if (wchar)
50 			*wchar = c;
51 		return (c ? 1 : 0);
52 	}
53 	intcode = 0;
54 	if (c == SS2) {
55 		if ((length = eucw2) == 0)
56 			goto lab1;
57 		mask = P01;
58 		goto lab2;
59 	} else if (c == SS3) {
60 		if ((length = eucw3) == 0)
61 			goto lab1;
62 		mask = P10;
63 		goto lab2;
64 	}
65 lab1:
66 	if (iscntrl(c)) {
67 		if (wchar)
68 			*wchar = c;
69 		return (1);
70 	}
71 	length = eucw1 - 1;
72 	mask = P11;
73 	intcode = c & 0177;
74 lab2:
75 	if (length + 1 > n || length < 0)
76 		return (-1);
77 	while (length--) {
78 		if ((c = (unsigned char)*s++) < 0200 || iscntrl(c))
79 			return (-1);
80 		intcode = (intcode << 7) | (c & 0x7F);
81 	}
82 	if (wchar)
83 		*wchar = intcode | mask;
84 	/*LINTED*/
85 	return ((int)(s - olds));
86 }
87