2 // Copyright (c) 2012 Artyom Beilis (Tonkikh)
4 // Distributed under the Boost Software License, Version 1.0. (See
5 // accompanying file LICENSE or copy at
6 // http://www.boost.org/LICENSE_1_0.txt)
8 #ifndef BOOST_NOWIDE_UTF_CONVERT_HPP_INCLUDED
9 #define BOOST_NOWIDE_UTF_CONVERT_HPP_INCLUDED
11 #include <boost/nowide/replacement.hpp>
12 #include <boost/nowide/utf/utf.hpp>
20 /// Convert a buffer of UTF sequences in the range [source_begin, source_end)
21 /// from \tparam CharIn to \tparam CharOut to the output \a buffer of size \a buffer_size.
23 /// \return original buffer containing the NULL terminated string or NULL
25 /// If there is not enough room in the buffer NULL is returned, and the content of the buffer is undefined.
26 /// Any illegal sequences are replaced with the replacement character, see #BOOST_NOWIDE_REPLACEMENT_CHARACTER
28 template<typename CharOut, typename CharIn>
30 convert_buffer(CharOut* buffer, size_t buffer_size, const CharIn* source_begin, const CharIn* source_end)
36 while(source_begin != source_end)
38 code_point c = utf_traits<CharIn>::decode(source_begin, source_end);
39 if(c == illegal || c == incomplete)
41 c = BOOST_NOWIDE_REPLACEMENT_CHARACTER;
43 size_t width = utf_traits<CharOut>::width(c);
44 if(buffer_size < width)
49 buffer = utf_traits<CharOut>::encode(c, buffer);
57 /// Convert the UTF sequences in range [begin, end) from \tparam CharIn to \tparam CharOut
58 /// and return it as a string
60 /// Any illegal sequences are replaced with the replacement character, see #BOOST_NOWIDE_REPLACEMENT_CHARACTER
62 template<typename CharOut, typename CharIn>
63 std::basic_string<CharOut> convert_string(const CharIn* begin, const CharIn* end)
65 std::basic_string<CharOut> result;
66 result.reserve(end - begin);
67 using inserter_type = std::back_insert_iterator<std::basic_string<CharOut>>;
68 inserter_type inserter(result);
72 c = utf_traits<CharIn>::decode(begin, end);
73 if(c == illegal || c == incomplete)
75 c = BOOST_NOWIDE_REPLACEMENT_CHARACTER;
77 utf_traits<CharOut>::encode(c, inserter);
82 /// Return the length of the given string in code units.
83 /// That is the number of elements of type Char until the first NULL character
84 /// Equivalent to `std::strlen(s)` but can handle wide-strings
85 template<typename Char>
86 size_t strlen(const Char* s)