| 1 | // |
| 2 | // Copyright (c) 2009-2011 Artyom Beilis (Tonkikh) |
| 3 | // Copyright (c) 2022-2023 Alexander Grund |
| 4 | // |
| 5 | // Distributed under the Boost Software License, Version 1.0. |
| 6 | // https://www.boost.org/LICENSE_1_0.txt |
| 7 | |
| 8 | #ifndef BOOST_LOCALE_UTIL_ENCODING_HPP |
| 9 | #define BOOST_LOCALE_UTIL_ENCODING_HPP |
| 10 | |
| 11 | #include <boost/locale/config.hpp> |
| 12 | #include <boost/utility/string_view.hpp> |
| 13 | #include <cstdint> |
| 14 | #include <string> |
| 15 | #include <type_traits> |
| 16 | #include <vector> |
| 17 | |
| 18 | namespace boost { namespace locale { namespace util { |
| 19 | |
| 20 | /// Get the UTF encoding name of the given \a CharType |
| 21 | template<typename CharType> |
| 22 | const char* utf_name() |
| 23 | { |
| 24 | constexpr auto CharSize = sizeof(CharType); |
| 25 | static_assert(CharSize == 1 || CharSize == 2 || CharSize == 4, "Unknown Character Encoding" ); |
| 26 | switch(CharSize) { |
| 27 | case 1: return "UTF-8" ; |
| 28 | case 2: { |
| 29 | const int16_t endianMark = 1; |
| 30 | const bool isLittleEndian = reinterpret_cast<const char*>(&endianMark)[0] == 1; |
| 31 | return isLittleEndian ? "UTF-16LE" : "UTF-16BE" ; |
| 32 | } |
| 33 | case 4: { |
| 34 | const int32_t endianMark = 1; |
| 35 | const bool isLittleEndian = reinterpret_cast<const char*>(&endianMark)[0] == 1; |
| 36 | return isLittleEndian ? "UTF-32LE" : "UTF-32BE" ; |
| 37 | } |
| 38 | } |
| 39 | BOOST_UNREACHABLE_RETURN("Unknown UTF" ); |
| 40 | } |
| 41 | |
| 42 | #ifdef __cpp_char8_t |
| 43 | template<typename T> |
| 44 | struct is_char8_t : std::is_same<T, char8_t> {}; |
| 45 | #else |
| 46 | template<typename T> |
| 47 | struct is_char8_t : std::false_type {}; |
| 48 | #endif |
| 49 | |
| 50 | /// Make encoding lowercase and remove all non-alphanumeric characters |
| 51 | BOOST_LOCALE_DECL std::string normalize_encoding(string_view encoding); |
| 52 | /// True if the normalized encodings are equal |
| 53 | inline bool are_encodings_equal(const std::string& l, const std::string& r) |
| 54 | { |
| 55 | return normalize_encoding(encoding: l) == normalize_encoding(encoding: r); |
| 56 | } |
| 57 | |
| 58 | BOOST_LOCALE_DECL std::vector<std::string> get_simple_encodings(); |
| 59 | |
| 60 | #if BOOST_LOCALE_USE_WIN32_API |
| 61 | int encoding_to_windows_codepage(string_view encoding); |
| 62 | #else |
| 63 | // Requires WinAPI -> Dummy returning invalid |
| 64 | inline int encoding_to_windows_codepage(string_view) // LCOV_EXCL_LINE |
| 65 | { |
| 66 | return -1; // LCOV_EXCL_LINE |
| 67 | } |
| 68 | #endif |
| 69 | |
| 70 | }}} // namespace boost::locale::util |
| 71 | |
| 72 | #endif |
| 73 | |