// useful_mbtowc.c // PUBLIC DOMAIN // http:///www.purposeful.co.uk/software/yabaplib /* I, Tom Vajzovic, am the author of this software and its documentation. I permanently abandon all intellectual property rights in them, including copyright, trademarks, design rights, database right, patents, and the right to be identified as the author. I am fairly certain that the software does what the documentation says it does, but I do not guarantee that it does, or that it does what you think it should. I do not guarantee that it will not have undesirable side effects. You are free to use, modify and distribute this software as you please, but you do so at your own risk. If you do not pass on this warning then you may be responsible for any problems encountered by those who obtain the software through you. */ #include #include ssize_t useful_mbtowc( wchar_t *pwc, const char *s, size_t n, mbstate_t *ps ) { size_t try; mbstate_t starting_state= {0}; /* possible warning about under-bracing */ /* explanation: although it is not stated explicitly in ISO9899:99, */ /* it is my understanding that {0} is the only portable way to */ /* initialise an mbstate_t. */ if( ps ) starting_state= *ps; for( try= 1; try <= n; ++try ) { mbstate_t state= starting_state; size_t overloaded_return= mbrtowc( pwc, s, try, & state ); if( overloaded_return == (size_t)-1 ) return -1; if( overloaded_return == (size_t)-2 ) continue; if( ps ) *ps= state; return try; } return 0; } ssize_t useful_mbstowcs( wchar_t *pwc, size_t nwc, const char *s, size_t n, mbstate_t *ps, const char **endp ) { size_t chars_input= 0; size_t wchars_output= 0; ssize_t coversion_result= 1; mbstate_t default_state= {0}; /* possible warning about under-bracing */ /* explanation: although it is not stated explicitly in ISO9899:99, */ /* it is my understanding that {0} is the only portable way to */ /* initialise an mbstate_t. */ if( ! ps ) ps= & default_state; while( (chars_input < n) && (wchars_output < nwc) && (coversion_result > 0) ) { coversion_result= useful_mbtowc( pwc + wchars_output, s + chars_input, n - chars_input, ps ); if( coversion_result > 0 ) { chars_input+= coversion_result; wchars_output+= 1; } } if( endp ) *endp= s + chars_input; if( coversion_result < 0 ) return -1; return wchars_output; }