1 /*
2 Copyright (c) 1990 Regents of the University of California.
3 All rights reserved.
4  */
5 /*
6 FUNCTION
7 <<mbtowc>>---minimal multibyte to wide char converter
8 
9 INDEX
10 	mbtowc
11 
12 SYNOPSIS
13 	#include <stdlib.h>
14 	int mbtowc(wchar_t *restrict <[pwc]>, const char *restrict <[s]>, size_t <[n]>);
15 
16 DESCRIPTION
17 When _MB_CAPABLE is not defined, this is a minimal ANSI-conforming
18 implementation of <<mbtowc>>.  In this case,
19 only ``multi-byte character sequences'' recognized are single bytes,
20 and they are ``converted'' to themselves.
21 Each call to <<mbtowc>> copies one character from <<*<[s]>>> to
22 <<*<[pwc]>>>, unless <[s]> is a null pointer.  The argument n
23 is ignored.
24 
25 When _MB_CAPABLE is defined, this routine uses a state variable to
26 allow state dependent decoding.  The result is based on the locale
27 setting which may be restricted to a defined set of locales.
28 
29 RETURNS
30 This implementation of <<mbtowc>> returns <<0>> if
31 <[s]> is <<NULL>> or is the empty string;
32 it returns <<1>> if not _MB_CAPABLE or
33 the character is a single-byte character; it returns <<-1>>
34 if n is <<0>> or the multi-byte character is invalid;
35 otherwise it returns the number of bytes in the multibyte character.
36 If the return value is -1, no changes are made to the <<pwc>>
37 output string.  If the input is the empty string, a wchar_t nul
38 is placed in the output string and 0 is returned.  If the input
39 has a length of 0, no changes are made to the <<pwc>> output string.
40 
41 PORTABILITY
42 <<mbtowc>> is required in the ANSI C standard.  However, the precise
43 effects vary with the locale.
44 
45 <<mbtowc>> requires no supporting OS subroutines.
46 */
47 
48 #include <stdlib.h>
49 #include <wchar.h>
50 #include "local.h"
51 
52 int
mbtowc(wchar_t * __restrict pwc,const char * __restrict s,size_t n)53 mbtowc (wchar_t *__restrict pwc,
54         const char *__restrict s,
55         size_t n)
56 {
57 #ifdef _MB_CAPABLE
58   int retval = 0;
59   static NEWLIB_THREAD_LOCAL mbstate_t _mbtowc_state;
60 
61   retval = __MBTOWC (pwc, s, n, &_mbtowc_state);
62 
63   if (retval < 0)
64     {
65       _mbtowc_state.__count = 0;
66       return -1;
67     }
68   return retval;
69 #else /* not _MB_CAPABLE */
70   if (s == NULL)
71     return 0;
72   if (n == 0)
73     return -1;
74   if (pwc)
75     *pwc = (wchar_t) *s;
76   return (*s != '\0');
77 #endif /* not _MB_CAPABLE */
78 }
79