Update.
[glibc.git] / manual / charset.texi
blobbae29102361de9ce8592a901049efc35460c8442
1 @node Character Set Handling, Locales, String and Array Utilities, Top
2 @c %MENU% Support for extended character sets
3 @chapter Character Set Handling
5 @ifnottex
6 @macro cal{text}
7 \text\
8 @end macro
9 @end ifnottex
11 Character sets used in the early days of computing had only six, seven,
12 or eight bits for each character: there was never a case where more than
13 eight bits (one byte) were used to represent a single character.  The
14 limitations of this approach became more apparent as more people
15 grappled with non-Roman character sets, where not all the characters
16 that make up a language's character set can be represented by @math{2^8}
17 choices.  This chapter shows the functionality that was added to the C
18 library to support multiple character sets.
20 @menu
21 * Extended Char Intro::              Introduction to Extended Characters.
22 * Charset Function Overview::        Overview about Character Handling
23                                       Functions.
24 * Restartable multibyte conversion:: Restartable multibyte conversion
25                                       Functions.
26 * Non-reentrant Conversion::         Non-reentrant Conversion Function.
27 * Generic Charset Conversion::       Generic Charset Conversion.
28 @end menu
31 @node Extended Char Intro
32 @section Introduction to Extended Characters
34 A variety of solutions is available to overcome the differences between
35 character sets with a 1:1 relation between bytes and characters and
36 character sets with ratios of 2:1 or 4:1.  The remainder of this
37 section gives a few examples to help understand the design decisions
38 made while developing the functionality of the @w{C library}.
40 @cindex internal representation
41 A distinction we have to make right away is between internal and
42 external representation.  @dfn{Internal representation} means the
43 representation used by a program while keeping the text in memory.
44 External representations are used when text is stored or transmitted
45 through some communication channel.  Examples of external
46 representations include files waiting in a directory to be
47 read and parsed.
49 Traditionally there has been no difference between the two representations.
50 It was equally comfortable and useful to use the same single-byte
51 representation internally and externally.  This comfort level decreases
52 with more and larger character sets.
54 One of the problems to overcome with the internal representation is
55 handling text that is externally encoded using different character
56 sets.  Assume a program that reads two texts and compares them using
57 some metric.  The comparison can be usefully done only if the texts are
58 internally kept in a common format.
60 @cindex wide character
61 For such a common format (@math{=} character set) eight bits are certainly
62 no longer enough.  So the smallest entity will have to grow: @dfn{wide
63 characters} will now be used.  Instead of one byte per character, two or
64 four will be used instead.  (Three are not good to address in memory and
65 more than four bytes seem not to be necessary).
67 @cindex Unicode
68 @cindex ISO 10646
69 As shown in some other part of this manual,
70 @c !!! Ahem, wide char string functions are not yet covered -- drepper
71 a completely new family has been created of functions that can handle wide
72 character texts in memory.  The most commonly used character sets for such
73 internal wide character representations are Unicode and @w{ISO 10646}
74 (also known as UCS for Universal Character Set).  Unicode was originally
75 planned as a 16-bit character set; whereas, @w{ISO 10646} was designed to
76 be a 31-bit large code space.  The two standards are practically identical.
77 They have the same character repertoire and code table, but Unicode specifies
78 added semantics.  At the moment, only characters in the first @code{0x10000}
79 code positions (the so-called Basic Multilingual Plane, BMP) have been
80 assigned, but the assignment of more specialized characters outside this
81 16-bit space is already in progress.  A number of encodings have been
82 defined for Unicode and @w{ISO 10646} characters:
83 @cindex UCS-2
84 @cindex UCS-4
85 @cindex UTF-8
86 @cindex UTF-16
87 UCS-2 is a 16-bit word that can only represent characters
88 from the BMP, UCS-4 is a 32-bit word than can represent any Unicode
89 and @w{ISO 10646} character, UTF-8 is an ASCII compatible encoding where
90 ASCII characters are represented by ASCII bytes and non-ASCII characters
91 by sequences of 2-6 non-ASCII bytes, and finally UTF-16 is an extension
92 of UCS-2 in which pairs of certain UCS-2 words can be used to encode
93 non-BMP characters up to @code{0x10ffff}.
95 To represent wide characters the @code{char} type is not suitable.  For
96 this reason the @w{ISO C} standard introduces a new type that is
97 designed to keep one character of a wide character string.  To maintain
98 the similarity there is also a type corresponding to @code{int} for
99 those functions that take a single wide character.
101 @comment stddef.h
102 @comment ISO
103 @deftp {Data type} wchar_t
104 This data type is used as the base type for wide character strings.
105 In other words, arrays of objects of this type are the equivalent of 
106 @code{char[]} for multibyte character strings.  The type is defined in 
107 @file{stddef.h}.
109 The @w{ISO C90} standard, where @code{wchar_t} was introduced, does not
110 say anything specific about the representation.  It only requires that
111 this type is capable of storing all elements of the basic character set.
112 Therefore it would be legitimate to define @code{wchar_t} as @code{char},
113 which might make sense for embedded systems.
115 But for GNU systems @code{wchar_t} is always 32 bits wide and, therefore,
116 capable of representing all UCS-4 values and, therefore, covering all of
117 @w{ISO 10646}.  Some Unix systems define @code{wchar_t} as a 16-bit type
118 and thereby follow Unicode very strictly.  This definition is perfectly
119 fine with the standard, but it also means that to represent all
120 characters from Unicode and @w{ISO 10646} one has to use UTF-16 surrogate
121 characters, which is in fact a multi-wide-character encoding.  But
122 resorting to multi-wide-character encoding contradicts the purpose of the
123 @code{wchar_t} type.
124 @end deftp
126 @comment wchar.h
127 @comment ISO
128 @deftp {Data type} wint_t
129 @code{wint_t} is a data type used for parameters and variables that
130 contain a single wide character.  As the name suggests this type is the
131 equivalent of @code{int} when using the normal @code{char} strings.  The
132 types @code{wchar_t} and @code{wint_t} often have the same
133 representation if their size is 32 bits wide but if @code{wchar_t} is
134 defined as @code{char} the type @code{wint_t} must be defined as
135 @code{int} due to the parameter promotion.
137 @pindex wchar.h
138 This type is defined in @file{wchar.h} and was introduced in
139 @w{Amendment 1} to @w{ISO C90}.
140 @end deftp
142 As there are for the @code{char} data type macros are available for
143 specifying the minimum and maximum value representable in an object of
144 type @code{wchar_t}.
146 @comment wchar.h
147 @comment ISO
148 @deftypevr Macro wint_t WCHAR_MIN
149 The macro @code{WCHAR_MIN} evaluates to the minimum value representable
150 by an object of type @code{wint_t}.
152 This macro was introduced in @w{Amendment 1} to @w{ISO C90}.
153 @end deftypevr
155 @comment wchar.h
156 @comment ISO
157 @deftypevr Macro wint_t WCHAR_MAX
158 The macro @code{WCHAR_MAX} evaluates to the maximum value representable
159 by an object of type @code{wint_t}.
161 This macro was introduced in @w{Amendment 1} to @w{ISO C90}.
162 @end deftypevr
164 Another special wide character value is the equivalent to @code{EOF}.
166 @comment wchar.h
167 @comment ISO
168 @deftypevr Macro wint_t WEOF
169 The macro @code{WEOF} evaluates to a constant expression of type
170 @code{wint_t} whose value is different from any member of the extended
171 character set.
173 @code{WEOF} need not be the same value as @code{EOF} and unlike
174 @code{EOF} it also need @emph{not} be negative.  In other words, sloppy 
175 code like
177 @smallexample
179   int c;
180   ...
181   while ((c = getc (fp)) < 0)
182     ...
184 @end smallexample
186 @noindent
187 has to be rewritten to use @code{WEOF} explicitly when wide characters
188 are used:
190 @smallexample
192   wint_t c;
193   ...
194   while ((c = wgetc (fp)) != WEOF)
195     ...
197 @end smallexample
199 @pindex wchar.h
200 This macro was introduced in @w{Amendment 1} to @w{ISO C90} and is
201 defined in @file{wchar.h}.
202 @end deftypevr
205 These internal representations present problems when it comes to storing
206 and transmittal.  Because each single wide character consists of more
207 than one byte, they are effected by byte-ordering.  Thus, machines with
208 different endianesses would see different values when accessing the same
209 data.  This byte ordering concern also applies for communication protocols
210 that are all byte-based and, thereforet require that the sender has to
211 decide about splitting the wide character in bytes.  A last (but not least
212 important) point is that wide characters often require more storage space
213 than a customized byte-oriented character set.
215 @cindex multibyte character
216 @cindex EBCDIC
217    For all the above reasons, an external encoding that is different
218 from the internal encoding is often used if the latter is UCS-2 or UCS-4.
219 The external encoding is byte-based and can be chosen appropriately for
220 the environment and for the texts to be handled.  A variety of different
221 character sets can be used for this external encoding (information that
222 will not be exhaustively presented here--instead, a description of the
223 major groups will suffice).  All of the ASCII-based character sets
224 [_bkoz_: do you mean Roman character sets? If not, what do you mean
225 here?] fulfill one requirement: they are "filesystem safe."  This means
226 that the character @code{'/'} is used in the encoding @emph{only} to
227 represent itself.  Things are a bit different for character sets like
228 EBCDIC (Extended Binary Coded Decimal Interchange Code, a character set
229 family used by IBM), but if the operation system does not understand
230 EBCDIC directly the parameters-to-system calls have to be converted first
231 anyhow.
233 @itemize @bullet
234 @item 
235 The simplest character sets are single-byte character sets.  There can 
236 be only up to 256 characters (for @w{8 bit} character sets), which is 
237 not sufficient to cover all languages but might be sufficient to handle 
238 a specific text.  Handling of a @w{8 bit} character sets is simple.  This 
239 is not true for other kinds presented later, and therefore, the 
240 application one uses might require the use of @w{8 bit} character sets.
242 @cindex ISO 2022
243 @item
244 The @w{ISO 2022} standard defines a mechanism for extended character
245 sets where one character @emph{can} be represented by more than one
246 byte.  This is achieved by associating a state with the text.
247 Characters that can be used to change the state can be embedded in the
248 text.  Each byte in the text might have a different interpretation in each
249 state.  The state might even influence whether a given byte stands for a
250 character on its own or whether it has to be combined with some more
251 bytes.
253 @cindex EUC
254 @cindex Shift_JIS
255 @cindex SJIS
256 In most uses of @w{ISO 2022} the defined character sets do not allow
257 state changes that cover more than the next character.  This has the
258 big advantage that whenever one can identify the beginning of the byte
259 sequence of a character one can interpret a text correctly.  Examples of
260 character sets using this policy are the various EUC character sets
261 (used by Sun's operations systems, EUC-JP, EUC-KR, EUC-TW, and EUC-CN)
262 or Shift_JIS (SJIS, a Japanese encoding).
264 But there are also character sets using a state that is valid for more
265 than one character and has to be changed by another byte sequence.
266 Examples for this are ISO-2022-JP, ISO-2022-KR, and ISO-2022-CN.
268 @item
269 @cindex ISO 6937
270 Early attempts to fix 8 bit character sets for other languages using the
271 Roman alphabet lead to character sets like @w{ISO 6937}.  Here bytes
272 representing characters like the acute accent do not produce output
273 themselves: one has to combine them with other characters to get the
274 desired result.  For example, the byte sequence @code{0xc2 0x61}
275 (non-spacing acute accent, followed by lower-case `a') to get the ``small
276 a with  acute'' character.  To get the acute accent character on its own,
277 one has to write @code{0xc2 0x20} (the non-spacing acute followed by a
278 space).
280 Character sets like @w[ISO 6937] are used in some embedded systems such
281 as teletex.
283 @item
284 @cindex UTF-8
285 Instead of converting the Unicode or @w{ISO 10646} text used internally,
286 it is often also sufficient to simply use an encoding different than
287 UCS-2/UCS-4.  The Unicode and @w{ISO 10646} standards even specify such an
288 encoding: UTF-8.  This encoding is able to represent all of @w{ISO
289 10646} 31 bits in a byte string of length one to six.
291 @cindex UTF-7
292 There were a few other attempts to encode @w{ISO 10646} such as UTF-7,
293 but UTF-8 is today the only encoding that should be used.  In fact, with
294 any luck UTF-8 will soon be the only external encoding that has to be
295 supported.  It proves to be universally usable and its only disadvantage
296 is that it favors Roman languages by making the byte string
297 representation of other scripts (Cyrillic, Greek, Asian scripts) longer
298 than necessary if using a specific character set for these scripts.
299 Methods like the Unicode compression scheme can alleviate these
300 problems.
301 @end itemize
303 The question remaining is: how to select the character set or encoding
304 to use.  The answer: you cannot decide about it yourself, it is decided
305 by the developers of the system or the majority of the users.  Since the
306 goal is interoperability one has to use whatever the other people one
307 works with use.  If there are no constraints, the selection is based on
308 the requirements the expected circle of users will have.  In other words,
309 if a project is expected to be used in only, say, Russia it is fine to use
310 KOI8-R or a similar character set.  But if at the same time people from,
311 say, Greece are participating one should use a character set that allows
312 all people to collaborate.
314 The most widely useful solution seems to be: go with the most general
315 character set, namely @w{ISO 10646}.  Use UTF-8 as the external encoding
316 and problems about users not being able to use their own language
317 adequately are a thing of the past.
319 One final comment about the choice of the wide character representation
320 is necessary at this point.  We have said above that the natural choice
321 is using Unicode or @w{ISO 10646}.  This is not required, but at least
322 encouraged, by the @w{ISO C} standard.  The standard defines at least a
323 macro @code{__STDC_ISO_10646__} that is only defined on systems where
324 the @code{wchar_t} type encodes @w{ISO 10646} characters.  If this
325 symbol is not defined one should avoid making assumptions about the wide
326 character representation.  If the programmer uses only the functions
327 provided by the C library to handle wide character strings there should
328 be no compatibility problems with other systems.
330 @node Charset Function Overview
331 @section Overview about Character Handling Functions
333 A Unix @w{C library} contains three different sets of functions in two 
334 families to handle character set conversion.  One of the function families 
335 (the most commonly used) is specified in the @w{ISO C90} standard and, 
336 therefore, is portable even beyond the Unix world.  Unfortunately this 
337 family is the least useful one.  These functions should be avoided 
338 whenever possible, especially when developing libraries (as opposed to 
339 applications). 
341 The second family of functions got introduced in the early Unix standards
342 (XPG2) and is still part of the latest and greatest Unix standard:
343 @w{Unix 98}.  It is also the most powerful and useful set of functions.
344 But we will start with the functions defined in @w{Amendment 1} to
345 @w{ISO C90}.
347 @node Restartable multibyte conversion
348 @section Restartable Multibyte Conversion Functions
350 The @w{ISO C} standard defines functions to convert strings from a
351 multibyte representation to wide character strings.  There are a number
352 of peculiarities:
354 @itemize @bullet
355 @item
356 The character set assumed for the multibyte encoding is not specified
357 as an argument to the functions.  Instead the character set specified by
358 the @code{LC_CTYPE} category of the current locale is used; see
359 @ref{Locale Categories}.
361 @item
362 The functions handling more than one character at a time require NUL
363 terminated strings as the argument (i.e., converting blocks of text
364 does not work unless one can add a NUL byte at an appropriate place). 
365 The GNU C library contains some extensions to the standard that allow
366 specifying a size, but basically they also expect terminated strings.
367 @end itemize
369 Despite these limitations the @w{ISO C} functions can be used in many
370 contexts.  In graphical user interfaces, for instance, it is not
371 uncommon to have functions that require text to be displayed in a wide
372 character string if the text is not simple ASCII.  The text itself might 
373 come from a file with translations and the user should decide about the
374 current locale, which determines the translation and therefore also the
375 external encoding used.  In such a situation (and many others) the
376 functions described here are perfect.  If more freedom while performing
377 the conversion is necessary take a look at the @code{iconv} functions
378 (@pxref{Generic Charset Conversion}).
380 @menu
381 * Selecting the Conversion::     Selecting the conversion and its properties.
382 * Keeping the state::            Representing the state of the conversion.
383 * Converting a Character::       Converting Single Characters.
384 * Converting Strings::           Converting Multibyte and Wide Character
385                                   Strings.
386 * Multibyte Conversion Example:: A Complete Multibyte Conversion Example.
387 @end menu
389 @node Selecting the Conversion
390 @subsection Selecting the conversion and its properties
392 We already said above that the currently selected locale for the
393 @code{LC_CTYPE} category decides about the conversion that is performed
394 by the functions we are about to describe.  Each locale uses its own
395 character set (given as an argument to @code{localedef}) and this is the
396 one assumed as the external multibyte encoding.  The wide character
397 character set always is UCS-4, at least on GNU systems.
399 A characteristic of each multibyte character set is the maximum number
400 of bytes that can be necessary to represent one character.  This
401 information is quite important when writing code that uses the
402 conversion functions (as shown in the examples below).
403 The @w{ISO C} standard defines two macros that provide this information.
406 @comment limits.h
407 @comment ISO
408 @deftypevr Macro int MB_LEN_MAX
409 @code{MB_LEN_MAX} specifies the maximum number of bytes in the multibyte
410 sequence for a single character in any of the supported locales.  It is
411 a compile-time constant and is defined in @file{limits.h}.
412 @pindex limits.h
413 @end deftypevr
415 @comment stdlib.h
416 @comment ISO
417 @deftypevr Macro int MB_CUR_MAX
418 @code{MB_CUR_MAX} expands into a positive integer expression that is the
419 maximum number of bytes in a multibyte character in the current locale.
420 The value is never greater than @code{MB_LEN_MAX}.  Unlike
421 @code{MB_LEN_MAX} this macro need not be a compile-time constant, and in 
422 the GNU C library it is not.
424 @pindex stdlib.h
425 @code{MB_CUR_MAX} is defined in @file{stdlib.h}.
426 @end deftypevr
428 Two different macros are necessary since strictly @w{ISO C90} compilers
429 do not allow variable length array definitions, but still it is desirable
430 to avoid dynamic allocation.  This incomplete piece of code shows the
431 problem:
433 @smallexample
435   char buf[MB_LEN_MAX];
436   ssize_t len = 0;
438   while (! feof (fp))
439     @{
440       fread (&buf[len], 1, MB_CUR_MAX - len, fp);
441       /* @r{... process} buf */
442       len -= used;
443     @}
445 @end smallexample
447 The code in the inner loop is expected to have always enough bytes in
448 the array @var{buf} to convert one multibyte character.  The array
449 @var{buf} has to be sized statically since many compilers do not allow a
450 variable size.  The @code{fread} call makes sure that @code{MB_CUR_MAX} 
451 bytes are always available in @var{buf}.  Note that it isn't
452 a problem if @code{MB_CUR_MAX} is not a compile-time constant.
455 @node Keeping the state
456 @subsection Representing the state of the conversion
458 @cindex stateful
459 In the introduction of this chapter it was said that certain character
460 sets use a @dfn{stateful} encoding.  That is, the encoded values depend 
461 in some way on the previous bytes in the text.
463 Since the conversion functions allow converting a text in more than one
464 step we must have a way to pass this information from one call of the
465 functions to another.
467 @comment wchar.h
468 @comment ISO
469 @deftp {Data type} mbstate_t
470 @cindex shift state
471 A variable of type @code{mbstate_t} can contain all the information
472 about the @dfn{shift state} needed from one call to a conversion
473 function to another.
475 @pindex wchar.h
476 @code{mbstate_t} is defined in @file{wchar.h}.  It was introduced in
477 @w{Amendment 1} to @w{ISO C90}.
478 @end deftp
480 To use objects of type @code{mbstate_t} the programmer has to define such 
481 objects (normally as local variables on the stack) and pass a pointer to 
482 the object to the conversion functions.  This way the conversion function
483 can update the object if the current multibyte character set is stateful.
485 There is no specific function or initializer to put the state object in
486 any specific state.  The rules are that the object should always
487 represent the initial state before the first use, and this is achieved by
488 clearing the whole variable with code such as follows:
490 @smallexample
492   mbstate_t state;
493   memset (&state, '\0', sizeof (state));
494   /* @r{from now on @var{state} can be used.}  */
495   ...
497 @end smallexample
499 When using the conversion functions to generate output it is often
500 necessary to test whether the current state corresponds to the initial
501 state.  This is necessary, for example, to decide whether to emit
502 escape sequences to set the state to the initial state at certain
503 sequence points.  Communication protocols often require this.
505 @comment wchar.h
506 @comment ISO
507 @deftypefun int mbsinit (const mbstate_t *@var{ps})
508 The @code {mbsinit} function determines whether the state object pointed 
509 to by @var{ps} is in the initial state.  If @var{ps} is a null pointer or 
510 the object is in the initial state the return value is nonzero.  Otherwise 
511 it is zero.
513 @pindex wchar.h
514 @code {mbsinit} was introduced in @w{Amendment 1} to @w{ISO C90} and is 
515 declared in @file{wchar.h}.
516 @end deftypefun
518 Code using @code {mbsinit} often looks similar to this:
520 @c Fix the example to explicitly say how to generate the escape sequence
521 @c to restore the initial state.
522 @smallexample
524   mbstate_t state;
525   memset (&state, '\0', sizeof (state));
526   /* @r{Use @var{state}.}  */
527   ...
528   if (! mbsinit (&state))
529     @{
530       /* @r{Emit code to return to initial state.}  */
531       const wchar_t empty[] = L"";
532       const wchar_t *srcp = empty;
533       wcsrtombs (outbuf, &srcp, outbuflen, &state);
534     @}
535   ...
537 @end smallexample
539 The code to emit the escape sequence to get back to the initial state is
540 interesting.  The @code{wcsrtombs} function can be used to determine the
541 necessary output code (@pxref{Converting Strings}).  Please note that on
542 GNU systems it is not necessary to perform this extra action for the
543 conversion from multibyte text to wide character text since the wide
544 character encoding is not stateful.  But there is nothing mentioned in
545 any standard that prohibits making @code{wchar_t} using a stateful
546 encoding.
548 @node Converting a Character
549 @subsection Converting Single Characters
551 The most fundamental of the conversion functions are those dealing with
552 single characters.  Please note that this does not always mean single
553 bytes.  But since there is very often a subset of the multibyte
554 character set that consists of single byte sequences, there are
555 functions to help with converting bytes.  Frequently, ASCII is a subpart 
556 of the multibyte character set.  In such a scenario, each ASCII character 
557 stands for itself, and all other characters have at least a first byte 
558 that is beyond the range @math{0} to @math{127}.
560 @comment wchar.h
561 @comment ISO
562 @deftypefun wint_t btowc (int @var{c})
563 The @code{btowc} function (``byte to wide character'') converts a valid
564 single byte character @var{c} in the initial shift state into the wide
565 character equivalent using the conversion rules from the currently
566 selected locale of the @code{LC_CTYPE} category.
568 If @code{(unsigned char) @var{c}} is no valid single byte multibyte
569 character or if @var{c} is @code{EOF}, the function returns @code{WEOF}.
571 Please note the restriction of @var{c} being tested for validity only in
572 the initial shift state.  No @code{mbstate_t} object is used from
573 which the state information is taken, and the function also does not use
574 any static state.
576 @pindex wchar.h
577 The @code{btowc} function was introduced in @w{Amendment 1} to @w{ISO C90} 
578 and is declared in @file{wchar.h}.
579 @end deftypefun
581 Despite the limitation that the single byte value always is interpreted
582 in the initial state this function is actually useful most of the time.
583 Most characters are either entirely single-byte character sets or they
584 are extension to ASCII.  But then it is possible to write code like this
585 (not that this specific example is very useful):
587 @smallexample
588 wchar_t *
589 itow (unsigned long int val)
591   static wchar_t buf[30];
592   wchar_t *wcp = &buf[29];
593   *wcp = L'\0';
594   while (val != 0)
595     @{
596       *--wcp = btowc ('0' + val % 10);
597       val /= 10;
598     @}
599   if (wcp == &buf[29])
600     *--wcp = L'0';
601   return wcp;
603 @end smallexample
605 Why is it necessary to use such a complicated implementation and not
606 simply cast @code{'0' + val % 10} to a wide character?  The answer is
607 that there is no guarantee that one can perform this kind of arithmetic
608 on the character of the character set used for @code{wchar_t}
609 representation.  In other situations the bytes are not constant at
610 compile time and so the compiler cannot do the work.  In situations like
611 this it is necessary @code{btowc}.
613 @noindent
614 There also is a function for the conversion in the other direction.
616 @comment wchar.h
617 @comment ISO
618 @deftypefun int wctob (wint_t @var{c})
619 The @code{wctob} function (``wide character to byte'') takes as the
620 parameter a valid wide character.  If the multibyte representation for
621 this character in the initial state is exactly one byte long, the return
622 value of this function is this character.  Otherwise the return value is
623 @code{EOF}.
625 @pindex wchar.h
626 @code{wctob} was introduced in @w{Amendment 1} to @w{ISO C90} and
627 is declared in @file{wchar.h}.
628 @end deftypefun
630 There are more general functions to convert single character from
631 multibyte representation to wide characters and vice versa.  These
632 functions pose no limit on the length of the multibyte representation
633 and they also do not require it to be in the initial state.
635 @comment wchar.h
636 @comment ISO
637 @deftypefun size_t mbrtowc (wchar_t *restrict @var{pwc}, const char *restrict @var{s}, size_t @var{n}, mbstate_t *restrict @var{ps})
638 @cindex stateful
639 The @code{mbrtowc} function (``multibyte restartable to wide
640 character'') converts the next multibyte character in the string pointed
641 to by @var{s} into a wide character and stores it in the wide character
642 string pointed to by @var{pwc}.  The conversion is performed according
643 to the locale currently selected for the @code{LC_CTYPE} category.  If
644 the conversion for the character set used in the locale requires a state,
645 the multibyte string is interpreted in the state represented by the
646 object pointed to by @var{ps}.  If @var{ps} is a null pointer, a static,
647 internal state variable used only by the @code{mbrtowc} function is
648 used.
650 If the next multibyte character corresponds to the NUL wide character,
651 the return value of the function is @math{0} and the state object is
652 afterwards in the initial state.  If the next @var{n} or fewer bytes
653 form a correct multibyte character, the return value is the number of
654 bytes starting from @var{s} that form the multibyte character.  The
655 conversion state is updated according to the bytes consumed in the
656 conversion.  In both cases the wide character (either the @code{L'\0'}
657 or the one found in the conversion) is stored in the string pointed to
658 by @var{pwc} if @var{pwc} is not null.
660 If the first @var{n} bytes of the multibyte string possibly form a valid
661 multibyte character but there are more than @var{n} bytes needed to
662 complete it, the return value of the function is @code{(size_t) -2} and
663 no value is stored.  Please note that this can happen even if @var{n}
664 has a value greater than or equal to @code{MB_CUR_MAX} since the input 
665 might contain redundant shift sequences.
667 If the first @code{n} bytes of the multibyte string cannot possibly form
668 a valid multibyte character, no value is stored, the global variable
669 @code{errno} is set to the value @code{EILSEQ}, and the function returns
670 @code{(size_t) -1}.  The conversion state is afterwards undefined.
672 @pindex wchar.h
673 @code{mbrtowc} was introduced in @w{Amendment 1} to @w{ISO C90} and
674 is declared in @file{wchar.h}.
675 @end deftypefun
677 Use of @code{mbrtowc} is straightforward.  A function that copies a
678 multibyte string into a wide character string while at the same time
679 converting all lowercase characters into uppercase could look like this
680 (this is not the final version, just an example; it has no error
681 checking, and sometimes leaks memory):
683 @smallexample
684 wchar_t *
685 mbstouwcs (const char *s)
687   size_t len = strlen (s);
688   wchar_t *result = malloc ((len + 1) * sizeof (wchar_t));
689   wchar_t *wcp = result;
690   wchar_t tmp[1];
691   mbstate_t state;
692   size_t nbytes;
694   memset (&state, '\0', sizeof (state));
695   while ((nbytes = mbrtowc (tmp, s, len, &state)) > 0)
696     @{
697       if (nbytes >= (size_t) -2)
698         /* Invalid input string.  */
699         return NULL;
700       *result++ = towupper (tmp[0]);
701       len -= nbytes;
702       s += nbytes;
703     @}
704   return result;
706 @end smallexample
708 The use of @code{mbrtowc} should be clear.  A single wide character is
709 stored in @code{@var{tmp}[0]}, and the number of consumed bytes is stored
710 in the variable @var{nbytes}.  If the conversion is successful, the 
711 uppercase variant of the wide character is stored in the @var{result} 
712 array and the pointer to the input string and the number of available 
713 bytes is adjusted.
715 The only non-obvious thing about @code{mbrtowc} might be the way memory 
716 is allocated for the result.  The above code uses the fact that there 
717 can never be more wide characters in the converted results than there are
718 bytes in the multibyte input string.  This method yields a pessimistic 
719 guess about the size of the result, and if many wide character strings 
720 have to be constructed this way or if the strings are long, the extra 
721 memory required to be allocated because the input string contains 
722 multibyte characters might be significant.  The allocated memory block can 
723 be resized to the correct size before returning it, but a better solution 
724 might be to allocate just the right amount of space for the result right 
725 away.  Unfortunately there is no function to compute the length of the wide 
726 character string directly from the multibyte string.  There is, however, a 
727 function that does part of the work.
729 @comment wchar.h
730 @comment ISO
731 @deftypefun size_t mbrlen (const char *restrict @var{s}, size_t @var{n}, mbstate_t *@var{ps})
732 The @code{mbrlen} function (``multibyte restartable length'') computes
733 the number of at most @var{n} bytes starting at @var{s}, which form the
734 next valid and complete multibyte character.
736 If the next multibyte character corresponds to the NUL wide character,
737 the return value is @math{0}.  If the next @var{n} bytes form a valid
738 multibyte character, the number of bytes belonging to this multibyte
739 character byte sequence is returned.
741 If the the first @var{n} bytes possibly form a valid multibyte
742 character but the character is incomplete, the return value is 
743 @code{(size_t) -2}.  Otherwise the multibyte character sequence is invalid 
744 and the return value is @code{(size_t) -1}.
746 The multibyte sequence is interpreted in the state represented by the
747 object pointed to by @var{ps}.  If @var{ps} is a null pointer, a state
748 object local to @code{mbrlen} is used.
750 @pindex wchar.h
751 @code{mbrlen} was introduced in @w{Amendment 1} to @w{ISO C90} and
752 is declared in @file{wchar.h}.
753 @end deftypefun
755 The attentive reader now will note that @code{mbrlen} can be implemented 
758 @smallexample
759 mbrtowc (NULL, s, n, ps != NULL ? ps : &internal)
760 @end smallexample
762 This is true and in fact is mentioned in the official specification.
763 How can this function be used to determine the length of the wide
764 character string created from a multibyte character string?  It is not
765 directly usable, but we can define a function @code{mbslen} using it:
767 @smallexample
768 size_t
769 mbslen (const char *s)
771   mbstate_t state;
772   size_t result = 0;
773   size_t nbytes;
774   memset (&state, '\0', sizeof (state));
775   while ((nbytes = mbrlen (s, MB_LEN_MAX, &state)) > 0)
776     @{
777       if (nbytes >= (size_t) -2)
778         /* @r{Something is wrong.}  */
779         return (size_t) -1;
780       s += nbytes;
781       ++result;
782     @}
783   return result;
785 @end smallexample
787 This function simply calls @code{mbrlen} for each multibyte character
788 in the string and counts the number of function calls.  Please note that
789 we here use @code{MB_LEN_MAX} as the size argument in the @code{mbrlen}
790 call.  This is acceptable since a) this value is larger then the length of 
791 the longest multibyte character sequence and b) we know that the string 
792 @var{s} ends with a NUL byte, which cannot be part of any other multibyte 
793 character sequence but the one representing the NUL wide character.  
794 Therefore, the @code{mbrlen} function will never read invalid memory.
796 Now that this function is available (just to make this clear, this
797 function is @emph{not} part of the GNU C library) we can compute the
798 number of wide character required to store the converted multibyte
799 character string @var{s} using
801 @smallexample
802 wcs_bytes = (mbslen (s) + 1) * sizeof (wchar_t);
803 @end smallexample
805 Please note that the @code{mbslen} function is quite inefficient.  The
806 implementation of @code{mbstouwcs} with @code{mbslen} would have to 
807 perform the conversion of the multibyte character input string twice, and 
808 this conversion might be quite expensive.  So it is necessary to think 
809 about the consequences of using the easier but imprecise method before 
810 doing the work twice.
812 @comment wchar.h
813 @comment ISO
814 @deftypefun size_t wcrtomb (char *restrict @var{s}, wchar_t @var{wc}, mbstate_t *restrict @var{ps})
815 The @code{wcrtomb} function (``wide character restartable to
816 multibyte'') converts a single wide character into a multibyte string
817 corresponding to that wide character.
819 If @var{s} is a null pointer, the function resets the state stored in
820 the objects pointed to by @var{ps} (or the internal @code{mbstate_t}
821 object) to the initial state.  This can also be achieved by a call like
822 this:
824 @smallexample
825 wcrtombs (temp_buf, L'\0', ps)
826 @end smallexample
828 @noindent
829 since, if @var{s} is a null pointer, @code{wcrtomb} performs as if it
830 writes into an internal buffer, which is guaranteed to be large enough.
832 If @var{wc} is the NUL wide character, @code{wcrtomb} emits, if
833 necessary, a shift sequence to get the state @var{ps} into the initial
834 state followed by a single NUL byte, which is stored in the string 
835 @var{s}.
837 Otherwise a byte sequence (possibly including shift sequences) is written 
838 into the string @var{s}.  This only happens if @var{wc} is a valid wide 
839 character (i.e., it has a multibyte representation in the character set 
840 selected by locale of the @code{LC_CTYPE} category).  If @var{wc} is no 
841 valid wide character, nothing is stored in the strings @var{s}, 
842 @code{errno} is set to @code{EILSEQ}, the conversion state in @var{ps} 
843 is undefined and the return value is @code{(size_t) -1}.
845 If no error occurred the function returns the number of bytes stored in
846 the string @var{s}.  This includes all bytes representing shift
847 sequences.
849 One word about the interface of the function: there is no parameter
850 specifying the length of the array @var{s}.  Instead the function
851 assumes that there are at least @code{MB_CUR_MAX} bytes available since
852 this is the maximum length of any byte sequence representing a single
853 character.  So the caller has to make sure that there is enough space
854 available, otherwise buffer overruns can occur.
856 @pindex wchar.h
857 @code{wcrtomb} was introduced in @w{Amendment 1} to @w{ISO C90} and is
858 declared in @file{wchar.h}.
859 @end deftypefun
861 Using @code{wcrtomb} is as easy as using @code{mbrtowc}.  The following
862 example appends a wide character string to a multibyte character string.
863 Again, the code is not really useful (or correct), it is simply here to
864 demonstrate the use and some problems.
866 @smallexample
867 char *
868 mbscatwcs (char *s, size_t len, const wchar_t *ws)
870   mbstate_t state;
871   /* @r{Find the end of the existing string.}  */
872   char *wp = strchr (s, '\0');
873   len -= wp - s;
874   memset (&state, '\0', sizeof (state));
875   do
876     @{
877       size_t nbytes;
878       if (len < MB_CUR_LEN)
879         @{
880           /* @r{We cannot guarantee that the next}
881              @r{character fits into the buffer, so}
882              @r{return an error.}  */
883           errno = E2BIG;
884           return NULL;
885         @}
886       nbytes = wcrtomb (wp, *ws, &state);
887       if (nbytes == (size_t) -1)
888         /* @r{Error in the conversion.}  */
889         return NULL;
890       len -= nbytes;
891       wp += nbytes;
892     @}
893   while (*ws++ != L'\0');
894   return s;
896 @end smallexample
898 First the function has to find the end of the string currently in the
899 array @var{s}.  The @code{strchr} call does this very efficiently since a
900 requirement for multibyte character representations is that the NUL byte
901 is never used except to represent itself (and in this context, the end
902 of the string).
904 After initializing the state object the loop is entered where the first
905 task is to make sure there is enough room in the array @var{s}.  We
906 abort if there are not at least @code{MB_CUR_LEN} bytes available.  This
907 is not always optimal but we have no other choice.  We might have less
908 than @code{MB_CUR_LEN} bytes available but the next multibyte character
909 might also be only one byte long.  At the time the @code{wcrtomb} call
910 returns it is too late to decide whether the buffer was large enough.  If 
911 this solution is unsuitable, there is a very slow but more accurate 
912 solution.
914 @smallexample
915   ...
916   if (len < MB_CUR_LEN)
917     @{
918       mbstate_t temp_state;
919       memcpy (&temp_state, &state, sizeof (state));
920       if (wcrtomb (NULL, *ws, &temp_state) > len)
921         @{
922           /* @r{We cannot guarantee that the next}
923              @r{character fits into the buffer, so}
924              @r{return an error.}  */
925           errno = E2BIG;
926           return NULL;
927         @}
928     @}
929   ...
930 @end smallexample
932 Here we perform the conversion that might overflow the buffer so that 
933 we are afterwards in the position to make an exact decision about the 
934 buffer size.  Please note the @code{NULL} argument for the destination 
935 buffer in the new @code{wcrtomb} call; since we are not interested in the 
936 converted text at this point, this is a nice way to express this.  The 
937 most unusual thing about this piece of code certainly is the duplication 
938 of the conversion state object, but if a change of the state is necessary 
939 to emit the next multibyte character, we want to have the same shift state 
940 change performed in the real conversion.  Therefore, we have to preserve 
941 the initial shift state information.
943 There are certainly many more and even better solutions to this problem.
944 This example is only provided for educational purposes.
946 @node Converting Strings
947 @subsection Converting Multibyte and Wide Character Strings
949 The functions described in the previous section only convert a single
950 character at a time.  Most operations to be performed in real-world
951 programs include strings and therefore the @w{ISO C} standard also
952 defines conversions on entire strings.  However, the defined set of
953 functions is quite limited; therefore, the GNU C library contains a few
954 extensions that can help in some important situations.
956 @comment wchar.h
957 @comment ISO
958 @deftypefun size_t mbsrtowcs (wchar_t *restrict @var{dst}, const char **restrict @var{src}, size_t @var{len}, mbstate_t *restrict @var{ps})
959 The @code{mbsrtowcs} function (``multibyte string restartable to wide
960 character string'') converts an NUL-terminated multibyte character
961 string at @code{*@var{src}} into an equivalent wide character string,
962 including the NUL wide character at the end.  The conversion is started
963 using the state information from the object pointed to by @var{ps} or
964 from an internal object of @code{mbsrtowcs} if @var{ps} is a null
965 pointer.  Before returning, the state object is updated to match the state 
966 after the last converted character.  The state is the initial state if the
967 terminating NUL byte is reached and converted.
969 If @var{dst} is not a null pointer, the result is stored in the array
970 pointed to by @var{dst}; otherwise, the conversion result is not
971 available since it is stored in an internal buffer.
973 If @var{len} wide characters are stored in the array @var{dst} before
974 reaching the end of the input string, the conversion stops and @var{len}
975 is returned.  If @var{dst} is a null pointer, @var{len} is never checked.
977 Another reason for a premature return from the function call is if the
978 input string contains an invalid multibyte sequence.  In this case the
979 global variable @code{errno} is set to @code{EILSEQ} and the function
980 returns @code{(size_t) -1}.
982 @c XXX The ISO C9x draft seems to have a problem here.  It says that PS
983 @c is not updated if DST is NULL.  This is not said straightforward and
984 @c none of the other functions is described like this.  It would make sense
985 @c to define the function this way but I don't think it is meant like this.
987 In all other cases the function returns the number of wide characters
988 converted during this call.  If @var{dst} is not null, @code{mbsrtowcs}
989 stores in the pointer pointed to by @var{src} either a null pointer (if 
990 the NUL byte in the input string was reached) or the address of the byte
991 following the last converted multibyte character.
993 @pindex wchar.h
994 @code{mbsrtowcs} was introduced in @w{Amendment 1} to @w{ISO C90} and is
995 declared in @file{wchar.h}.
996 @end deftypefun
998 The definition of the @code{mbsrtowcs} function has one important 
999 limitation.  The requirement that @var{dst} has to be a NUL-terminated 
1000 string provides problems if one wants to convert buffers with text.  A
1001 buffer is normally no collection of NUL-terminated strings but instead a
1002 continuous collection of lines, separated by newline characters.  Now
1003 assume that a function to convert one line from a buffer is needed.  Since
1004 the line is not NUL-terminated, the source pointer cannot directly point
1005 into the unmodified text buffer.  This means, either one inserts the NUL
1006 byte at the appropriate place for the time of the @code{mbsrtowcs}
1007 function call (which is not doable for a read-only buffer or in a
1008 multi-threaded application) or one copies the line in an extra buffer
1009 where it can be terminated by a NUL byte.  Note that it is not in general 
1010 possible to limit the number of characters to convert by setting the 
1011 parameter @var{len} to any specific value.  Since it is not known how 
1012 many bytes each multibyte character sequence is in length, one can only 
1013 guess.
1015 @cindex stateful
1016 There is still a problem with the method of NUL-terminating a line right
1017 after the newline character, which could lead to very strange results.
1018 As said in the description of the @code{mbsrtowcs} function above the
1019 conversion state is guaranteed to be in the initial shift state after
1020 processing the NUL byte at the end of the input string.  But this NUL
1021 byte is not really part of the text (i.e., the conversion state after
1022 the newline in the original text could be something different than the
1023 initial shift state and therefore the first character of the next line
1024 is encoded using this state).  But the state in question is never
1025 accessible to the user since the conversion stops after the NUL byte
1026 (which resets the state).  Most stateful character sets in use today
1027 require that the shift state after a newline be the initial state--but
1028 this is not a strict guarantee.  Therefore, simply NUL-terminating a
1029 piece of a running text is not always an adequate solution and, 
1030 therefore, should never be used in generally used code.
1032 The generic conversion interface (@pxref{Generic Charset Conversion})
1033 does not have this limitation (it simply works on buffers, not
1034 strings), and the GNU C library contains a set of functions that take
1035 additional parameters specifying the maximal number of bytes that are
1036 consumed from the input string.  This way the problem of
1037 @code{mbsrtowcs}'s example above could be solved by determining the line
1038 length and passing this length to the function.
1040 @comment wchar.h
1041 @comment ISO
1042 @deftypefun size_t wcsrtombs (char *restrict @var{dst}, const wchar_t **restrict @var{src}, size_t @var{len}, mbstate_t *restrict @var{ps})
1043 The @code{wcsrtombs} function (``wide character string restartable to
1044 multibyte string'') converts the NUL-terminated wide character string at
1045 @code{*@var{src}} into an equivalent multibyte character string and 
1046 stores the result in the array pointed to by @var{dst}.  The NUL wide
1047 character is also converted.  The conversion starts in the state
1048 described in the object pointed to by @var{ps} or by a state object
1049 locally to @code{wcsrtombs} in case @var{ps} is a null pointer.  If
1050 @var{dst} is a null pointer, the conversion is performed as usual but the
1051 result is not available.  If all characters of the input string were
1052 successfully converted and if @var{dst} is not a null pointer, the 
1053 pointer pointed to by @var{src} gets assigned a null pointer.
1055 If one of the wide characters in the input string has no valid multibyte
1056 character equivalent, the conversion stops early, sets the global
1057 variable @code{errno} to @code{EILSEQ}, and returns @code{(size_t) -1}.
1059 Another reason for a premature stop is if @var{dst} is not a null
1060 pointer and the next converted character would require more than
1061 @var{len} bytes in total to the array @var{dst}.  In this case (and if
1062 @var{dest} is not a null pointer) the pointer pointed to by @var{src} is
1063 assigned a value pointing to the wide character right after the last one
1064 successfully converted.
1066 Except in the case of an encoding error the return value of the 
1067 @code{wcsrtombs} function is the number of bytes in all the multibyte 
1068 character sequences stored in @var{dst}.  Before returning the state in 
1069 the object pointed to by @var{ps} (or the internal object in case 
1070 @var{ps} is a null pointer) is updated to reflect the state after the 
1071 last conversion.  The state is the initial shift state in case the 
1072 terminating NUL wide character was converted.
1074 @pindex wchar.h
1075 The @code{wcsrtombs} function was introduced in @w{Amendment 1} to 
1076 @w{ISO C90} and is declared in @file{wchar.h}.
1077 @end deftypefun
1079 The restriction mentioned above for the @code{mbsrtowcs} function applies
1080 here also.  There is no possibility of directly controlling the number of
1081 input characters.  One has to place the NUL wide character at the correct 
1082 place or control the consumed input indirectly via the available output 
1083 array size (the @var{len} parameter).
1085 @comment wchar.h
1086 @comment GNU
1087 @deftypefun size_t mbsnrtowcs (wchar_t *restrict @var{dst}, const char **restrict @var{src}, size_t @var{nmc}, size_t @var{len}, mbstate_t *restrict @var{ps})
1088 The @code{mbsnrtowcs} function is very similar to the @code{mbsrtowcs}
1089 function.  All the parameters are the same except for @var{nmc}, which is
1090 new.  The return value is the same as for @code{mbsrtowcs}.
1092 This new parameter specifies how many bytes at most can be used from the
1093 multibyte character string.  In other words, the multibyte character 
1094 string @code{*@var{src}} need not be NUL-terminated.  But if a NUL byte 
1095 is found within the @var{nmc} first bytes of the string, the conversion 
1096 stops here.
1098 This function is a GNU extension.  It is meant to work around the
1099 problems mentioned above.  Now it is possible to convert a buffer with
1100 multibyte character text piece for piece without having to care about
1101 inserting NUL bytes and the effect of NUL bytes on the conversion state.
1102 @end deftypefun
1104 A function to convert a multibyte string into a wide character string
1105 and display it could be written like this (this is not a really useful
1106 example):
1108 @smallexample
1109 void
1110 showmbs (const char *src, FILE *fp)
1112   mbstate_t state;
1113   int cnt = 0;
1114   memset (&state, '\0', sizeof (state));
1115   while (1)
1116     @{
1117       wchar_t linebuf[100];
1118       const char *endp = strchr (src, '\n');
1119       size_t n;
1121       /* @r{Exit if there is no more line.}  */
1122       if (endp == NULL)
1123         break;
1125       n = mbsnrtowcs (linebuf, &src, endp - src, 99, &state);
1126       linebuf[n] = L'\0';
1127       fprintf (fp, "line %d: \"%S\"\n", linebuf);
1128     @}
1130 @end smallexample
1132 There is no problem with the state after a call to @code{mbsnrtowcs}.
1133 Since we don't insert characters in the strings that were not in there
1134 right from the beginning and we use @var{state} only for the conversion
1135 of the given buffer, there is no problem with altering the state.
1137 @comment wchar.h
1138 @comment GNU
1139 @deftypefun size_t wcsnrtombs (char *restrict @var{dst}, const wchar_t **restrict @var{src}, size_t @var{nwc}, size_t @var{len}, mbstate_t *restrict @var{ps})
1140 The @code{wcsnrtombs} function implements the conversion from wide
1141 character strings to multibyte character strings.  It is similar to
1142 @code{wcsrtombs} but, just like @code{mbsnrtowcs}, it takes an extra
1143 parameter, which specifies the length of the input string.
1145 No more than @var{nwc} wide characters from the input string
1146 @code{*@var{src}} are converted.  If the input string contains a NUL
1147 wide character in the first @var{nwc} characters, the conversion stops at
1148 this place.
1150 The @code{wcsnrtombs} function is a GNU extension and just like 
1151 @code{mbsnrtowcs} helps in situations where no NUL-terminated input 
1152 strings are available.
1153 @end deftypefun
1156 @node Multibyte Conversion Example
1157 @subsection A Complete Multibyte Conversion Example
1159 The example programs given in the last sections are only brief and do
1160 not contain all the error checking, etc.  Presented here is a complete
1161 and documented example.  It features the @code{mbrtowc} function but it
1162 should be easy to derive versions using the other functions.
1164 @smallexample
1166 file_mbsrtowcs (int input, int output)
1168   /* @r{Note the use of @code{MB_LEN_MAX}.}
1169      @r{@code{MB_CUR_MAX} cannot portably be used here.}  */
1170   char buffer[BUFSIZ + MB_LEN_MAX];
1171   mbstate_t state;
1172   int filled = 0;
1173   int eof = 0;
1175   /* @r{Initialize the state.}  */
1176   memset (&state, '\0', sizeof (state));
1178   while (!eof)
1179     @{
1180       ssize_t nread;
1181       ssize_t nwrite;
1182       char *inp = buffer;
1183       wchar_t outbuf[BUFSIZ];
1184       wchar_t *outp = outbuf;
1186       /* @r{Fill up the buffer from the input file.}  */
1187       nread = read (input, buffer + filled, BUFSIZ);
1188       if (nread < 0)
1189         @{
1190           perror ("read");
1191           return 0;
1192         @}
1193       /* @r{If we reach end of file, make a note to read no more.} */
1194       if (nread == 0)
1195         eof = 1;
1197       /* @r{@code{filled} is now the number of bytes in @code{buffer}.} */
1198       filled += nread;
1200       /* @r{Convert those bytes to wide characters--as many as we can.} */
1201       while (1)
1202         @{
1203           size_t thislen = mbrtowc (outp, inp, filled, &state);
1204           /* @r{Stop converting at invalid character;}
1205              @r{this can mean we have read just the first part}
1206              @r{of a valid character.}  */
1207           if (thislen == (size_t) -1)
1208             break;
1209           /* @r{We want to handle embedded NUL bytes}
1210              @r{but the return value is 0.  Correct this.}  */
1211           if (thislen == 0)
1212             thislen = 1;
1213           /* @r{Advance past this character.} */
1214           inp += thislen;
1215           filled -= thislen;
1216           ++outp;
1217         @}
1219       /* @r{Write the wide characters we just made.}  */
1220       nwrite = write (output, outbuf,
1221                       (outp - outbuf) * sizeof (wchar_t));
1222       if (nwrite < 0)
1223         @{
1224           perror ("write");
1225           return 0;
1226         @}
1228       /* @r{See if we have a @emph{real} invalid character.} */
1229       if ((eof && filled > 0) || filled >= MB_CUR_MAX)
1230         @{
1231           error (0, 0, "invalid multibyte character");
1232           return 0;
1233         @}
1235       /* @r{If any characters must be carried forward,}
1236          @r{put them at the beginning of @code{buffer}.} */
1237       if (filled > 0)
1238         memmove (inp, buffer, filled);
1239     @}
1241   return 1;
1243 @end smallexample
1246 @node Non-reentrant Conversion
1247 @section Non-reentrant Conversion Function
1249 The functions described in the previous chapter are defined in
1250 @w{Amendment 1} to @w{ISO C90}, but the original @w{ISO C90} standard 
1251 also contained functions for character set conversion.  The reason that 
1252 these original functions are not described first is that they are almost 
1253 entirely useless.
1255 The problem is that all the conversion functions described in the 
1256 original @w{ISO C90} use a local state.  Using a local state implies that 
1257 multiple conversions at the same time (not only when using threads) 
1258 cannot be done, and that you cannot first convert single characters and 
1259 then strings since you cannot tell the conversion functions which state 
1260 to use.
1262 These original functions are therefore usable only in a very limited set 
1263 of situations.  One must complete converting the entire string before
1264 starting a new one, and each string/text must be converted with the same
1265 function (there is no problem with the library itself; it is guaranteed
1266 that no library function changes the state of any of these functions).
1267 @strong{For the above reasons it is highly requested that the functions
1268 described in the previous section be used in place of non-reentrant 
1269 conversion functions.}
1271 @menu
1272 * Non-reentrant Character Conversion::  Non-reentrant Conversion of Single
1273                                          Characters.
1274 * Non-reentrant String Conversion::     Non-reentrant Conversion of Strings.
1275 * Shift State::                         States in Non-reentrant Functions.
1276 @end menu
1278 @node Non-reentrant Character Conversion
1279 @subsection Non-reentrant Conversion of Single Characters
1281 @comment stdlib.h
1282 @comment ISO
1283 @deftypefun int mbtowc (wchar_t *restrict @var{result}, const char *restrict @var{string}, size_t @var{size})
1284 The @code{mbtowc} (``multibyte to wide character'') function when called
1285 with non-null @var{string} converts the first multibyte character
1286 beginning at @var{string} to its corresponding wide character code.  It
1287 stores the result in @code{*@var{result}}.
1289 @code{mbtowc} never examines more than @var{size} bytes.  (The idea is
1290 to supply for @var{size} the number of bytes of data you have in hand.)
1292 @code{mbtowc} with non-null @var{string} distinguishes three
1293 possibilities: the first @var{size} bytes at @var{string} start with
1294 valid multibyte characters, they start with an invalid byte sequence or
1295 just part of a character, or @var{string} points to an empty string (a
1296 null character).
1298 For a valid multibyte character, @code{mbtowc} converts it to a wide
1299 character and stores that in @code{*@var{result}}, and returns the
1300 number of bytes in that character (always at least @math{1} and never
1301 more than @var{size}).
1303 For an invalid byte sequence, @code{mbtowc} returns @math{-1}.  For an
1304 empty string, it returns @math{0}, also storing @code{'\0'} in
1305 @code{*@var{result}}.
1307 If the multibyte character code uses shift characters, then
1308 @code{mbtowc} maintains and updates a shift state as it scans.  If you
1309 call @code{mbtowc} with a null pointer for @var{string}, that
1310 initializes the shift state to its standard initial value.  It also
1311 returns nonzero if the multibyte character code in use actually has a
1312 shift state.  @xref{Shift State}.
1313 @end deftypefun
1315 @comment stdlib.h
1316 @comment ISO
1317 @deftypefun int wctomb (char *@var{string}, wchar_t @var{wchar})
1318 The @code{wctomb} (``wide character to multibyte'') function converts
1319 the wide character code @var{wchar} to its corresponding multibyte
1320 character sequence, and stores the result in bytes starting at
1321 @var{string}.  At most @code{MB_CUR_MAX} characters are stored.
1323 @code{wctomb} with non-null @var{string} distinguishes three
1324 possibilities for @var{wchar}: a valid wide character code (one that can
1325 be translated to a multibyte character), an invalid code, and 
1326 @code{L'\0'}.
1328 Given a valid code, @code{wctomb} converts it to a multibyte character,
1329 storing the bytes starting at @var{string}.  Then it returns the number
1330 of bytes in that character (always at least @math{1} and never more
1331 than @code{MB_CUR_MAX}).
1333 If @var{wchar} is an invalid wide character code, @code{wctomb} returns
1334 @math{-1}.  If @var{wchar} is @code{L'\0'}, it returns @code{0}, also
1335 storing @code{'\0'} in @code{*@var{string}}.
1337 If the multibyte character code uses shift characters, then
1338 @code{wctomb} maintains and updates a shift state as it scans.  If you
1339 call @code{wctomb} with a null pointer for @var{string}, that
1340 initializes the shift state to its standard initial value.  It also
1341 returns nonzero if the multibyte character code in use actually has a
1342 shift state.  @xref{Shift State}.
1344 Calling this function with a @var{wchar} argument of zero when
1345 @var{string} is not null has the side-effect of reinitializing the
1346 stored shift state @emph{as well as} storing the multibyte character
1347 @code{'\0'} and returning @math{0}.
1348 @end deftypefun
1350 Similar to @code{mbrlen} there is also a non-reentrant function that
1351 computes the length of a multibyte character.  It can be defined in
1352 terms of @code{mbtowc}.
1354 @comment stdlib.h
1355 @comment ISO
1356 @deftypefun int mblen (const char *@var{string}, size_t @var{size})
1357 The @code{mblen} function with a non-null @var{string} argument returns
1358 the number of bytes that make up the multibyte character beginning at
1359 @var{string}, never examining more than @var{size} bytes.  (The idea is
1360 to supply for @var{size} the number of bytes of data you have in hand.)
1362 The return value of @code{mblen} distinguishes three possibilities: the
1363 first @var{size} bytes at @var{string} start with valid multibyte
1364 characters, they start with an invalid byte sequence or just part of a
1365 character, or @var{string} points to an empty string (a null character).
1367 For a valid multibyte character, @code{mblen} returns the number of
1368 bytes in that character (always at least @code{1} and never more than
1369 @var{size}).  For an invalid byte sequence, @code{mblen} returns 
1370 @math{-1}.  For an empty string, it returns @math{0}.
1372 If the multibyte character code uses shift characters, then @code{mblen}
1373 maintains and updates a shift state as it scans.  If you call
1374 @code{mblen} with a null pointer for @var{string}, that initializes the
1375 shift state to its standard initial value.  It also returns a nonzero
1376 value if the multibyte character code in use actually has a shift state.
1377 @xref{Shift State}.
1379 @pindex stdlib.h
1380 The function @code{mblen} is declared in @file{stdlib.h}.
1381 @end deftypefun
1384 @node Non-reentrant String Conversion
1385 @subsection Non-reentrant Conversion of Strings
1387 For convenience the @w{ISO C90} standard also defines functions to 
1388 convert entire strings instead of single characters.  These functions
1389 suffer from the same problems as their reentrant counterparts from
1390 @w{Amendment 1} to @w{ISO C90}; see @ref{Converting Strings}.
1392 @comment stdlib.h
1393 @comment ISO
1394 @deftypefun size_t mbstowcs (wchar_t *@var{wstring}, const char *@var{string}, size_t @var{size})
1395 The @code{mbstowcs} (``multibyte string to wide character string'')
1396 function converts the null-terminated string of multibyte characters
1397 @var{string} to an array of wide character codes, storing not more than
1398 @var{size} wide characters into the array beginning at @var{wstring}.
1399 The terminating null character counts towards the size, so if @var{size}
1400 is less than the actual number of wide characters resulting from
1401 @var{string}, no terminating null character is stored.
1403 The conversion of characters from @var{string} begins in the initial
1404 shift state.
1406 If an invalid multibyte character sequence is found, the @code{mbstowcs} 
1407 function returns a value of @math{-1}.  Otherwise, it returns the number 
1408 of wide characters stored in the array @var{wstring}.  This number does 
1409 not include the terminating null character, which is present if the 
1410 number is less than @var{size}.
1412 Here is an example showing how to convert a string of multibyte
1413 characters, allocating enough space for the result.
1415 @smallexample
1416 wchar_t *
1417 mbstowcs_alloc (const char *string)
1419   size_t size = strlen (string) + 1;
1420   wchar_t *buf = xmalloc (size * sizeof (wchar_t));
1422   size = mbstowcs (buf, string, size);
1423   if (size == (size_t) -1)
1424     return NULL;
1425   buf = xrealloc (buf, (size + 1) * sizeof (wchar_t));
1426   return buf;
1428 @end smallexample
1430 @end deftypefun
1432 @comment stdlib.h
1433 @comment ISO
1434 @deftypefun size_t wcstombs (char *@var{string}, const wchar_t *@var{wstring}, size_t @var{size})
1435 The @code{wcstombs} (``wide character string to multibyte string'')
1436 function converts the null-terminated wide character array @var{wstring}
1437 into a string containing multibyte characters, storing not more than
1438 @var{size} bytes starting at @var{string}, followed by a terminating
1439 null character if there is room.  The conversion of characters begins in
1440 the initial shift state.
1442 The terminating null character counts towards the size, so if @var{size}
1443 is less than or equal to the number of bytes needed in @var{wstring}, no
1444 terminating null character is stored.
1446 If a code that does not correspond to a valid multibyte character is
1447 found, the @code{wcstombs} function returns a value of @math{-1}. 
1448 Otherwise, the return value is the number of bytes stored in the array 
1449 @var{string}.  This number does not include the terminating null character, 
1450 which is present if the number is less than @var{size}.
1451 @end deftypefun
1453 @node Shift State
1454 @subsection States in Non-reentrant Functions
1456 In some multibyte character codes, the @emph{meaning} of any particular
1457 byte sequence is not fixed; it depends on what other sequences have come
1458 earlier in the same string.  Typically there are just a few sequences that 
1459 can change the meaning of other sequences; these few are called 
1460 @dfn{shift sequences} and we say that they set the @dfn{shift state} for
1461 other sequences that follow.
1463 To illustrate shift state and shift sequences, suppose we decide that
1464 the sequence @code{0200} (just one byte) enters Japanese mode, in which
1465 pairs of bytes in the range from @code{0240} to @code{0377} are single
1466 characters, while @code{0201} enters Latin-1 mode, in which single bytes
1467 in the range from @code{0240} to @code{0377} are characters, and
1468 interpreted according to the ISO Latin-1 character set.  This is a
1469 multibyte code that has two alternative shift states (``Japanese mode''
1470 and ``Latin-1 mode''), and two shift sequences that specify particular
1471 shift states.
1473 When the multibyte character code in use has shift states, then
1474 @code{mblen}, @code{mbtowc}, and @code{wctomb} must maintain and update
1475 the current shift state as they scan the string.  To make this work
1476 properly, you must follow these rules:
1478 @itemize @bullet
1479 @item
1480 Before starting to scan a string, call the function with a null pointer
1481 for the multibyte character address---for example, @code{mblen (NULL,
1482 0)}.  This initializes the shift state to its standard initial value.
1484 @item
1485 Scan the string one character at a time, in order.  Do not ``back up''
1486 and rescan characters already scanned, and do not intersperse the
1487 processing of different strings.
1488 @end itemize
1490 Here is an example of using @code{mblen} following these rules:
1492 @smallexample
1493 void
1494 scan_string (char *s)
1496   int length = strlen (s);
1498   /* @r{Initialize shift state.}  */
1499   mblen (NULL, 0);
1501   while (1)
1502     @{
1503       int thischar = mblen (s, length);
1504       /* @r{Deal with end of string and invalid characters.}  */
1505       if (thischar == 0)
1506         break;
1507       if (thischar == -1)
1508         @{
1509           error ("invalid multibyte character");
1510           break;
1511         @}
1512       /* @r{Advance past this character.}  */
1513       s += thischar;
1514       length -= thischar;
1515     @}
1517 @end smallexample
1519 The functions @code{mblen}, @code{mbtowc} and @code{wctomb} are not
1520 reentrant when using a multibyte code that uses a shift state.  However,
1521 no other library functions call these functions, so you don't have to
1522 worry that the shift state will be changed mysteriously.
1525 @node Generic Charset Conversion
1526 @section Generic Charset Conversion
1528 The conversion functions mentioned so far in this chapter all had in
1529 common that they operate on character sets that are not directly
1530 specified by the functions.  The multibyte encoding used is specified by
1531 the currently selected locale for the @code{LC_CTYPE} category.  The
1532 wide character set is fixed by the implementation (in the case of GNU C
1533 library it is always UCS-4 encoded @w{ISO 10646}.
1535 This has of course several problems when it comes to general character
1536 conversion:
1538 @itemize @bullet
1539 @item
1540 For every conversion where neither the source nor the destination 
1541 character set is the character set of the locale for the @code{LC_CTYPE} 
1542 category, one has to change the @code{LC_CTYPE} locale using 
1543 @code{setlocale}.
1545 Changing the @code{LC_TYPE} locale introduces major problems for the rest 
1546 of the programs since several more functions (e.g., the character 
1547 classification functions, @pxref{Classification of Characters}) use the 
1548 @code{LC_CTYPE} category.
1550 @item
1551 Parallel conversions to and from different character sets are not
1552 possible since the @code{LC_CTYPE} selection is global and shared by all
1553 threads.
1555 @item
1556 If neither the source nor the destination character set is the character
1557 set used for @code{wchar_t} representation, there is at least a two-step
1558 process necessary to convert a text using the functions above.  One would 
1559 have to select the source character set as the multibyte encoding, 
1560 convert the text into a @code{wchar_t} text, select the destination
1561 character set as the multibyte encoding, and convert the wide character
1562 text to the multibyte (@math{=} destination) character set.
1564 Even if this is possible (which is not guaranteed) it is a very tiring
1565 work.  Plus it suffers from the other two raised points even more due to
1566 the steady changing of the locale.
1567 @end itemize
1569 The XPG2 standard defines a completely new set of functions, which has
1570 none of these limitations.  They are not at all coupled to the selected
1571 locales, and they have no constraints on the character sets selected for
1572 source and destination.  Only the set of available conversions limits 
1573 them.  The standard does not specify that any conversion at all must be 
1574 available.  Such availability is a measure of the quality of the 
1575 implementation.
1577 In the following text first the interface to @code{iconv} and then the
1578 conversion function, will be described.  Comparisons with other
1579 implementations will show what obstacles stand in the way of portable
1580 applications.  Finally, the implementation is described in so far as might 
1581 interest the advanced user who wants to extend conversion capabilities.
1583 @menu
1584 * Generic Conversion Interface::    Generic Character Set Conversion Interface.
1585 * iconv Examples::                  A complete @code{iconv} example.
1586 * Other iconv Implementations::     Some Details about other @code{iconv}
1587                                      Implementations.
1588 * glibc iconv Implementation::      The @code{iconv} Implementation in the GNU C
1589                                      library.
1590 @end menu
1592 @node Generic Conversion Interface
1593 @subsection Generic Character Set Conversion Interface
1595 This set of functions follows the traditional cycle of using a resource:
1596 open--use--close.  The interface consists of three functions, each of
1597 which implements one step.
1599 Before the interfaces are described it is necessary to introduce a
1600 data type.  Just like other open--use--close interfaces the functions
1601 introduced here work using handles and the @file{iconv.h} header
1602 defines a special type for the handles used.
1604 @comment iconv.h
1605 @comment XPG2
1606 @deftp {Data Type} iconv_t
1607 This data type is an abstract type defined in @file{iconv.h}.  The user
1608 must not assume anything about the definition of this type; it must be
1609 completely opaque.
1611 Objects of this type can get assigned handles for the conversions using
1612 the @code{iconv} functions.  The objects themselves need not be freed, but
1613 the conversions for which the handles stand for have to.
1614 @end deftp
1616 @noindent
1617 The first step is the function to create a handle.
1619 @comment iconv.h
1620 @comment XPG2
1621 @deftypefun iconv_t iconv_open (const char *@var{tocode}, const char *@var{fromcode})
1622 The @code{iconv_open} function has to be used before starting a
1623 conversion.  The two parameters this function takes determine the
1624 source and destination character set for the conversion, and if the
1625 implementation has the possibility to perform such a conversion, the
1626 function returns a handle.
1628 If the wanted conversion is not available, the @code{iconv_open} function 
1629 returns @code{(iconv_t) -1}. In this case the global variable 
1630 @code{errno} can have the following values:
1632 @table @code
1633 @item EMFILE
1634 The process already has @code{OPEN_MAX} file descriptors open.
1635 @item ENFILE
1636 The system limit of open file is reached.
1637 @item ENOMEM
1638 Not enough memory to carry out the operation.
1639 @item EINVAL
1640 The conversion from @var{fromcode} to @var{tocode} is not supported.
1641 @end table
1643 It is not possible to use the same descriptor in different threads to
1644 perform independent conversions.  The data structures associated
1645 with the descriptor include information about the conversion state.
1646 This must not be messed up by using it in different conversions.
1648 An @code{iconv} descriptor is like a file descriptor as for every use a
1649 new descriptor must be created.  The descriptor does not stand for all
1650 of the conversions from @var{fromset} to @var{toset}.
1652 The GNU C library implementation of @code{iconv_open} has one
1653 significant extension to other implementations.  To ease the extension
1654 of the set of available conversions, the implementation allows storing
1655 the necessary files with data and code in an arbitrary number of 
1656 directories.  How this extension must be written will be explained below
1657 (@pxref{glibc iconv Implementation}).  Here it is only important to say
1658 that all directories mentioned in the @code{GCONV_PATH} environment
1659 variable are considered only if they contain a file @file{gconv-modules}.
1660 These directories need not necessarily be created by the system
1661 administrator.  In fact, this extension is introduced to help users
1662 writing and using their own, new conversions.  Of course, this does not 
1663 work for security reasons in SUID binaries; in this case only the system
1664 directory is considered and this normally is 
1665 @file{@var{prefix}/lib/gconv}.  The @code{GCONV_PATH} environment 
1666 variable is examined exactly once at the first call of the 
1667 @code{iconv_open} function.  Later modifications of the variable have no 
1668 effect.
1670 @pindex iconv.h
1671 The @code{iconv_open} function was introduced early in the X/Open 
1672 Portability Guide, @w{version 2}.  It is supported by all commercial 
1673 Unices as it is required for the Unix branding.  However, the quality and 
1674 completeness of the implementation varies widely.  The @code{iconv_open} 
1675 function is declared in @file{iconv.h}.
1676 @end deftypefun
1678 The @code{iconv} implementation can associate large data structure with
1679 the handle returned by @code{iconv_open}.  Therefore, it is crucial to 
1680 free all the resources once all conversions are carried out and the 
1681 conversion is not needed anymore.
1683 @comment iconv.h
1684 @comment XPG2
1685 @deftypefun int iconv_close (iconv_t @var{cd})
1686 The @code{iconv_close} function frees all resources associated with the
1687 handle @var{cd}, which must have been returned by a successful call to
1688 the @code{iconv_open} function.
1690 If the function call was successful the return value is @math{0}.
1691 Otherwise it is @math{-1} and @code{errno} is set appropriately.
1692 Defined error are:
1694 @table @code
1695 @item EBADF
1696 The conversion descriptor is invalid.
1697 @end table
1699 @pindex iconv.h
1700 The @code{iconv_close} function was introduced together with the rest 
1701 of the @code{iconv} functions in XPG2 and is declared in @file{iconv.h}.
1702 @end deftypefun
1704 The standard defines only one actual conversion function.  This has,
1705 therefore, the most general interface: it allows conversion from one
1706 buffer to another.  Conversion from a file to a buffer, vice versa, or
1707 even file to file can be implemented on top of it.
1709 @comment iconv.h
1710 @comment XPG2
1711 @deftypefun size_t iconv (iconv_t @var{cd}, char **@var{inbuf}, size_t *@var{inbytesleft}, char **@var{outbuf}, size_t *@var{outbytesleft})
1712 @cindex stateful
1713 The @code{iconv} function converts the text in the input buffer
1714 according to the rules associated with the descriptor @var{cd} and
1715 stores the result in the output buffer.  It is possible to call the
1716 function for the same text several times in a row since for stateful
1717 character sets the necessary state information is kept in the data
1718 structures associated with the descriptor.
1720 The input buffer is specified by @code{*@var{inbuf}} and it contains
1721 @code{*@var{inbytesleft}} bytes.  The extra indirection is necessary for
1722 communicating the used input back to the caller (see below).  It is
1723 important to note that the buffer pointer is of type @code{char} and the
1724 length is measured in bytes even if the input text is encoded in wide
1725 characters.
1727 The output buffer is specified in a similar way.  @code{*@var{outbuf}}
1728 points to the beginning of the buffer with at least
1729 @code{*@var{outbytesleft}} bytes room for the result.  The buffer
1730 pointer again is of type @code{char} and the length is measured in
1731 bytes.  If @var{outbuf} or @code{*@var{outbuf}} is a null pointer, the
1732 conversion is performed but no output is available.
1734 If @var{inbuf} is a null pointer, the @code{iconv} function performs the
1735 necessary action to put the state of the conversion into the initial
1736 state.  This is obviously a no-op for non-stateful encodings, but if the
1737 encoding has a state, such a function call might put some byte sequences
1738 in the output buffer, which perform the necessary state changes.  The
1739 next call with @var{inbuf} not being a null pointer then simply goes on
1740 from the initial state.  It is important that the programmer never makes
1741 any assumption as to whether the conversion has to deal with states.  
1742 Even if the input and output character sets are not stateful, the 
1743 implementation might still have to keep states.  This is due to the
1744 implementation chosen for the GNU C library as it is described below.
1745 Therefore an @code{iconv} call to reset the state should always be
1746 performed if some protocol requires this for the output text.
1748 The conversion stops for one of three reasons. The first is that all
1749 characters from the input buffer are converted.  This actually can mean
1750 two things: either all bytes from the input buffer are consumed or
1751 there are some bytes at the end of the buffer that possibly can form a
1752 complete character but the input is incomplete.  The second reason for a
1753 stop is that the output buffer is full.  And the third reason is that
1754 the input contains invalid characters.
1756 In all of these cases the buffer pointers after the last successful
1757 conversion, for input and output buffer, are stored in @var{inbuf} and
1758 @var{outbuf}, and the available room in each buffer is stored in
1759 @var{inbytesleft} and @var{outbytesleft}.
1761 Since the character sets selected in the @code{iconv_open} call can be
1762 almost arbitrary, there can be situations where the input buffer contains
1763 valid characters, which have no identical representation in the output
1764 character set.  The behavior in this situation is undefined.  The
1765 @emph{current} behavior of the GNU C library in this situation is to
1766 return with an error immediately.  This certainly is not the most
1767 desirable solution; therefore, future versions will provide better ones,
1768 but they are not yet finished.
1770 If all input from the input buffer is successfully converted and stored
1771 in the output buffer, the function returns the number of non-reversible
1772 conversions performed.  In all other cases the return value is
1773 @code{(size_t) -1} and @code{errno} is set appropriately.  In such cases
1774 the value pointed to by @var{inbytesleft} is nonzero.
1776 @table @code
1777 @item EILSEQ
1778 The conversion stopped because of an invalid byte sequence in the input.
1779 After the call, @code{*@var{inbuf}} points at the first byte of the
1780 invalid byte sequence.
1782 @item E2BIG
1783 The conversion stopped because it ran out of space in the output buffer.
1785 @item EINVAL
1786 The conversion stopped because of an incomplete byte sequence at the end
1787 of the input buffer.
1789 @item EBADF
1790 The @var{cd} argument is invalid.
1791 @end table
1793 @pindex iconv.h
1794 The @code{iconv} function was introduced in the XPG2 standard and is 
1795 declared in the @file{iconv.h} header.
1796 @end deftypefun
1798 The definition of the @code{iconv} function is quite good overall.  It
1799 provides quite flexible functionality.  The only problems lie in the
1800 boundary cases, which are incomplete byte sequences at the end of the
1801 input buffer and invalid input.  A third problem, which is not really
1802 a design problem, is the way conversions are selected.  The standard
1803 does not say anything about the legitimate names, a minimal set of
1804 available conversions.  We will see how this negatively impacts other
1805 implementations, as demonstrated below.
1807 @node iconv Examples
1808 @subsection A complete @code{iconv} example
1810 The example below features a solution for a common problem.  Given that
1811 one knows the internal encoding used by the system for @code{wchar_t}
1812 strings, one often is in the position to read text from a file and store
1813 it in wide character buffers.  One can do this using @code{mbsrtowcs},
1814 but then we run into the problems discussed above.
1816 @smallexample
1818 file2wcs (int fd, const char *charset, wchar_t *outbuf, size_t avail)
1820   char inbuf[BUFSIZ];
1821   size_t insize = 0;
1822   char *wrptr = (char *) outbuf;
1823   int result = 0;
1824   iconv_t cd;
1826   cd = iconv_open ("WCHAR_T", charset);
1827   if (cd == (iconv_t) -1)
1828     @{
1829       /* @r{Something went wrong.}  */
1830       if (errno == EINVAL)
1831         error (0, 0, "conversion from '%s' to wchar_t not available",
1832                charset);
1833       else
1834         perror ("iconv_open");
1836       /* @r{Terminate the output string.}  */
1837       *outbuf = L'\0';
1839       return -1;
1840     @}
1842   while (avail > 0)
1843     @{
1844       size_t nread;
1845       size_t nconv;
1846       char *inptr = inbuf;
1848       /* @r{Read more input.}  */
1849       nread = read (fd, inbuf + insize, sizeof (inbuf) - insize);
1850       if (nread == 0)
1851         @{
1852           /* @r{When we come here the file is completely read.}
1853              @r{This still could mean there are some unused}
1854              @r{characters in the @code{inbuf}.  Put them back.}  */
1855           if (lseek (fd, -insize, SEEK_CUR) == -1)
1856             result = -1;
1858           /* @r{Now write out the byte sequence to get into the}
1859              @r{initial state if this is necessary.}  */
1860           iconv (cd, NULL, NULL, &wrptr, &avail);
1862           break;
1863         @}
1864       insize += nread;
1866       /* @r{Do the conversion.}  */
1867       nconv = iconv (cd, &inptr, &insize, &wrptr, &avail);
1868       if (nconv == (size_t) -1)
1869         @{
1870           /* @r{Not everything went right.  It might only be}
1871              @r{an unfinished byte sequence at the end of the}
1872              @r{buffer.  Or it is a real problem.}  */
1873           if (errno == EINVAL)
1874             /* @r{This is harmless.  Simply move the unused}
1875                @r{bytes to the beginning of the buffer so that}
1876                @r{they can be used in the next round.}  */
1877             memmove (inbuf, inptr, insize);
1878           else
1879             @{
1880               /* @r{It is a real problem.  Maybe we ran out of}
1881                  @r{space in the output buffer or we have invalid}
1882                  @r{input.  In any case back the file pointer to}
1883                  @r{the position of the last processed byte.}  */
1884               lseek (fd, -insize, SEEK_CUR);
1885               result = -1;
1886               break;
1887             @}
1888         @}
1889     @}
1891   /* @r{Terminate the output string.}  */
1892   if (avail >= sizeof (wchar_t))
1893     *((wchar_t *) wrptr) = L'\0';
1895   if (iconv_close (cd) != 0)
1896     perror ("iconv_close");
1898   return (wchar_t *) wrptr - outbuf;
1900 @end smallexample
1902 @cindex stateful
1903 This example shows the most important aspects of using the @code{iconv}
1904 functions.  It shows how successive calls to @code{iconv} can be used to
1905 convert large amounts of text.  The user does not have to care about
1906 stateful encodings as the functions take care of everything.
1908 An interesting point is the case where @code{iconv} returns an error and
1909 @code{errno} is set to @code{EINVAL}.  This is not really an error in the 
1910 transformation.  It can happen whenever the input character set contains 
1911 byte sequences of more than one byte for some character and texts are not 
1912 processed in one piece.  In this case there is a chance that a multibyte 
1913 sequence is cut.  The caller can then simply read the remainder of the 
1914 takes and feed the offending bytes together with new character from the 
1915 input to @code{iconv} and continue the work.  The internal state kept in 
1916 the descriptor is @emph{not} unspecified after such an event as is the 
1917 case with the conversion functions from the @w{ISO C} standard.
1919 The example also shows the problem of using wide character strings with
1920 @code{iconv}.  As explained in the description of the @code{iconv}
1921 function above, the function always takes a pointer to a @code{char}
1922 array and the available space is measured in bytes.  In the example, the
1923 output buffer is a wide character buffer; therefore, we use a local
1924 variable @var{wrptr} of type @code{char *}, which is used in the
1925 @code{iconv} calls.
1927 This looks rather innocent but can lead to problems on platforms that
1928 have tight restriction on alignment.  Therefore the caller of @code{iconv} 
1929 has to make sure that the pointers passed are suitable for access of 
1930 characters from the appropriate character set.  Since, in the
1931 above case, the input parameter to the function is a @code{wchar_t}
1932 pointer, this is the case (unless the user violates alignment when
1933 computing the parameter).  But in other situations, especially when
1934 writing generic functions where one does not know what type of character
1935 set one uses and, therefore, treats text as a sequence of bytes, it might
1936 become tricky.
1938 @node Other iconv Implementations
1939 @subsection Some Details about other @code{iconv} Implementations
1941 This is not really the place to discuss the @code{iconv} implementation
1942 of other systems but it is necessary to know a bit about them to write
1943 portable programs.  The above mentioned problems with the specification
1944 of the @code{iconv} functions can lead to portability issues.
1946 The first thing to notice is that, due to the large number of character
1947 sets in use, it is certainly not practical to encode the conversions
1948 directly in the C library.  Therefore, the conversion information must
1949 come from files outside the C library.  This is usually done in one or
1950 both of the following ways:
1952 @itemize @bullet
1953 @item
1954 The C library contains a set of generic conversion functions that can
1955 read the needed conversion tables and other information from data files.
1956 These files get loaded when necessary.
1958 This solution is problematic as it requires a great deal of effort to
1959 apply to all character sets (potentially an infinite set).  The 
1960 differences in the structure of the different character sets is so large
1961 that many different variants of the table-processing functions must be
1962 developed.  In addition, the generic nature of these functions make them 
1963 slower than specifically implemented functions.
1965 @item
1966 The C library only contains a framework that can dynamically load
1967 object files and execute the conversion functions contained therein.
1969 This solution provides much more flexibility.  The C library itself
1970 contains only very little code and therefore reduces the general memory
1971 footprint.  Also, with a documented interface between the C library and
1972 the loadable modules it is possible for third parties to extend the set
1973 of available conversion modules.  A drawback of this solution is that
1974 dynamic loading must be available.
1975 @end itemize
1977 Some implementations in commercial Unices implement a mixture of these 
1978 possibilities; the majority implement only the second solution.  Using 
1979 loadable modules moves the code out of the library itself and keeps 
1980 the door open for extensions and improvements, but this design is also
1981 limiting on some platforms since not many platforms support dynamic
1982 loading in statically linked programs.  On platforms without this
1983 capability it is therefore not possible to use this interface in
1984 statically linked programs.  The GNU C library has, on ELF platforms, no
1985 problems with dynamic loading in these situations; therefore, this
1986 point is moot.  The danger is that one gets acquainted with this 
1987 situation and forgets about the restrictions on other systems.
1989 A second thing to know about other @code{iconv} implementations is that
1990 the number of available conversions is often very limited.  Some
1991 implementations provide, in the standard release (not special
1992 international or developer releases), at most 100 to 200 conversion
1993 possibilities.  This does not mean 200 different character sets are
1994 supported; for example, conversions from one character set to a set of 10 
1995 others might count as 10 conversions.  Together with the other direction
1996 this makes 20 conversion possibilities used up by one character set.  One 
1997 can imagine the thin coverage these platform provide.  Some Unix vendors 
1998 even provide only a handful of conversions, which renders them useless for 
1999 almost all uses.
2001 This directly leads to a third and probably the most problematic point.
2002 The way the @code{iconv} conversion functions are implemented on all
2003 known Unix systems and the availability of the conversion functions from
2004 character set @math{@cal{A}} to @math{@cal{B}} and the conversion from
2005 @math{@cal{B}} to @math{@cal{C}} does @emph{not} imply that the
2006 conversion from @math{@cal{A}} to @math{@cal{C}} is available.
2008 This might not seem unreasonable and problematic at first, but it is a
2009 quite big problem as one will notice shortly after hitting it.  To show
2010 the problem we assume to write a program that has to convert from
2011 @math{@cal{A}} to @math{@cal{C}}.  A call like
2013 @smallexample
2014 cd = iconv_open ("@math{@cal{C}}", "@math{@cal{A}}");
2015 @end smallexample
2017 @noindent
2018 fails according to the assumption above.  But what does the program
2019 do now?  The conversion is necessary; therefore, simply giving up is not
2020 an option.
2022 This is a nuisance.  The @code{iconv} function should take care of this.
2023 But how should the program proceed from here on?  If it tries to convert 
2024 to character set @math{@cal{B}}, first the two @code{iconv_open}
2025 calls
2027 @smallexample
2028 cd1 = iconv_open ("@math{@cal{B}}", "@math{@cal{A}}");
2029 @end smallexample
2031 @noindent
2034 @smallexample
2035 cd2 = iconv_open ("@math{@cal{C}}", "@math{@cal{B}}");
2036 @end smallexample
2038 @noindent
2039 will succeed, but how to find @math{@cal{B}}?
2041 Unfortunately, the answer is: there is no general solution.  On some
2042 systems guessing might help.  On those systems most character sets can
2043 convert to and from UTF-8 encoded @w{ISO 10646} or Unicode text. Beside 
2044 this only some very system-specific methods can help.  Since the 
2045 conversion functions come from loadable modules and these modules must
2046 be stored somewhere in the filesystem, one @emph{could} try to find them
2047 and determine from the available file which conversions are available
2048 and whether there is an indirect route from @math{@cal{A}} to
2049 @math{@cal{C}}.
2051 This example shows one of the design errors of @code{iconv} mentioned 
2052 above.  It should at least be possible to determine the list of available
2053 conversion programmatically so that if @code{iconv_open} says there is no 
2054 such conversion, one could make sure this also is true for indirect
2055 routes.
2057 @node glibc iconv Implementation
2058 @subsection The @code{iconv} Implementation in the GNU C library
2060 After reading about the problems of @code{iconv} implementations in the
2061 last section it is certainly good to note that the implementation in
2062 the GNU C library has none of the problems mentioned above.  What
2063 follows is a step-by-step analysis of the points raised above.  The
2064 evaluation is based on the current state of the development (as of
2065 January 1999).  The development of the @code{iconv} functions is not
2066 complete, but basic functionality has solidified.
2068 The GNU C library's @code{iconv} implementation uses shared loadable
2069 modules to implement the conversions.  A very small number of
2070 conversions are built into the library itself but these are only rather
2071 trivial conversions.
2073 All the benefits of loadable modules are available in the GNU C library
2074 implementation.  This is especially appealing since the interface is
2075 well documented (see below), and it, therefore, is easy to write new
2076 conversion modules.  The drawback of using loadable objects is not a
2077 problem in the GNU C library, at least on ELF systems.  Since the
2078 library is able to load shared objects even in statically linked
2079 binaries, static linking need not be forbidden in case one wants to use 
2080 @code{iconv}.
2082 The second mentioned problem is the number of supported conversions.
2083 Currently, the GNU C library supports more than 150 character sets.  The
2084 way the implementation is designed the number of supported conversions
2085 is greater than 22350 (@math{150} times @math{149}).  If any conversion
2086 from or to a character set is missing, it can be added easily.
2088 Particularly impressive as it may be, this high number is due to the
2089 fact that the GNU C library implementation of @code{iconv} does not have
2090 the third problem mentioned above (i.e., whenever there is a conversion
2091 from a character set @math{@cal{A}} to @math{@cal{B}} and from
2092 @math{@cal{B}} to @math{@cal{C}} it is always possible to convert from
2093 @math{@cal{A}} to @math{@cal{C}} directly).  If the @code{iconv_open}
2094 returns an error and sets @code{errno} to @code{EINVAL}, there is no 
2095 known way, directly or indirectly, to perform the wanted conversion.
2097 @cindex triangulation
2098 Triangulation is achieved by providing for each character set a 
2099 conversion from and to UCS-4 encoded @w{ISO 10646}.  Using @w{ISO 10646} 
2100 as an intermediate representation it is possible to @dfn{triangulate}
2101 (i.e., convert with an intermediate representation).
2103 There is no inherent requirement to provide a conversion to @w{ISO
2104 10646} for a new character set, and it is also possible to provide other
2105 conversions where neither source nor destination character set is @w{ISO
2106 10646}.  The existing set of conversions is simply meant to cover all 
2107 conversions that might be of interest.
2109 @cindex ISO-2022-JP
2110 @cindex EUC-JP
2111 All currently available conversions use the triangulation method above,
2112 making conversion run unnecessarily slow.  If, for example, somebody 
2113 often needs the conversion from ISO-2022-JP to EUC-JP, a quicker solution
2114 would involve direct conversion between the two character sets, skipping
2115 the input to @w{ISO 10646} first.  The two character sets of interest
2116 are much more similar to each other than to @w{ISO 10646}.
2118 In such a situation one easily can write a new conversion and provide it
2119 as a better alternative.  The GNU C library @code{iconv} implementation
2120 would automatically use the module implementing the conversion if it is
2121 specified to be more efficient.
2123 @subsubsection Format of @file{gconv-modules} files
2125 All information about the available conversions comes from a file named
2126 @file{gconv-modules}, which can be found in any of the directories along
2127 the @code{GCONV_PATH}.  The @file{gconv-modules} files are line-oriented
2128 text files, where each of the lines has one of the following formats:
2130 @itemize @bullet
2131 @item
2132 If the first non-whitespace character is a @kbd{#} the line contains only 
2133 comments and is ignored.
2135 @item
2136 Lines starting with @code{alias} define an alias name for a character 
2137 set.  Two more words are expected on the line.  The first word 
2138 defines the alias name, and the second defines the original name of the
2139 character set.  The effect is that it is possible to use the alias name
2140 in the @var{fromset} or @var{toset} parameters of @code{iconv_open} and
2141 achieve the same result as when using the real character set name.
2143 This is quite important as a character set has often many different
2144 names.  There is normally an official name but this need not correspond to 
2145 the most popular name.  Beside this many character sets have special 
2146 names that are somehow constructed.  For example, all character sets 
2147 specified by the ISO have an alias of the form @code{ISO-IR-@var{nnn}} 
2148 where @var{nnn} is the registration number.  This allows programs that 
2149 know about the registration number to construct character set names and 
2150 use them in @code{iconv_open} calls.  More on the available names and 
2151 aliases follows below.
2153 @item
2154 Lines starting with @code{module} introduce an available conversion
2155 module.  These lines must contain three or four more words.
2157 The first word specifies the source character set, the second word the
2158 destination character set of conversion implemented in this module, and 
2159 the third word is the name of the loadable module.  The filename is
2160 constructed by appending the usual shared object suffix (normally
2161 @file{.so}) and this file is then supposed to be found in the same
2162 directory the @file{gconv-modules} file is in.  The last word on the line, 
2163 which is optional, is a numeric value representing the cost of the
2164 conversion.  If this word is missing, a cost of @math{1} is assumed.  The
2165 numeric value itself does not matter that much; what counts are the
2166 relative values of the sums of costs for all possible conversion paths.
2167 Below is a more precise description of the use of the cost value.
2168 @end itemize
2170 Returning to the example above where one has written a module to directly
2171 convert from ISO-2022-JP to EUC-JP and back.  All that has to be done is
2172 to put the new module, let its name be ISO2022JP-EUCJP.so, in a directory
2173 and add a file @file{gconv-modules} with the following content in the
2174 same directory:
2176 @smallexample
2177 module  ISO-2022-JP//   EUC-JP//        ISO2022JP-EUCJP    1
2178 module  EUC-JP//        ISO-2022-JP//   ISO2022JP-EUCJP    1
2179 @end smallexample
2181 To see why this is sufficient, it is necessary to understand how the
2182 conversion used by @code{iconv} (and described in the descriptor) is
2183 selected.  The approach to this problem is quite simple.
2185 At the first call of the @code{iconv_open} function the program reads
2186 all available @file{gconv-modules} files and builds up two tables: one
2187 containing all the known aliases and another that contains the
2188 information about the conversions and which shared object implements
2189 them.
2191 @subsubsection Finding the conversion path in @code{iconv}
2193 The set of available conversions form a directed graph with weighted
2194 edges.  The weights on the edges are the costs specified in the
2195 @file{gconv-modules} files.  The @code{iconv_open} function uses an
2196 algorithm suitable for search for the best path in such a graph and so
2197 constructs a list of conversions that must be performed in succession
2198 to get the transformation from the source to the destination character
2199 set.
2201 Explaining why the above @file{gconv-modules} files allows the
2202 @code{iconv} implementation to resolve the specific ISO-2022-JP to
2203 EUC-JP conversion module instead of the conversion coming with the
2204 library itself is straightforward.  Since the latter conversion takes two
2205 steps (from ISO-2022-JP to @w{ISO 10646} and then from @w{ISO 10646} to
2206 EUC-JP), the cost is @math{1+1 = 2}.  The above @file{gconv-modules}
2207 file, however, specifies that the new conversion modules can perform this
2208 conversion with only the cost of @math{1}.
2210 A mysterious item about the @file{gconv-modules} file above (and also
2211 the file coming with the GNU C library) are the names of the character
2212 sets specified in the @code{module} lines.  Why do almost all the names
2213 end in @code{//}?  And this is not all: the names can actually be
2214 regular expressions.  At this point in time this mystery should not be
2215 revealed, unless you have the relevant spell-casting materials: ashes
2216 from an original @w{DOS 6.2} boot disk burnt in effigy, a crucifix
2217 blessed by St.@: Emacs, assorted herbal roots from Central America, sand
2218 from Cebu, etc.  Sorry!  @strong{The part of the implementation where
2219 this is used is not yet finished.  For now please simply follow the
2220 existing examples.  It'll become clearer once it is. --drepper}
2222 A last remark about the @file{gconv-modules} is about the names not
2223 ending with @code{//}.  A character set named @code{INTERNAL} is often 
2224 mentioned.  From the discussion above and the chosen name it should have 
2225 become clear that this is the name for the representation used in the 
2226 intermediate step of the triangulation.  We have said that this is UCS-4 
2227 but actually that is not quite right.  The UCS-4 specification also 
2228 includes the specification of the byte ordering used.  Since a UCS-4 value 
2229 consists of four bytes, a stored value is effected by byte ordering.  The 
2230 internal representation is @emph{not} the same as UCS-4 in case the byte 
2231 ordering of the processor (or at least the running process) is not the 
2232 same as the one required for UCS-4.  This is done for performance reasons 
2233 as one does not want to perform unnecessary byte-swapping operations if 
2234 one is not interested in actually seeing the result in UCS-4.  To avoid 
2235 trouble with endianess, the internal representation consistently is named 
2236 @code{INTERNAL} even on big-endian systems where the representations are 
2237 identical.
2239 @subsubsection @code{iconv} module data structures
2241 So far this section has described how modules are located and considered 
2242 to be used.  What remains to be described is the interface of the modules
2243 so that one can write new ones. This section describes the interface as
2244 it is in use in January 1999.  The interface will change a bit in the 
2245 future but, with luck, only in an upwardly compatible way.
2247 The definitions necessary to write new modules are publicly available
2248 in the non-standard header @file{gconv.h}.  The following text,
2249 therefore, describes the definitions from this header file.  First, 
2250 however, it is necessary to get an overview.
2252 From the perspective of the user of @code{iconv} the interface is quite
2253 simple: the @code{iconv_open} function returns a handle that can be used 
2254 in calls to @code{iconv}, and finally the handle is freed with a call to 
2255 @code{iconv_close}.  The problem is that the handle has to be able to
2256 represent the possibly long sequences of conversion steps and also the
2257 state of each conversion since the handle is all that is passed to the
2258 @code{iconv} function.  Therefore, the data structures are really the
2259 elements necessary to understanding the implementation.
2261 We need two different kinds of data structures.  The first describes the
2262 conversion and the second describes the state etc.  There are really two
2263 type definitions like this in @file{gconv.h}.
2264 @pindex gconv.h
2266 @comment gconv.h
2267 @comment GNU
2268 @deftp {Data type} {struct __gconv_step}
2269 This data structure describes one conversion a module can perform.  For
2270 each function in a loaded module with conversion functions there is
2271 exactly one object of this type.  This object is shared by all users of
2272 the conversion (i.e., this object does not contain any information
2273 corresponding to an actual conversion; it only describes the conversion
2274 itself).
2276 @table @code
2277 @item struct __gconv_loaded_object *__shlib_handle
2278 @itemx const char *__modname
2279 @itemx int __counter
2280 All these elements of the structure are used internally in the C library
2281 to coordinate loading and unloading the shared.  One must not expect any
2282 of the other elements to be available or initialized.
2284 @item const char *__from_name
2285 @itemx const char *__to_name
2286 @code{__from_name} and @code{__to_name} contain the names of the source and
2287 destination character sets.  They can be used to identify the actual
2288 conversion to be carried out since one module might implement conversions 
2289 for more than one character set and/or direction.
2291 @item gconv_fct __fct
2292 @itemx gconv_init_fct __init_fct
2293 @itemx gconv_end_fct __end_fct
2294 These elements contain pointers to the functions in the loadable module.
2295 The interface will be explained below.
2297 @item int __min_needed_from
2298 @itemx int __max_needed_from
2299 @itemx int __min_needed_to
2300 @itemx int __max_needed_to;
2301 These values have to be supplied in the init function of the module.  The
2302 @code{__min_needed_from} value specifies how many bytes a character of
2303 the source character set at least needs.  The @code{__max_needed_from}
2304 specifies the maximum value that also includes possible shift sequences.
2306 The @code{__min_needed_to} and @code{__max_needed_to} values serve the
2307 same purpose as @code{__min_needed_from} and @code{__max_needed_from} but 
2308 this time for the destination character set.
2310 It is crucial that these values be accurate since otherwise the
2311 conversion functions will have problems or not work at all.
2313 @item int __stateful
2314 This element must also be initialized by the init function. 
2315 @code{int __stateful} is nonzero if the source character set is stateful. 
2316 Otherwise it is zero.
2318 @item void *__data
2319 This element can be used freely by the conversion functions in the
2320 module.  @code{void *__data} can be used to communicate extra information 
2321 from one call to another.  @code{void *__data} need not be initialized if 
2322 not needed at all.  If @code{void *__data} element is assigned a pointer 
2323 to dynamically allocated memory (presumably in the init function) it has 
2324 to be made sure that the end function deallocates the memory.  Otherwise 
2325 the application will leak memory.
2327 It is important to be aware that this data structure is shared by all
2328 users of this specification conversion and therefore the @code{__data}
2329 element must not contain data specific to one specific use of the
2330 conversion function.
2331 @end table
2332 @end deftp
2334 @comment gconv.h
2335 @comment GNU
2336 @deftp {Data type} {struct __gconv_step_data}
2337 This is the data structure that contains the information specific to
2338 each use of the conversion functions.
2341 @table @code
2342 @item char *__outbuf
2343 @itemx char *__outbufend
2344 These elements specify the output buffer for the conversion step.  The
2345 @code{__outbuf} element points to the beginning of the buffer, and
2346 @code{__outbufend} points to the byte following the last byte in the
2347 buffer.  The conversion function must not assume anything about the size
2348 of the buffer but it can be safely assumed the there is room for at
2349 least one complete character in the output buffer.
2351 Once the conversion is finished, if the conversion is the last step, the
2352 @code{__outbuf} element must be modified to point after the last byte
2353 written into the buffer to signal how much output is available.  If this
2354 conversion step is not the last one, the element must not be modified.
2355 The @code{__outbufend} element must not be modified.
2357 @item int __is_last
2358 This element is nonzero if this conversion step is the last one.  This
2359 information is necessary for the recursion.  See the description of the
2360 conversion function internals below.  This element must never be
2361 modified.
2363 @item int __invocation_counter
2364 The conversion function can use this element to see how many calls of 
2365 the conversion function already happened.  Some character sets require a 
2366 certain prolog when generating output, and by comparing this value with
2367 zero, one can find out whether it is the first call and whether, 
2368 therefore, the prolog should be emitted.  This element must never be 
2369 modified.
2371 @item int __internal_use
2372 This element is another one rarely used but needed in certain
2373 situations.  It is assigned a nonzero value in case the conversion
2374 functions are used to implement @code{mbsrtowcs} et.al.@: (i.e., the
2375 function is not used directly through the @code{iconv} interface).
2377 This sometimes makes a difference as it is expected that the
2378 @code{iconv} functions are used to translate entire texts while the
2379 @code{mbsrtowcs} functions are normally used only to convert single
2380 strings and might be used multiple times to convert entire texts.
2382 But in this situation we would have problem complying with some rules of
2383 the character set specification.  Some character sets require a prolog,
2384 which must appear exactly once for an entire text.  If a number of
2385 @code{mbsrtowcs} calls are used to convert the text, only the first call
2386 must add the prolog.  However, because there is no communication between the
2387 different calls of @code{mbsrtowcs}, the conversion functions have no
2388 possibility to find this out.  The situation is different for sequences
2389 of @code{iconv} calls since the handle allows access to the needed
2390 information.
2392 The @code{int __internal_use} element is mostly used together with 
2393 @code{__invocation_counter} as follows:
2395 @smallexample
2396 if (!data->__internal_use
2397      && data->__invocation_counter == 0)
2398   /* @r{Emit prolog.}  */
2399   ...
2400 @end smallexample
2402 This element must never be modified.
2404 @item mbstate_t *__statep
2405 The @code{__statep} element points to an object of type @code{mbstate_t}
2406 (@pxref{Keeping the state}).  The conversion of a stateful character
2407 set must use the object pointed to by @code{__statep} to store 
2408 information about the conversion state.  The @code{__statep} element 
2409 itself must never be modified.
2411 @item mbstate_t __state
2412 This element must @emph{never} be used directly.  It is only part of
2413 this structure to have the needed space allocated.
2414 @end table
2415 @end deftp
2417 @subsubsection @code{iconv} module interfaces
2419 With the knowledge about the data structures we now can describe the
2420 conversion function itself.  To understand the interface a bit of
2421 knowledge is necessary about the functionality in the C library that 
2422 loads the objects with the conversions.
2424 It is often the case that one conversion is used more than once (i.e.,
2425 there are several @code{iconv_open} calls for the same set of character
2426 sets during one program run).  The @code{mbsrtowcs} et.al.@: functions in
2427 the GNU C library also use the @code{iconv} functionality, which 
2428 increases the number of uses of the same functions even more.
2430 Because of this multiple use of conversions, the modules do not get 
2431 loaded exclusively for one conversion.  Instead a module once loaded can 
2432 be used by an arbitrary number of @code{iconv} or @code{mbsrtowcs} calls 
2433 at the same time.  The splitting of the information between conversion-
2434 function-specific information and conversion data makes this possible. 
2435 The last section showed the two data structures used to do this.
2437 This is of course also reflected in the interface and semantics of the
2438 functions that the modules must provide.  There are three functions that
2439 must have the following names:
2441 @table @code
2442 @item gconv_init
2443 The @code{gconv_init} function initializes the conversion function
2444 specific data structure.  This very same object is shared by all
2445 conversions that use this conversion and, therefore, no state information
2446 about the conversion itself must be stored in here.  If a module 
2447 implements more than one conversion, the @code{gconv_init} function will 
2448 be called multiple times.
2450 @item gconv_end
2451 The @code{gconv_end} function is responsible for freeing all resources
2452 allocated by the @code{gconv_init} function.  If there is nothing to do,
2453 this function can be missing.  Special care must be taken if the module
2454 implements more than one conversion and the @code{gconv_init} function
2455 does not allocate the same resources for all conversions.
2457 @item gconv
2458 This is the actual conversion function.  It is called to convert one
2459 block of text.  It gets passed the conversion step information
2460 initialized by @code{gconv_init} and the conversion data, specific to
2461 this use of the conversion functions.
2462 @end table
2464 There are three data types defined for the three module interface
2465 functions and these define the interface.
2467 @comment gconv.h
2468 @comment GNU
2469 @deftypevr {Data type} int {(*__gconv_init_fct)} (struct __gconv_step *)
2470 This specifies the interface of the initialization function of the
2471 module.  It is called exactly once for each conversion the module
2472 implements.
2474 As explained in the description of the @code{struct __gconv_step} data
2475 structure above the initialization function has to initialize parts of
2478 @table @code
2479 @item __min_needed_from
2480 @itemx __max_needed_from
2481 @itemx __min_needed_to
2482 @itemx __max_needed_to
2483 These elements must be initialized to the exact numbers of the minimum
2484 and maximum number of bytes used by one character in the source and
2485 destination character sets, respectively.  If the characters all have the
2486 same size, the minimum and maximum values are the same.
2488 @item __stateful
2489 This element must be initialized to an nonzero value if the source
2490 character set is stateful.  Otherwise it must be zero.
2491 @end table
2493 If the initialization function needs to communicate some information
2494 to the conversion function, this communication can happen using the 
2495 @code{__data} element of the @code{__gconv_step} structure.  But since 
2496 this data is shared by all the conversions, it must not be modified by 
2497 the conversion function.  The example below shows how this can be used.
2499 @smallexample
2500 #define MIN_NEEDED_FROM         1
2501 #define MAX_NEEDED_FROM         4
2502 #define MIN_NEEDED_TO           4
2503 #define MAX_NEEDED_TO           4
2506 gconv_init (struct __gconv_step *step)
2508   /* @r{Determine which direction.}  */
2509   struct iso2022jp_data *new_data;
2510   enum direction dir = illegal_dir;
2511   enum variant var = illegal_var;
2512   int result;
2514   if (__strcasecmp (step->__from_name, "ISO-2022-JP//") == 0)
2515     @{
2516       dir = from_iso2022jp;
2517       var = iso2022jp;
2518     @}
2519   else if (__strcasecmp (step->__to_name, "ISO-2022-JP//") == 0)
2520     @{
2521       dir = to_iso2022jp;
2522       var = iso2022jp;
2523     @}
2524   else if (__strcasecmp (step->__from_name, "ISO-2022-JP-2//") == 0)
2525     @{
2526       dir = from_iso2022jp;
2527       var = iso2022jp2;
2528     @}
2529   else if (__strcasecmp (step->__to_name, "ISO-2022-JP-2//") == 0)
2530     @{
2531       dir = to_iso2022jp;
2532       var = iso2022jp2;
2533     @}
2535   result = __GCONV_NOCONV;
2536   if (dir != illegal_dir)
2537     @{
2538       new_data = (struct iso2022jp_data *)
2539         malloc (sizeof (struct iso2022jp_data));
2541       result = __GCONV_NOMEM;
2542       if (new_data != NULL)
2543         @{
2544           new_data->dir = dir;
2545           new_data->var = var;
2546           step->__data = new_data;
2548           if (dir == from_iso2022jp)
2549             @{
2550               step->__min_needed_from = MIN_NEEDED_FROM;
2551               step->__max_needed_from = MAX_NEEDED_FROM;
2552               step->__min_needed_to = MIN_NEEDED_TO;
2553               step->__max_needed_to = MAX_NEEDED_TO;
2554             @}
2555           else
2556             @{
2557               step->__min_needed_from = MIN_NEEDED_TO;
2558               step->__max_needed_from = MAX_NEEDED_TO;
2559               step->__min_needed_to = MIN_NEEDED_FROM;
2560               step->__max_needed_to = MAX_NEEDED_FROM + 2;
2561             @}
2563           /* @r{Yes, this is a stateful encoding.}  */
2564           step->__stateful = 1;
2566           result = __GCONV_OK;
2567         @}
2568     @}
2570   return result;
2572 @end smallexample
2574 The function first checks which conversion is wanted.  The module from
2575 which this function is taken implements four different conversions; 
2576 which one is selected can be determined by comparing the names.  The
2577 comparison should always be done without paying attention to the case.
2579 Next, a data structure, which contains the necessary information about 
2580 which conversion is selected, is allocated.  The data structure
2581 @code{struct iso2022jp_data} is locally defined since, outside the 
2582 module, this data is not used at all.  Please note that if all four 
2583 conversions this modules supports are requested there are four data 
2584 blocks.
2586 One interesting thing is the initialization of the @code{__min_} and
2587 @code{__max_} elements of the step data object.  A single ISO-2022-JP
2588 character can consist of one to four bytes.  Therefore the
2589 @code{MIN_NEEDED_FROM} and @code{MAX_NEEDED_FROM} macros are defined
2590 this way.  The output is always the @code{INTERNAL} character set (aka
2591 UCS-4) and therefore each character consists of exactly four bytes.  For
2592 the conversion from @code{INTERNAL} to ISO-2022-JP we have to take into
2593 account that escape sequences might be necessary to switch the character
2594 sets.  Therefore the @code{__max_needed_to} element for this direction
2595 gets assigned @code{MAX_NEEDED_FROM + 2}.  This takes into account the
2596 two bytes needed for the escape sequences to single the switching.  The
2597 asymmetry in the maximum values for the two directions can be explained
2598 easily: when reading ISO-2022-JP text, escape sequences can be handled
2599 alone (i.e., it is not necessary to process a real character since the
2600 effect of the escape sequence can be recorded in the state information).
2601 The situation is different for the other direction.  Since it is in
2602 general not known which character comes next, one cannot emit escape
2603 sequences to change the state in advance.  This means the escape
2604 sequences that have to be emitted together with the next character.
2605 Therefore one needs more room than only for the character itself.
2607 The possible return values of the initialization function are:
2609 @table @code
2610 @item __GCONV_OK
2611 The initialization succeeded
2612 @item __GCONV_NOCONV
2613 The requested conversion is not supported in the module.  This can
2614 happen if the @file{gconv-modules} file has errors.
2615 @item __GCONV_NOMEM
2616 Memory required to store additional information could not be allocated.
2617 @end table
2618 @end deftypevr
2620 The function called before the module is unloaded is significantly
2621 easier.  It often has nothing at all to do; in which case it can be left
2622 out completely.
2624 @comment gconv.h
2625 @comment GNU
2626 @deftypevr {Data type} void {(*__gconv_end_fct)} (struct gconv_step *)
2627 The task of this function is to free all resources allocated in the
2628 initialization function.  Therefore only the @code{__data} element of
2629 the object pointed to by the argument is of interest.  Continuing the
2630 example from the initialization function, the finalization function
2631 looks like this:
2633 @smallexample
2634 void
2635 gconv_end (struct __gconv_step *data)
2637   free (data->__data);
2639 @end smallexample
2640 @end deftypevr
2642 The most important function is the conversion function itself, which can
2643 get quite complicated for complex character sets.  But since this is not
2644 of interest here, we will only describe a possible skeleton for the
2645 conversion function.
2647 @comment gconv.h
2648 @comment GNU
2649 @deftypevr {Data type} int {(*__gconv_fct)} (struct __gconv_step *, struct __gconv_step_data *, const char **, const char *, size_t *, int)
2650 The conversion function can be called for two basic reason: to convert
2651 text or to reset the state.  From the description of the @code{iconv}
2652 function it can be seen why the flushing mode is necessary.  What mode
2653 is selected is determined by the sixth argument, an integer.  This 
2654 argument being nonzero means that flushing is selected.
2656 Common to both modes is where the output buffer can be found.  The
2657 information about this buffer is stored in the conversion step data.  A
2658 pointer to this information is passed as the second argument to this 
2659 function.  The description of the @code{struct __gconv_step_data} 
2660 structure has more information on the conversion step data.
2662 @cindex stateful
2663 What has to be done for flushing depends on the source character set.
2664 If the source character set is not stateful, nothing has to be done. 
2665 Otherwise the function has to emit a byte sequence to bring the state 
2666 object into the initial state.  Once this all happened the other 
2667 conversion modules in the chain of conversions have to get the same 
2668 chance.  Whether another step follows can be determined from the 
2669 @code{__is_last} element of the step data structure to which the first 
2670 parameter points.
2672 The more interesting mode is when actual text has to be converted.  The 
2673 first step in this case is to convert as much text as possible from the 
2674 input buffer and store the result in the output buffer.  The start of the 
2675 input buffer is determined by the third argument, which is a pointer to a 
2676 pointer variable referencing the beginning of the buffer.  The fourth 
2677 argument is a pointer to the byte right after the last byte in the buffer.
2679 The conversion has to be performed according to the current state if the
2680 character set is stateful.  The state is stored in an object pointed to
2681 by the @code{__statep} element of the step data (second argument).  Once
2682 either the input buffer is empty or the output buffer is full the
2683 conversion stops.  At this point, the pointer variable referenced by the
2684 third parameter must point to the byte following the last processed
2685 byte (i.e., if all of the input is consumed, this pointer and the fourth
2686 parameter have the same value).
2688 What now happens depends on whether this step is the last one.  If it is 
2689 the last step, the only thing that has to be done is to update the 
2690 @code{__outbuf} element of the step data structure to point after the
2691 last written byte.  This update gives the caller the information on how 
2692 much text is available in the output buffer.  In addition, the variable
2693 pointed to by the fifth parameter, which is of type @code{size_t}, must
2694 be incremented by the number of characters (@emph{not bytes}) that were
2695 converted in a non-reversible way.  Then, the function can return.
2697 In case the step is not the last one, the later conversion functions have
2698 to get a chance to do their work.  Therefore, the appropriate conversion
2699 function has to be called.  The information about the functions is
2700 stored in the conversion data structures, passed as the first parameter.
2701 This information and the step data are stored in arrays, so the next
2702 element in both cases can be found by simple pointer arithmetic:
2704 @smallexample
2706 gconv (struct __gconv_step *step, struct __gconv_step_data *data,
2707        const char **inbuf, const char *inbufend, size_t *written,
2708        int do_flush)
2710   struct __gconv_step *next_step = step + 1;
2711   struct __gconv_step_data *next_data = data + 1;
2712   ...
2713 @end smallexample
2715 The @code{next_step} pointer references the next step information and
2716 @code{next_data} the next data record.  The call of the next function
2717 therefore will look similar to this:
2719 @smallexample
2720   next_step->__fct (next_step, next_data, &outerr, outbuf,
2721                     written, 0)
2722 @end smallexample
2724 But this is not yet all.  Once the function call returns the conversion
2725 function might have some more to do.  If the return value of the function 
2726 is @code{__GCONV_EMPTY_INPUT}, more room is available in the output 
2727 buffer.  Unless the input buffer is empty the conversion, functions start 
2728 all over again and process the rest of the input buffer.  If the return 
2729 value is not @code{__GCONV_EMPTY_INPUT}, something went wrong and we have 
2730 to recover from this.
2732 A requirement for the conversion function is that the input buffer
2733 pointer (the third argument) always point to the last character that
2734 was put in converted form into the output buffer.  This is trivially
2735 true after the conversion performed in the current step, but if the
2736 conversion functions deeper downstream stop prematurely, not all
2737 characters from the output buffer are consumed and, therefore, the input
2738 buffer pointers must be backed off to the right position.
2740 Correcting the input buffers is easy to do if the input and output 
2741 character sets have a fixed width for all characters.  In this situation 
2742 we can compute how many characters are left in the output buffer and, 
2743 therefore, can correct the input buffer pointer appropriately with a 
2744 similar computation.  Things are getting tricky if either character set 
2745 has characters represented with variable length byte sequences, and it 
2746 gets even more complicated if the conversion has to take care of the 
2747 state.  In these cases the conversion has to be performed once again, from 
2748 the known state before the initial conversion (i.e., if necessary the 
2749 state of the conversion has to be reset and the conversion loop has to be 
2750 executed again).  The difference now is that it is known how much input 
2751 must be created, and the conversion can stop before converting the first 
2752 unused character.  Once this is done the input buffer pointers must be 
2753 updated again and the function can return.
2755 One final thing should be mentioned.  If it is necessary for the
2756 conversion to know whether it is the first invocation (in case a prolog
2757 has to be emitted), the conversion function should increment the 
2758 @code{__invocation_counter} element of the step data structure just 
2759 before returning to the caller.  See the description of the @code{struct
2760 __gconv_step_data} structure above for more information on how this can
2761 be used.
2763 The return value must be one of the following values:
2765 @table @code
2766 @item __GCONV_EMPTY_INPUT
2767 All input was consumed and there is room left in the output buffer.
2768 @item __GCONV_FULL_OUTPUT
2769 No more room in the output buffer.  In case this is not the last step
2770 this value is propagated down from the call of the next conversion
2771 function in the chain. 
2772 @item __GCONV_INCOMPLETE_INPUT
2773 The input buffer is not entirely empty since it contains an incomplete
2774 character sequence.
2775 @end table
2777 The following example provides a framework for a conversion function.
2778 In case a new conversion has to be written the holes in this
2779 implementation have to be filled and that is it.
2781 @smallexample
2783 gconv (struct __gconv_step *step, struct __gconv_step_data *data,
2784        const char **inbuf, const char *inbufend, size_t *written,
2785        int do_flush)
2787   struct __gconv_step *next_step = step + 1;
2788   struct __gconv_step_data *next_data = data + 1;
2789   gconv_fct fct = next_step->__fct;
2790   int status;
2792   /* @r{If the function is called with no input this means we have}
2793      @r{to reset to the initial state.  The possibly partly}
2794      @r{converted input is dropped.}  */
2795   if (do_flush)
2796     @{
2797       status = __GCONV_OK;
2799       /* @r{Possible emit a byte sequence which put the state object}
2800          @r{into the initial state.}  */
2802       /* @r{Call the steps down the chain if there are any but only}
2803          @r{if we successfully emitted the escape sequence.}  */
2804       if (status == __GCONV_OK && ! data->__is_last)
2805         status = fct (next_step, next_data, NULL, NULL,
2806                       written, 1);
2807     @}
2808   else
2809     @{
2810       /* @r{We preserve the initial values of the pointer variables.}  */
2811       const char *inptr = *inbuf;
2812       char *outbuf = data->__outbuf;
2813       char *outend = data->__outbufend;
2814       char *outptr;
2816       do
2817         @{
2818           /* @r{Remember the start value for this round.}  */
2819           inptr = *inbuf;
2820           /* @r{The outbuf buffer is empty.}  */
2821           outptr = outbuf;
2823           /* @r{For stateful encodings the state must be safe here.}  */
2825           /* @r{Run the conversion loop.  @code{status} is set}
2826              @r{appropriately afterwards.}  */
2828           /* @r{If this is the last step, leave the loop. There is}
2829              @r{nothing we can do.}  */
2830           if (data->__is_last)
2831             @{
2832               /* @r{Store information about how many bytes are}
2833                  @r{available.}  */
2834               data->__outbuf = outbuf;
2836              /* @r{If any non-reversible conversions were performed,}
2837                 @r{add the number to @code{*written}.}  */
2839              break;
2840            @}
2842           /* @r{Write out all output that was produced.}  */
2843           if (outbuf > outptr)
2844             @{
2845               const char *outerr = data->__outbuf;
2846               int result;
2848               result = fct (next_step, next_data, &outerr,
2849                             outbuf, written, 0);
2851               if (result != __GCONV_EMPTY_INPUT)
2852                 @{
2853                   if (outerr != outbuf)
2854                     @{
2855                       /* @r{Reset the input buffer pointer.  We}
2856                          @r{document here the complex case.}  */
2857                       size_t nstatus;
2859                       /* @r{Reload the pointers.}  */
2860                       *inbuf = inptr;
2861                       outbuf = outptr;
2863                       /* @r{Possibly reset the state.}  */
2865                       /* @r{Redo the conversion, but this time}
2866                          @r{the end of the output buffer is at}
2867                          @r{@code{outerr}.}  */
2868                     @}
2870                   /* @r{Change the status.}  */
2871                   status = result;
2872                 @}
2873               else
2874                 /* @r{All the output is consumed, we can make}
2875                    @r{ another run if everything was ok.}  */
2876                 if (status == __GCONV_FULL_OUTPUT)
2877                   status = __GCONV_OK;
2878            @}
2879         @}
2880       while (status == __GCONV_OK);
2882       /* @r{We finished one use of this step.}  */
2883       ++data->__invocation_counter;
2884     @}
2886   return status;
2888 @end smallexample
2889 @end deftypevr
2891 This information should be sufficient to write new modules.  Anybody
2892 doing so should also take a look at the available source code in the GNU
2893 C library sources.  It contains many examples of working and optimized
2894 modules.
2896 @c File charset.texi edited October 2001 by Dennis Grace, IBM Corporation