1 <section xmlns="http://docbook.org/ns/docbook" version="5.0"
2 xml:id="std.localization.facet.codecvt" xreflabel="codecvt">
3 <?dbhtml filename="codecvt.html"?>
5 <info><title>codecvt</title>
7 <keyword>ISO C++</keyword>
8 <keyword>codecvt</keyword>
15 The standard class codecvt attempts to address conversions between
16 different character encoding schemes. In particular, the standard
17 attempts to detail conversions between the implementation-defined wide
18 characters (hereafter referred to as <type>wchar_t</type>) and the standard
19 type <type>char</type> that is so beloved in classic <quote>C</quote>
20 (which can now be referred to as narrow characters.) This document attempts
21 to describe how the GNU libstdc++ implementation deals with the conversion
22 between wide and narrow characters, and also presents a framework for dealing
23 with the huge number of other encodings that iconv can convert,
24 including Unicode and UTF8. Design issues and requirements are
25 addressed, and examples of correct usage for both the required
26 specializations for wide and narrow characters and the
27 implementation-provided extended functionality are given.
30 <section xml:id="facet.codecvt.req"><info><title>Requirements</title></info>
34 Around page 425 of the C++ Standard, this charming heading comes into view:
39 22.2.1.5 - Template class codecvt
44 The text around the codecvt definition gives some clues:
50 -1- The class <code>codecvt<internT,externT,stateT></code> is for use
51 when converting from one codeset to another, such as from wide characters
52 to multibyte characters, between wide character encodings such as
59 Hmm. So, in some unspecified way, Unicode encodings and
60 translations between other character sets should be handled by this
67 -2- The <type>stateT</type> argument selects the pair of codesets being mapped between.
73 Ah ha! Another clue...
79 -3- The instantiations required in the Table 51 (lib.locale.category), namely
80 <classname>codecvt<wchar_t,char,mbstate_t></classname> and
81 <classname>codecvt<char,char,mbstate_t></classname>, convert the
82 implementation-defined native character set.
83 <classname>codecvt<char,char,mbstate_t></classname> implements a
84 degenerate conversion; it does not convert at all.
85 <classname>codecvt<wchar_t,char,mbstate_t></classname> converts between
86 the native character sets for tiny and wide characters. Instantiations on
87 <type>mbstate_t</type> perform conversion between encodings known to the library
88 implementor. Other encodings can be converted by specializing on a
89 user-defined <type>stateT</type> type. The <type>stateT</type> object can
90 contain any state that is useful to communicate to or from the specialized
91 <function>do_convert</function> member.
97 At this point, a couple points become clear:
101 One: The standard clearly implies that attempts to add non-required
102 (yet useful and widely used) conversions need to do so through the
103 third template parameter, <type>stateT</type>.</para>
106 Two: The required conversions, by specifying <type>mbstate_t</type> as the
107 third template parameter, imply an implementation strategy that is mostly
108 (or wholly) based on the underlying C library, and the functions
109 <function>mcsrtombs</function> and <function>wcsrtombs</function> in
113 <section xml:id="facet.codecvt.design"><info><title>Design</title></info>
116 <section xml:id="codecvt.design.wchar_t_size"><info><title><type>wchar_t</type> Size</title></info>
120 The simple implementation detail of <type>wchar_t</type>'s size seems to
121 repeatedly confound people. Many systems use a two byte,
122 unsigned integral type to represent wide characters, and use an
123 internal encoding of Unicode or UCS2. (See AIX, Microsoft NT,
124 Java, others.) Other systems, use a four byte, unsigned integral
125 type to represent wide characters, and use an internal encoding
126 of UCS4. (GNU/Linux systems using glibc, in particular.) The C
127 programming language (and thus C++) does not specify a specific
128 size for the type <type>wchar_t</type>.
132 Thus, portable C++ code cannot assume a byte size (or endianness) either.
136 <section xml:id="codecvt.design.unicode"><info><title>Support for Unicode</title></info>
139 Probably the most frequently asked question about code conversion
140 is: "So dudes, what's the deal with Unicode strings?"
141 The dude part is optional, but apparently the usefulness of
142 Unicode strings is pretty widely appreciated. The Unicode character
143 set (and useful encodings like UTF-8, UCS-4, ISO 8859-10,
144 etc etc etc) were not mentioned in the first C++ standard. (The 2011
145 standard added support for string literals with different encodings
146 and some library facilities for converting between encodings, but the
147 notes below have not been updated to reflect that.)
151 A couple of comments:
155 The thought that all one needs to convert between two arbitrary
156 codesets is two types and some kind of state argument is
157 unfortunate. In particular, encodings may be stateless. The naming
158 of the third parameter as <type>stateT</type> is unfortunate, as what is
159 really needed is some kind of generalized type that accounts for the
160 issues that abstract encodings will need. The minimum information
161 that is required includes:
167 Identifiers for each of the codesets involved in the
168 conversion. For example, using the iconv family of functions
169 from the Single Unix Specification (what used to be called
170 X/Open) hosted on the GNU/Linux operating system allows
171 bi-directional mapping between far more than the following
172 tantalizing possibilities:
176 (An edited list taken from <code>`iconv --list`</code> on a
177 Red Hat 6.2/Intel system:
182 8859_1, 8859_9, 10646-1:1993, 10646-1:1993/UCS4, ARABIC, ARABIC7,
183 ASCII, EUC-CN, EUC-JP, EUC-KR, EUC-TW, GREEK-CCIcode, GREEK, GREEK7-OLD,
184 GREEK7, GREEK8, HEBREW, ISO-8859-1, ISO-8859-2, ISO-8859-3,
185 ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8,
186 ISO-8859-9, ISO-8859-10, ISO-8859-11, ISO-8859-13, ISO-8859-14,
187 ISO-8859-15, ISO-10646, ISO-10646/UCS2, ISO-10646/UCS4,
188 ISO-10646/UTF-8, ISO-10646/UTF8, SHIFT-JIS, SHIFT_JIS, UCS-2, UCS-4,
189 UCS2, UCS4, UNICODE, UNICODEBIG, UNICODELIcodeLE, US-ASCII, US, UTF-8,
190 UTF-16, UTF8, UTF16).
195 For iconv-based implementations, string literals for each of the
196 encodings (i.e. "UCS-2" and "UTF-8") are necessary,
198 non-iconv implementations a table of enumerated values or some other
199 mechanism may be required.
204 Maximum length of the identifying string literal.
208 Some encodings require explicit endian-ness. As such, some kind
209 of endian marker or other byte-order marker will be necessary. See
210 "Footnotes for C/C++ developers" in Haible for more information on
211 UCS-2/Unicode endian issues. (Summary: big endian seems most likely,
212 however implementations, most notably Microsoft, vary.)
216 Types representing the conversion state, for conversions involving
217 the machinery in the "C" library, or the conversion descriptor, for
218 conversions using iconv (such as the type iconv_t.) Note that the
219 conversion descriptor encodes more information than a simple encoding
224 Conversion descriptors for both directions of encoding. (i.e., both
225 UCS-2 to UTF-8 and UTF-8 to UCS-2.)
229 Something to indicate if the conversion requested if valid.
233 Something to represent if the conversion descriptors are valid.
237 Some way to enforce strict type checking on the internal and
238 external types. As part of this, the size of the internal and
239 external types will need to be known.
244 <section xml:id="codecvt.design.issues"><info><title>Other Issues</title></info>
247 In addition, multi-threaded and multi-locale environments also impact
248 the design and requirements for code conversions. In particular, they
249 affect the required specialization
250 <classname>codecvt<wchar_t, char, mbstate_t></classname>
251 when implemented using standard "C" functions.
255 Three problems arise, one big, one of medium importance, and one small.
259 First, the small: <function>mcsrtombs</function> and
260 <function>wcsrtombs</function> may not be multithread-safe
261 on all systems required by the GNU tools. For GNU/Linux and glibc,
262 this is not an issue.
266 Of medium concern, in the grand scope of things, is that the functions
267 used to implement this specialization work on null-terminated
268 strings. Buffers, especially file buffers, may not be null-terminated,
269 thus giving conversions that end prematurely or are otherwise
274 The last, and fundamental problem, is the assumption of a global
275 locale for all the "C" functions referenced above. For something like
276 C++ iostreams (where codecvt is explicitly used) the notion of
277 multiple locales is fundamental. In practice, most users may not run
278 into this limitation. However, as a quality of implementation issue,
279 the GNU C++ library would like to offer a solution that allows
280 multiple locales and or simultaneous usage with computationally
281 correct results. In short, libstdc++ is trying to offer, as an
282 option, a high-quality implementation, damn the additional complexity!
286 For the required specialization
287 <classname>codecvt<wchar_t, char, mbstate_t></classname>,
288 conversions are made between the internal character set (always UCS4
289 on GNU/Linux) and whatever the currently selected locale for the
290 LC_CTYPE category implements.
297 <section xml:id="facet.codecvt.impl"><info><title>Implementation</title></info>
301 The two required specializations are implemented as follows:
306 codecvt<char, char, mbstate_t>
310 This is a degenerate (i.e., does nothing) specialization. Implementing
311 this was a piece of cake.
316 codecvt<char, wchar_t, mbstate_t>
321 This specialization, by specifying all the template parameters, pretty
322 much ties the hands of implementors. As such, the implementation is
323 straightforward, involving <function>mcsrtombs</function> for the conversions
324 between <type>char</type> to <type>wchar_t</type> and
325 <function>wcsrtombs</function> for conversions between <type>wchar_t</type>
326 and <type>char</type>.
330 Neither of these two required specializations deals with Unicode
331 characters. As such, libstdc++ implements a partial specialization
332 of the <type>codecvt</type> class with an iconv wrapper class,
333 <classname>encoding_state</classname> as the third template parameter.
337 This implementation should be standards conformant. First of all, the
338 standard explicitly points out that instantiations on the third
339 template parameter, <type>stateT</type>, are the proper way to implement
340 non-required conversions. Second of all, the standard says (in Chapter
341 17) that partial specializations of required classes are A-OK. Third
342 of all, the requirements for the <type>stateT</type> type elsewhere in the
343 standard (see 21.1.2 traits typedefs) only indicate that this type be copy
348 As such, the type <type>encoding_state</type> is defined as a non-templatized,
349 POD type to be used as the third type of a <type>codecvt</type> instantiation.
350 This type is just a wrapper class for iconv, and provides an easy interface
351 to iconv functionality.
355 There are two constructors for <type>encoding_state</type>:
360 encoding_state() : __in_desc(0), __out_desc(0)
364 This default constructor sets the internal encoding to some default
365 (currently UCS4) and the external encoding to whatever is returned by
366 <code>nl_langinfo(CODESET)</code>.
371 encoding_state(const char* __int, const char* __ext)
376 This constructor takes as parameters string literals that indicate the
377 desired internal and external encoding. There are no defaults for
382 One of the issues with iconv is that the string literals identifying
383 conversions are not standardized. Because of this, the thought of
384 mandating and/or enforcing some set of pre-determined valid
385 identifiers seems iffy: thus, a more practical (and non-migraine
386 inducing) strategy was implemented: end-users can specify any string
387 (subject to a pre-determined length qualifier, currently 32 bytes) for
388 encodings. It is up to the user to make sure that these strings are
389 valid on the target system.
399 Strangely enough, this member function attempts to open conversion
400 descriptors for a given encoding_state object. If the conversion
401 descriptors are not valid, the conversion descriptors returned will
402 not be valid and the resulting calls to the codecvt conversion
403 functions will return error.
414 Provides a way to see if the given <type>encoding_state</type> object has been
415 properly initialized. If the string literals describing the desired
416 internal and external encoding are not valid, initialization will
417 fail, and this will return false. If the internal and external
418 encodings are valid, but <function>iconv_open</function> could not allocate
419 conversion descriptors, this will also return false. Otherwise, the object is
420 ready to convert and will return true.
425 encoding_state(const encoding_state&)
430 As iconv allocates memory and sets up conversion descriptors, the copy
431 constructor can only copy the member data pertaining to the internal
432 and external code conversions, and not the conversion descriptors
437 Definitions for all the required codecvt member functions are provided
438 for this specialization, and usage of <code>codecvt<<replaceable>internal
439 character type</replaceable>, <replaceable>external character type</replaceable>, <replaceable>encoding_state</replaceable>></code> is consistent with other
445 <section xml:id="facet.codecvt.use"><info><title>Use</title></info>
447 <para>A conversion involving a string literal.</para>
450 typedef codecvt_base::result result;
451 typedef unsigned short unicode_t;
452 typedef unicode_t int_type;
453 typedef char ext_type;
454 typedef encoding_state state_type;
455 typedef codecvt<int_type, ext_type, state_type> unicode_codecvt;
457 const ext_type* e_lit = "black pearl jasmine tea";
458 int size = strlen(e_lit);
459 int_type i_lit_base[24] =
460 { 25088, 27648, 24832, 25344, 27392, 8192, 28672, 25856, 24832, 29184,
461 27648, 8192, 27136, 24832, 29440, 27904, 26880, 28160, 25856, 8192, 29696,
464 const int_type* i_lit = i_lit_base;
465 const ext_type* efrom_next;
466 const int_type* ifrom_next;
467 ext_type* e_arr = new ext_type[size + 1];
469 int_type* i_arr = new int_type[size + 1];
472 // construct a locale object with the specialized facet.
473 locale loc(locale::classic(), new unicode_codecvt);
474 // sanity check the constructed locale has the specialized facet.
475 VERIFY( has_facet<unicode_codecvt>(loc) );
476 const unicode_codecvt& cvt = use_facet<unicode_codecvt>(loc);
477 // convert between const char* and unicode strings
478 unicode_codecvt::state_type state01("UNICODE", "ISO_8859-1");
479 initialize_state(state01);
480 result r1 = cvt.in(state01, e_lit, e_lit + size, efrom_next,
481 i_arr, i_arr + size, ito_next);
482 VERIFY( r1 == codecvt_base::ok );
483 VERIFY( !int_traits::compare(i_arr, i_lit, size) );
484 VERIFY( efrom_next == e_lit + size );
485 VERIFY( ito_next == i_arr + size );
490 <section xml:id="facet.codecvt.future"><info><title>Future</title></info>
495 a. things that are sketchy, or remain unimplemented:
496 do_encoding, max_length and length member functions
497 are only weakly implemented. I have no idea how to do
498 this correctly, and in a generic manner. Nathan?
504 b. conversions involving <type>std::string</type>
508 how should operators != and == work for string of
509 different/same encoding?
513 what is equal? A byte by byte comparison or an
514 encoding then byte comparison?
518 conversions between narrow, wide, and unicode strings
523 c. conversions involving std::filebuf and std::ostream
527 how to initialize the state object in a
528 standards-conformant manner?
532 how to synchronize the "C" and "C++"
533 conversion information?
537 wchar_t/char internal buffers and conversions between
538 internal/external buffers?
546 <bibliography xml:id="facet.codecvt.biblio"><info><title>Bibliography</title></info>
553 <author><personname><surname>McGrath</surname><firstname>Roland</firstname></personname></author>
554 <author><personname><surname>Drepper</surname><firstname>Ulrich</firstname></personname></author>
560 Chapters 6 Character Set Handling and 7 Locales and Internationalization
568 <author><personname><surname>Drepper</surname><firstname>Ulrich</firstname></personname></author>
577 ISO/IEC 14882:1998 Programming languages - C++
587 ISO/IEC 9899:1999 Programming languages - C
597 <link xmlns:xlink="http://www.w3.org/1999/xlink"
598 xlink:href="https://pubs.opengroup.org/onlinepubs/9699919799/">
599 System Interface Definitions, Issue 7 (IEEE Std. 1003.1-2008)
606 The Open Group/The Institute of Electrical and Electronics
614 The C++ Programming Language, Special Edition
616 <author><personname><surname>Stroustrup</surname><firstname>Bjarne</firstname></personname></author>
619 <holder>Addison Wesley, Inc.</holder>
621 <pagenums>Appendix D</pagenums>
632 Standard C++ IOStreams and Locales
635 Advanced Programmer's Guide and Reference
637 <author><personname><surname>Langer</surname><firstname>Angelika</firstname></personname></author>
638 <author><personname><surname>Kreft</surname><firstname>Klaus</firstname></personname></author>
641 <holder>Addison Wesley Longman, Inc.</holder>
645 Addison Wesley Longman
652 <link xmlns:xlink="http://www.w3.org/1999/xlink"
653 xlink:href="http://www.lysator.liu.se/c/na1.html">
654 A brief description of Normative Addendum 1
658 <author><personname><surname>Feather</surname><firstname>Clive</firstname></personname></author>
659 <pagenums>Extended Character Sets</pagenums>
664 <link xmlns:xlink="http://www.w3.org/1999/xlink"
665 xlink:href="https://tldp.org/HOWTO/Unicode-HOWTO.html">
670 <author><personname><surname>Haible</surname><firstname>Bruno</firstname></personname></author>
675 <link xmlns:xlink="http://www.w3.org/1999/xlink"
676 xlink:href="https://www.cl.cam.ac.uk/~mgk25/unicode.html">
677 UTF-8 and Unicode FAQ for Unix/Linux
682 <author><personname><surname>Khun</surname><firstname>Markus</firstname></personname></author>