From aeeac9ca5490d7d90fe061ab72da446c01ddf746 Mon Sep 17 00:00:00 2001 From: Rich Felker Date: Wed, 27 May 2015 15:54:47 -0400 Subject: implement fail-safe static locales for newlocale this frees applications which need to make temporary use of the C locale (via uselocale) from the possibility that newlocale might fail. the C.UTF-8 locale is also provided as a static locale. presently they behave the same, but this may change in the future. --- src/locale/newlocale.c | 49 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 9 deletions(-) (limited to 'src/locale/newlocale.c') diff --git a/src/locale/newlocale.c b/src/locale/newlocale.c index 4e0cbd34..89d36b1d 100644 --- a/src/locale/newlocale.c +++ b/src/locale/newlocale.c @@ -3,21 +3,52 @@ #include "locale_impl.h" #include "libc.h" +extern const struct __locale_map __c_dot_utf8; + +static const struct __locale_struct c_locale = { 0 }; +static const struct __locale_struct c_dot_utf8_locale = { + .cat[LC_CTYPE] = &__c_dot_utf8 +}; + +int __loc_is_allocated(locale_t loc) +{ + return loc && loc != &c_locale && loc != &c_dot_utf8_locale; +} + locale_t __newlocale(int mask, const char *name, locale_t loc) { - int i; + int i, j; + struct __locale_struct tmp; + const struct __locale_map *lm; - if (!loc) { - loc = malloc(sizeof *loc); - if (!loc) return 0; + /* For locales with allocated storage, modify in-place. */ + if (__loc_is_allocated(loc)) { for (i=0; icat[i] = __get_locale(i, ""); + if (mask & (1<cat[i] = __get_locale(i, name); + return loc; + } + + /* Otherwise, build a temporary locale object, which will only + * be instantiated in allocated storage if it does not match + * one of the built-in static locales. This makes the common + * usage case for newlocale, getting a C locale with predictable + * behavior, very fast, and more importantly, fail-safe. */ + for (j=i=0; icat[i]; + else + lm = __get_locale(i, mask & (1<cat[i] = __get_locale(i, name); + if (!j) + return (locale_t)&c_locale; + if (j==1 && tmp.cat[LC_CTYPE]==c_dot_utf8_locale.cat[LC_CTYPE]) + return (locale_t)&c_dot_utf8_locale; + + if ((loc = malloc(sizeof *loc))) *loc = tmp; return loc; } -- cgit 1.4.1