| 1 | //===----------------------------------------------------------------------===// |
|---|---|
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include <__config> |
| 10 | #include <__locale_dir/locale_base_api.h> |
| 11 | #include <__utility/scope_guard.h> |
| 12 | #include <text_encoding> |
| 13 | |
| 14 | _LIBCPP_BEGIN_NAMESPACE_STD |
| 15 | _LIBCPP_BEGIN_EXPLICIT_ABI_ANNOTATIONS |
| 16 | |
| 17 | #if defined(__ANDROID__) |
| 18 | // UTF-8 is the always the environment encoding on Android. |
| 19 | std::text_encoding __get_locale_encoding([[maybe_unused]] const char* __name) { return std::text_encoding::id::UTF8; } |
| 20 | #else |
| 21 | static text_encoding __make_text_encoding(const char* __name) { |
| 22 | if (__name == nullptr) |
| 23 | return text_encoding{}; |
| 24 | |
| 25 | string_view __name_view(__name); |
| 26 | if (__name_view.size() > text_encoding::max_name_length) |
| 27 | return text_encoding{}; |
| 28 | |
| 29 | return text_encoding(__name_view); |
| 30 | } |
| 31 | |
| 32 | std::text_encoding __get_locale_encoding(const char* __name) { |
| 33 | if (__name == nullptr) |
| 34 | return __make_text_encoding(name: __locale::__get_locale_encoding(loc: static_cast<__locale::__locale_t>(0))); |
| 35 | |
| 36 | __locale::__locale_t __l = __locale::__newlocale(_LIBCPP_CTYPE_MASK, locale: __name, base: static_cast<__locale::__locale_t>(0)); |
| 37 | |
| 38 | __scope_guard __locale_guard([&__l] { |
| 39 | if (__l) { |
| 40 | __locale::__freelocale(loc: __l); |
| 41 | } |
| 42 | }); |
| 43 | |
| 44 | if (!__l) { |
| 45 | return text_encoding{}; |
| 46 | } |
| 47 | |
| 48 | return __make_text_encoding(name: __locale::__get_locale_encoding(loc: __l)); |
| 49 | } |
| 50 | |
| 51 | #endif // __ANDROID__ |
| 52 | |
| 53 | _LIBCPP_END_EXPLICIT_ABI_ANNOTATIONS |
| 54 | _LIBCPP_END_NAMESPACE_STD |
| 55 |