xref: /original-bsd/lib/libc/locale/ansi.c (revision f4546c36)
1 /*-
2  * Copyright (c) 1993 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Paul Borman at Krystal Technologies.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #if defined(LIBC_SCCS) && !defined(lint)
12 static char sccsid[] = "@(#)ansi.c	5.2 (Berkeley) 05/27/93";
13 #endif /* LIBC_SCCS and not lint */
14 
15 #include <stdlib.h>
16 #include <limits.h>
17 #include <stddef.h>
18 #include <rune.h>
19 
20 int
21 mblen(s, n)
22 	const char *s;
23 	size_t n;
24 {
25 	char const *e;
26 
27 	if (s == 0 || *s == 0)
28 		return (0);	/* No support for state dependent encodings. */
29 
30 	if (sgetrune(s, (int)n, &e) == _INVALID_RUNE)
31 		return (s - e);
32 	return (e - s);
33 }
34 
35 int
36 mbtowc(pwc, s, n)
37 	wchar_t *pwc;
38 	const char *s;
39 	size_t n;
40 {
41 	char const *e;
42 	rune_t r;
43 
44 	if (s == 0 || *s == 0)
45 		return (0);	/* No support for state dependent encodings. */
46 
47 	if ((r = sgetrune(s, (int)n, &e)) == _INVALID_RUNE)
48 		return (s - e);
49 	if (pwc)
50 		*pwc = r;
51 	return (e - s);
52 }
53 
54 int
55 wctomb(s, wchar)
56 	char *s;
57 	wchar_t wchar;
58 {
59 	char *e;
60 
61 	if (s == 0)
62 		return (0);	/* No support for state dependent encodings. */
63 
64 	if (wchar == 0) {
65 		*s = 0;
66 		return (1);
67 	}
68 
69 	sputrune(wchar, s, MB_CUR_MAX, &e);
70 	return (e ? e - s : -1);
71 }
72 
73 size_t
74 mbstowcs(pwcs, s, n)
75 	wchar_t *pwcs;
76 	const char *s;
77 	size_t n;
78 {
79 	char const *e;
80 	int cnt = 0;
81 
82 	if (!pwcs || !s)
83 		return (-1);
84 
85 	while (n-- > 0) {
86 		*pwcs = sgetrune(s, MB_LEN_MAX, &e);
87 		if (*pwcs == _INVALID_RUNE)
88 			return (-1);
89 		if (*pwcs++ == 0)
90 			break;
91 		s = e;
92 		++cnt;
93 	}
94 	return (cnt);
95 }
96 
97 size_t
98 wcstombs(s, pwcs, n)
99 	char *s;
100 	const wchar_t *pwcs;
101 	size_t n;
102 {
103 	char *e;
104 	int cnt = 0;
105 
106 	if (!pwcs || !s)
107 		return (-1);
108 
109 	while (n > 0) {
110 		if (*pwcs == 0) {
111 			*s = 0;
112 			break;
113 		}
114 		if (!sputrune(*pwcs++, s, (int)n, &e))
115 			return (-1);		/* encoding error */
116 		if (!e)			/* too long */
117 			return (cnt);
118 		cnt += e - s;
119 		s = e;
120 	}
121 	return (cnt);
122 }
123