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