1 /* ncmpc (Ncurses MPD Client)
2  * (c) 2004-2020 The Music Player Daemon Project
3  * Project homepage: http://musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #include "StringUTF8.hxx"
21 
22 #include <string.h>
23 
24 #ifdef HAVE_LOCALE_T
25 #include <langinfo.h>
26 #include <locale.h>
27 
28 static locale_t utf8_locale = locale_t(0);
29 
ScopeInitUTF8()30 ScopeInitUTF8::ScopeInitUTF8() noexcept
31 {
32 	const char *charset = nl_langinfo(CODESET);
33 	if (charset == nullptr || strcasecmp(charset, "utf-8") == 0)
34 		/* if we're already UTF-8, we don't need a special
35 		   UTF-8 locale */
36 		return;
37 
38 	locale_t l = duplocale(LC_GLOBAL_LOCALE);
39 	if (l == locale_t(0))
40 		return;
41 
42 	locale_t l2 = newlocale(LC_COLLATE_MASK, "en_US.UTF-8", l);
43 	if (l2 == locale_t(0)) {
44 		freelocale(l);
45 		return;
46 	}
47 
48 	utf8_locale = l2;
49 }
50 
~ScopeInitUTF8()51 ScopeInitUTF8::~ScopeInitUTF8() noexcept
52 {
53 	if (utf8_locale != locale_t(0)) {
54 		freelocale(utf8_locale);
55 		utf8_locale = locale_t(0);
56 	}
57 }
58 
59 #endif
60 
61 gcc_pure
62 int
CollateUTF8(const char * a,const char * b)63 CollateUTF8(const char *a, const char *b)
64 {
65 #ifdef HAVE_LOCALE_T
66 	if (utf8_locale != locale_t(0))
67 		return strcoll_l(a, b, utf8_locale);
68 #endif
69 
70 	return strcoll(a, b);
71 }
72