mblen.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. /* Internal state. */
  20. static mbstate_t state;
  21. /* Return the length of the multibyte character (if there is one)
  22. at S which is no longer than N characters.
  23. The ISO C standard says that the `mblen' function must not change
  24. the state of the `mbtowc' function. */
  25. int
  26. mblen (const char *s, size_t n)
  27. {
  28. int result;
  29. /* If S is NULL the function has to return null or not null
  30. depending on the encoding having a state depending encoding or
  31. not. */
  32. if (s == NULL)
  33. {
  34. const struct gconv_fcts *fcts;
  35. /* Get the conversion functions. */
  36. fcts = get_gconv_fcts (_NL_CURRENT_DATA (LC_CTYPE));
  37. /* Reset the state. */
  38. memset (&state, '\0', sizeof state);
  39. result = fcts->towc->__stateful;
  40. }
  41. else if (*s == '\0')
  42. /* According to the ISO C 89 standard this is the expected behaviour. */
  43. result = 0;
  44. else
  45. {
  46. memset (&state, '\0', sizeof state);
  47. result = __mbrtowc (NULL, s, n, &state);
  48. /* The `mbrtowc' functions tell us more than we need. Fold the -1
  49. and -2 result into -1. */
  50. if (result < 0)
  51. result = -1;
  52. }
  53. return result;
  54. }