simplify newlocale and allow failure for explicit locale names
[musl] / src / locale / newlocale.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include "locale_impl.h"
4
5 int __loc_is_allocated(locale_t loc)
6 {
7         return loc && loc != C_LOCALE && loc != UTF8_LOCALE;
8 }
9
10 locale_t __newlocale(int mask, const char *name, locale_t loc)
11 {
12         struct __locale_struct tmp;
13
14         for (int i=0; i<LC_ALL; i++) {
15                 tmp.cat[i] = (!(mask & (1<<i)) && loc) ? loc->cat[i] :
16                         __get_locale(i, (mask & (1<<i)) ? name : "");
17                 if (tmp.cat[i] == LOC_MAP_FAILED)
18                         return 0;
19         }
20
21         /* For locales with allocated storage, modify in-place. */
22         if (__loc_is_allocated(loc)) {
23                 *loc = tmp;
24                 return loc;
25         }
26
27         /* Otherwise, first see if we can use one of the builtin locales.
28          * This makes the common usage case for newlocale, getting a C locale
29          * with predictable behavior, very fast, and more importantly, fail-safe. */
30         if (!memcmp(&tmp, C_LOCALE, sizeof tmp)) return C_LOCALE;
31         if (!memcmp(&tmp, UTF8_LOCALE, sizeof tmp)) return UTF8_LOCALE;
32
33         /* If no builtin locale matched, attempt to allocate and copy. */
34         if ((loc = malloc(sizeof *loc))) *loc = tmp;
35
36         return loc;
37 }
38
39 weak_alias(__newlocale, newlocale);