Boost.Locale
|
Boost.Locale provides to_utf, from_utf and utf_to_utf functions in the boost::locale::conv
namespace. They are simple and convenient functions to convert a string to and from UTF-8/16/32 strings and strings using other encodings.
For example:
This function may use an explicit encoding name like "Latin1" or "ISO-8859-8", or use std::locale as a parameter to fetch this information from it. It also receives a policy parameter that tells it how to behave if the conversion can't be performed (i.e. an illegal or unsupported character is found). By default this function skips all illegal characters and tries to do the best it can, however, it is possible ask it to throw a conversion_error exception by passing the stop
flag to it:
Boost.Locale provides stream codepage conversion facets based on the std::codecvt
facet. This allows conversion between wide-character encodings and 8-bit encodings like UTF-8, ISO-8859 or Shift-JIS.
Most of compilers provide such facets, but:
he_IL.CP1255
locale even when the he_IL
locale is available.Thus Boost.Locale provides an option to generate code-page conversion facets for use with Boost.Iostreams filters or std::wfstream
. For example:
Would create a file hello.txt
encoded as UTF-8 with "שלום!" (shalom) in it.
You can use the std::codecvt
facet directly, but this is quite tricky and requires accurate buffer and error management.
You can use the boost::iostreams::code_converter
class for stream-oriented conversions between the wide-character set and narrow locale character set.
This is a sample program that converts wide to narrow characters for an arbitrary stream:
The Standard does not provide any information about std::mbstate_t
that could be used to save intermediate code-page conversion states. It leaves the definition up to the compiler implementation, making it impossible to reimplement std::codecvt<wchar_t,char,mbstate_t>
for stateful encodings. Thus, Boost.Locale's codecvt
facet implementation may be used with stateless encodings like UTF-8, ISO-8859, and Shift-JIS, but not with stateful encodings like UTF-7 or SCSU.
Recommendation: Prefer the Unicode UTF-8 encoding for char
based strings and files in your application.
The implementation of codecvt for single byte encodings like ISO-8859-X and for UTF-8 is very efficient and would allow fast conversion of the content, however its performance may be sub-optimal for double-width encodings like Shift-JIS, due to the stateless problem described above.