encoding_utf.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. template<typename CharOut, typename CharIn>
  22. std::basic_string<CharOut> utf_to_utf(const CharIn* begin, const CharIn* end, method_type how = default_method)
  23. {
  24. std::basic_string<CharOut> result;
  25. result.reserve(end - begin);
  26. typedef std::back_insert_iterator<std::basic_string<CharOut>> inserter_type;
  27. inserter_type inserter(result);
  28. utf::code_point c;
  29. while(begin != end) {
  30. c = utf::utf_traits<CharIn>::template decode<const CharIn*>(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>::template encode<inserter_type>(c, inserter);
  36. }
  37. }
  38. return result;
  39. }
  40. /// Convert a Unicode NULL terminated string \a str other Unicode encoding
  41. template<typename CharOut, typename CharIn>
  42. std::basic_string<CharOut> utf_to_utf(const CharIn* str, method_type how = default_method)
  43. {
  44. return utf_to_utf<CharOut, CharIn>(str, util::str_end(str), how);
  45. }
  46. /// Convert a Unicode string \a str other Unicode encoding
  47. template<typename CharOut, typename CharIn>
  48. std::basic_string<CharOut> utf_to_utf(const std::basic_string<CharIn>& str, method_type how = default_method)
  49. {
  50. return utf_to_utf<CharOut, CharIn>(str.c_str(), str.c_str() + str.size(), how);
  51. }
  52. /// @}
  53. }}} // namespace boost::locale::conv
  54. #ifdef BOOST_MSVC
  55. # pragma warning(pop)
  56. #endif
  57. #endif