stdex Additional custom or not Standard C++ covered algorithms

Loading...
Searching...
No Matches
locale.hpp
1/*
2 SPDX-License-Identifier: MIT
3 Copyright © 2016-2024 Amebis
4*/
5
6#pragma once
7
8#include "compat.hpp"
9#include <locale.h>
10#include <memory>
11
12#if defined(__GNUC__)
13#pragma GCC diagnostic push
14#pragma GCC diagnostic ignored "-Wexit-time-destructors"
15#endif
16
17 namespace stdex
18{
19#ifdef _WIN32
20 using locale_t = _locale_t;
21
22 inline locale_t create_locale(_In_ int category, _In_z_ const char* locale) { return _create_locale(category, locale); }
23 inline locale_t create_locale(_In_ int category, _In_z_ const wchar_t* locale) { return _wcreate_locale(category, locale); }
24 inline void free_locale(_In_opt_ locale_t locale) { _free_locale(locale); }
25#else
26 using locale_t = ::locale_t;
27
28 inline locale_t create_locale(_In_ int category, _In_z_ const char* locale)
29 {
30 int mask = 0;
31 switch (category) {
32 case LC_ALL : mask = LC_ALL_MASK ; break;
33 case LC_COLLATE : mask = LC_COLLATE_MASK ; break;
34 case LC_CTYPE : mask = LC_CTYPE_MASK ; break;
35 case LC_MESSAGES: mask = LC_MESSAGES_MASK; break;
36 case LC_MONETARY: mask = LC_MONETARY_MASK; break;
37 case LC_NUMERIC : mask = LC_NUMERIC_MASK ; break;
38 case LC_TIME : mask = LC_TIME_MASK ; break;
39 }
40 return newlocale(mask, locale, LC_GLOBAL_LOCALE);
41 }
42
43 inline void free_locale(_In_opt_ locale_t locale) { freelocale(locale); }
44#endif
45
49 struct free_locale_delete
50 {
54 void operator()(_In_ locale_t locale) const
55 {
56 free_locale(locale);
57 }
58 };
59
61#if defined(_WIN32)
62 using _locale_t_ref = __crt_locale_pointers;
63#elif defined(__APPLE__)
64 using _locale_t_ref = struct _xlocale;
65#else
66 using _locale_t_ref = struct __locale_struct;
67#endif
69
73 class locale : public std::unique_ptr<_locale_t_ref, free_locale_delete>
74 {
75 public:
76 locale() = default;
77
78 locale(_In_ locale_t ptr) :
79 std::unique_ptr<_locale_t_ref, free_locale_delete>(ptr)
80 {}
81
82 locale(_In_ int category, _In_z_ const char* locale) :
83 stdex::locale(create_locale(category, locale))
84 {}
85
86#ifdef _WIN32
87 locale(_In_ int category, _In_z_ const wchar_t* locale) :
88 stdex::locale(create_locale(category, locale))
89 {}
90#endif
91
92 operator locale_t() const { return get(); }
93 };
94
98 const inline locale locale_C(create_locale(LC_ALL, "C"));
99
103 const inline locale locale_utf8(create_locale(LC_ALL, ".UTF-8"));
104
108 inline locale locale_default(nullptr);
109}
110
111#if defined(__GNUC__)
112#pragma GCC diagnostic pop
113#endif
stdex::locale
locale_t helper class to free_locale when going out of scope.
Definition locale.hpp:74
stdex::free_locale_delete
Deleter for unique_ptr using free_locale.
Definition locale.hpp:50
stdex::free_locale_delete::operator()
void operator()(locale_t locale) const
Delete a pointer.
Definition locale.hpp:54