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