encoding_utf.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // https://www.boost.org/LICENSE_1_0.txt
  6. #ifndef BOOST_LOCALE_ENCODING_UTF_HPP_INCLUDED
  7. #define BOOST_LOCALE_ENCODING_UTF_HPP_INCLUDED
  8. #include <boost/locale/encoding_errors.hpp>
  9. #include <boost/locale/utf.hpp>
  10. #include <boost/locale/util/string.hpp>
  11. #include <iterator>
  12. #ifdef BOOST_MSVC
  13. # pragma warning(push)
  14. # pragma warning(disable : 4275 4251 4231 4660)
  15. #endif
  16. namespace boost { namespace locale { namespace conv {
  17. /// \addtogroup codepage
  18. ///
  19. /// @{
  20. /// Convert a Unicode text in range [begin,end) to other Unicode encoding
  21. ///
  22. /// \throws conversion_error: Conversion failed (e.g. \a how is \c stop and any character cannot be decoded)
  23. template<typename CharOut, typename CharIn>
  24. std::basic_string<CharOut> utf_to_utf(const CharIn* begin, const CharIn* end, method_type how = default_method)
  25. {
  26. std::basic_string<CharOut> result;
  27. result.reserve(end - begin);
  28. std::back_insert_iterator<std::basic_string<CharOut>> inserter(result);
  29. while(begin != end) {
  30. const utf::code_point c = utf::utf_traits<CharIn>::decode(begin, end);
  31. if(c == utf::illegal || c == utf::incomplete) {
  32. if(how == stop)
  33. throw conversion_error();
  34. } else
  35. utf::utf_traits<CharOut>::encode(c, inserter);
  36. }
  37. return result;
  38. }
  39. /// Convert a Unicode NULL terminated string \a str other Unicode encoding
  40. ///
  41. /// \throws conversion_error: Conversion failed (e.g. \a how is \c stop and any character cannot be decoded)
  42. template<typename CharOut, typename CharIn>
  43. std::basic_string<CharOut> utf_to_utf(const CharIn* str, method_type how = default_method)
  44. {
  45. return utf_to_utf<CharOut, CharIn>(str, util::str_end(str), how);
  46. }
  47. /// Convert a Unicode string \a str other Unicode encoding
  48. ///
  49. /// \throws conversion_error: Conversion failed (e.g. \a how is \c stop and any character cannot be decoded)
  50. template<typename CharOut, typename CharIn>
  51. std::basic_string<CharOut> utf_to_utf(const std::basic_string<CharIn>& str, method_type how = default_method)
  52. {
  53. return utf_to_utf<CharOut, CharIn>(str.c_str(), str.c_str() + str.size(), how);
  54. }
  55. /// @}
  56. }}} // namespace boost::locale::conv
  57. #ifdef BOOST_MSVC
  58. # pragma warning(pop)
  59. #endif
  60. #endif