newlocale.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include "locale_impl.h"
  4. #include "libc.h"
  5. extern const struct __locale_map __c_dot_utf8;
  6. static const struct __locale_struct c_locale = { 0 };
  7. static const struct __locale_struct c_dot_utf8_locale = {
  8. .cat[LC_CTYPE] = &__c_dot_utf8
  9. };
  10. int __loc_is_allocated(locale_t loc)
  11. {
  12. return loc && loc != &c_locale && loc != &c_dot_utf8_locale;
  13. }
  14. locale_t __newlocale(int mask, const char *name, locale_t loc)
  15. {
  16. int i, j;
  17. struct __locale_struct tmp;
  18. const struct __locale_map *lm;
  19. /* For locales with allocated storage, modify in-place. */
  20. if (__loc_is_allocated(loc)) {
  21. for (i=0; i<LC_ALL; i++)
  22. if (mask & (1<<i))
  23. loc->cat[i] = __get_locale(i, name);
  24. return loc;
  25. }
  26. /* Otherwise, build a temporary locale object, which will only
  27. * be instantiated in allocated storage if it does not match
  28. * one of the built-in static locales. This makes the common
  29. * usage case for newlocale, getting a C locale with predictable
  30. * behavior, very fast, and more importantly, fail-safe. */
  31. for (j=i=0; i<LC_ALL; i++) {
  32. if (loc && !(mask & (1<<i)))
  33. lm = loc->cat[i];
  34. else
  35. lm = __get_locale(i, mask & (1<<i) ? name : "");
  36. if (lm) j++;
  37. tmp.cat[i] = lm;
  38. }
  39. if (!j)
  40. return (locale_t)&c_locale;
  41. if (j==1 && tmp.cat[LC_CTYPE]==c_dot_utf8_locale.cat[LC_CTYPE])
  42. return (locale_t)&c_dot_utf8_locale;
  43. if ((loc = malloc(sizeof *loc))) *loc = tmp;
  44. return loc;
  45. }
  46. weak_alias(__newlocale, newlocale);