mbtowc.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Copyright (C) 1991-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <http://www.gnu.org/licenses/>. */
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <wchar.h>
  17. #include <gconv.h>
  18. #include <wcsmbs/wcsmbsload.h>
  19. /* Convert the multibyte character at S, which is no longer
  20. than N characters, to its `wchar_t' representation, placing
  21. this n *PWC and returning its length.
  22. Attention: this function should NEVER be intentionally used.
  23. The interface is completely stupid. The state is shared between
  24. all conversion functions. You should use instead the restartable
  25. version `mbrtowc'. */
  26. int
  27. mbtowc (wchar_t *pwc, const char *s, size_t n)
  28. {
  29. int result;
  30. static mbstate_t state;
  31. /* If S is NULL the function has to return null or not null
  32. depending on the encoding having a state depending encoding or
  33. not. */
  34. if (s == NULL)
  35. {
  36. const struct gconv_fcts *fcts;
  37. /* Get the conversion functions. */
  38. fcts = get_gconv_fcts (_NL_CURRENT_DATA (LC_CTYPE));
  39. /* This is an extension in the Unix standard which does not directly
  40. violate ISO C. */
  41. memset (&state, '\0', sizeof state);
  42. result = fcts->towc->__stateful;
  43. }
  44. else if (*s == '\0')
  45. {
  46. if (pwc != NULL)
  47. *pwc = L'\0';
  48. result = 0;
  49. }
  50. else
  51. {
  52. result = __mbrtowc (pwc, s, n, &state);
  53. /* The `mbrtowc' functions tell us more than we need. Fold the -1
  54. and -2 result into -1. */
  55. if (result < 0)
  56. result = -1;
  57. }
  58. return result;
  59. }