encoding_utf.hpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See
  5. // accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. #ifndef BOOST_LOCALE_ENCODING_UTF_HPP_INCLUDED
  9. #define BOOST_LOCALE_ENCODING_UTF_HPP_INCLUDED
  10. #include <boost/locale/utf.hpp>
  11. #include <boost/locale/encoding_errors.hpp>
  12. #include <iterator>
  13. #ifdef BOOST_MSVC
  14. # pragma warning(push)
  15. # pragma warning(disable : 4275 4251 4231 4660)
  16. #endif
  17. namespace boost {
  18. namespace locale {
  19. namespace conv {
  20. ///
  21. /// \addtogroup codepage
  22. ///
  23. /// @{
  24. ///
  25. /// Convert a Unicode text in range [begin,end) to other Unicode encoding
  26. ///
  27. template<typename CharOut,typename CharIn>
  28. std::basic_string<CharOut>
  29. utf_to_utf(CharIn const *begin,CharIn const *end,method_type how = default_method)
  30. {
  31. std::basic_string<CharOut> result;
  32. result.reserve(end-begin);
  33. typedef std::back_insert_iterator<std::basic_string<CharOut> > inserter_type;
  34. inserter_type inserter(result);
  35. utf::code_point c;
  36. while(begin!=end) {
  37. c=utf::utf_traits<CharIn>::template decode<CharIn const *>(begin,end);
  38. if(c==utf::illegal || c==utf::incomplete) {
  39. if(how==stop)
  40. throw conversion_error();
  41. }
  42. else {
  43. utf::utf_traits<CharOut>::template encode<inserter_type>(c,inserter);
  44. }
  45. }
  46. return result;
  47. }
  48. ///
  49. /// Convert a Unicode NUL terminated string \a str other Unicode encoding
  50. ///
  51. template<typename CharOut,typename CharIn>
  52. std::basic_string<CharOut>
  53. utf_to_utf(CharIn const *str,method_type how = default_method)
  54. {
  55. CharIn const *end = str;
  56. while(*end)
  57. end++;
  58. return utf_to_utf<CharOut,CharIn>(str,end,how);
  59. }
  60. ///
  61. /// Convert a Unicode string \a str other Unicode encoding
  62. ///
  63. template<typename CharOut,typename CharIn>
  64. std::basic_string<CharOut>
  65. utf_to_utf(std::basic_string<CharIn> const &str,method_type how = default_method)
  66. {
  67. return utf_to_utf<CharOut,CharIn>(str.c_str(),str.c_str()+str.size(),how);
  68. }
  69. /// @}
  70. } // conv
  71. } // locale
  72. } // boost
  73. #ifdef BOOST_MSVC
  74. #pragma warning(pop)
  75. #endif
  76. #endif
  77. // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4