qxLib
locale.inl
Go to the documentation of this file.
1 /**
2 
3  @file locale.inl
4  @author Khrapov
5  @date 07.11.2026
6  @copyright (c) Nick Khrapov, 2026. All right reserved.
7 
8 **/
9 
10 namespace qx
11 {
12 
13 namespace details
14 {
15 
16 inline auto& get_locale_state()
17 {
18  struct locale_state
19  {
20 #if QX_STRING_USE_CRT_LOCALE
21  struct crt_locale_deleter
22  {
23  void operator()(_locale_t locale) const noexcept
24  {
25  if (locale)
26  _free_locale(locale);
27  }
28  };
29 
30  using crt_locale_ptr = std::unique_ptr<std::remove_pointer_t<_locale_t>, crt_locale_deleter>;
31 
32  locale_state()
33  {
34  set(locale);
35  }
36 #endif
37 
38  void set(const std::locale& value)
39  {
40 #if QX_STRING_USE_CRT_LOCALE
41  // On Windows, libc++ queries and switches the C locale for each character,
42  // causing contention on the CRT locale lock. The default named locale can
43  // instead use explicit CRT locale conversions without changing thread locale.
44  // These convert single bytes, not UTF-8 sequences; behavior for every CRT
45  // locale has not been verified. Explicit, custom and classic locales, or
46  // failure to create the CRT locale, fall back to the C++ facet.
47  const std::string sName = value.name();
48  crt_locale_ptr crtValue;
49  if (sName != "*" && sName != "C")
50  crtValue.reset(_create_locale(LC_CTYPE, sName.c_str()));
51 #endif
52  locale = value;
53  facet = &std::use_facet<std::ctype<wchar_t>>(locale);
54 #if QX_STRING_USE_CRT_LOCALE
55  crtLocale = std::move(crtValue);
56 #endif
57  }
58 
59  std::locale locale = std::locale();
60  const std::ctype<wchar_t>* facet = &std::use_facet<std::ctype<wchar_t>>(locale);
61 #if QX_STRING_USE_CRT_LOCALE
62  crt_locale_ptr crtLocale;
63 #endif
64  };
65 
66  static locale_state s_State;
67  return s_State;
68 }
69 
70 } // namespace details
71 
72 inline void set_locale(const std::locale& locale)
73 {
74  details::get_locale_state().set(locale);
75 }
76 
77 inline const std::locale& get_locale()
78 {
79  return details::get_locale_state().locale;
80 }
81 
82 inline const std::ctype<wchar_t>& get_locale_facet()
83 {
84  return *details::get_locale_state().facet;
85 }
86 
87 } // namespace qx
const std::locale & get_locale()
Get the default locale used by string converters.
Definition: locale.inl:77
const std::ctype< wchar_t > & get_locale_facet()
Get the cached character conversion facet for the default locale.
Definition: locale.inl:82
void set_locale(const std::locale &locale)
Set the locale used by string converters by default.
Definition: locale.inl:72