Merge branch 'vendor/GREP'
[dragonfly.git] / contrib / grep / lib / hard-locale.c
1 /* hard-locale.c -- Determine whether a locale is hard.
2
3    Copyright (C) 1997-1999, 2002-2004, 2006-2007, 2009-2012 Free Software
4    Foundation, Inc.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #include <config.h>
20
21 #include "hard-locale.h"
22
23 #include <locale.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #ifdef __GLIBC__
28 # define GLIBC_VERSION __GLIBC__
29 #elif defined __UCLIBC__
30 # define GLIBC_VERSION 2
31 #else
32 # define GLIBC_VERSION 0
33 #endif
34
35 /* Return true if the current CATEGORY locale is hard, i.e. if you
36    can't get away with assuming traditional C or POSIX behavior.  */
37 bool
38 hard_locale (int category)
39 {
40   bool hard = true;
41   char const *p = setlocale (category, NULL);
42
43   if (p)
44     {
45       if (2 <= GLIBC_VERSION)
46         {
47           if (strcmp (p, "C") == 0 || strcmp (p, "POSIX") == 0)
48             hard = false;
49         }
50       else
51         {
52           char *locale = strdup (p);
53           if (locale)
54             {
55               /* Temporarily set the locale to the "C" and "POSIX" locales
56                  to find their names, so that we can determine whether one
57                  or the other is the caller's locale.  */
58               if (((p = setlocale (category, "C"))
59                    && strcmp (p, locale) == 0)
60                   || ((p = setlocale (category, "POSIX"))
61                       && strcmp (p, locale) == 0))
62                 hard = false;
63
64               /* Restore the caller's locale.  */
65               setlocale (category, locale);
66               free (locale);
67             }
68         }
69     }
70
71   return hard;
72 }