1 /*
2 Copyright (c) 1990 Regents of the University of California.
3 All rights reserved.
4  */
5 /*
6 FUNCTION
7 <<wctomb>>---minimal wide char to multibyte converter
8 
9 INDEX
10 	wctomb
11 
12 SYNOPSIS
13 	#include <stdlib.h>
14 	int wctomb(char *<[s]>, wchar_t <[wchar]>);
15 
16 DESCRIPTION
17 When _MB_CAPABLE is not defined, this is a minimal ANSI-conforming
18 implementation of <<wctomb>>.  The
19 only ``wide characters'' recognized are single bytes,
20 and they are ``converted'' to themselves.
21 
22 When _MB_CAPABLE is defined, this routine calls <<_wctomb_r>> to perform
23 the conversion, passing a state variable to allow state dependent
24 decoding.  The result is based on the locale setting which may
25 be restricted to a defined set of locales.
26 
27 Each call to <<wctomb>> modifies <<*<[s]>>> unless <[s]> is a null
28 pointer or _MB_CAPABLE is defined and <[wchar]> is invalid.
29 
30 RETURNS
31 This implementation of <<wctomb>> returns <<0>> if
32 <[s]> is <<NULL>>; it returns <<-1>> if _MB_CAPABLE is enabled
33 and the wchar is not a valid multi-byte character, it returns <<1>>
34 if _MB_CAPABLE is not defined or the wchar is in reality a single
35 byte character, otherwise it returns the number of bytes in the
36 multi-byte character.
37 
38 PORTABILITY
39 <<wctomb>> is required in the ANSI C standard.  However, the precise
40 effects vary with the locale.
41 
42 <<wctomb>> requires no supporting OS subroutines.
43 */
44 
45 #include <stdlib.h>
46 #include <errno.h>
47 #include "local.h"
48 
49 int
wctomb(char * s,wchar_t wchar)50 wctomb (char *s,
51         wchar_t wchar)
52 {
53 #ifdef _MB_CAPABLE
54 	static NEWLIB_THREAD_LOCAL mbstate_t _wctomb_state;
55 
56         return __WCTOMB (s, wchar, &_wctomb_state);
57 #else /* not _MB_CAPABLE */
58         if (s == NULL)
59                 return 0;
60 
61 	/* Verify that wchar is a valid single-byte character.  */
62 	if ((size_t)wchar >= 0x100) {
63 		errno = EILSEQ;
64 		return -1;
65 	}
66 
67         *s = (char) wchar;
68         return 1;
69 #endif /* not _MB_CAPABLE */
70 }
71