Remove powerpc, sparc fdim inlines (bug 22987).
[glibc.git] / manual / charset.texi
blob1867ace48589d2d023589e77515958104445cdde
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 are 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 @deftp {Data type} wchar_t
102 @standards{ISO, stddef.h}
103 This data type is used as the base type for wide character strings.
104 In other words, arrays of objects of this type are the equivalent of
105 @code{char[]} for multibyte character strings.  The type is defined in
106 @file{stddef.h}.
108 The @w{ISO C90} standard, where @code{wchar_t} was introduced, does not
109 say anything specific about the representation.  It only requires that
110 this type is capable of storing all elements of the basic character set.
111 Therefore it would be legitimate to define @code{wchar_t} as @code{char},
112 which might make sense for embedded systems.
114 But in @theglibc{} @code{wchar_t} is always 32 bits wide and, therefore,
115 capable of representing all UCS-4 values and, therefore, covering all of
116 @w{ISO 10646}.  Some Unix systems define @code{wchar_t} as a 16-bit type
117 and thereby follow Unicode very strictly.  This definition is perfectly
118 fine with the standard, but it also means that to represent all
119 characters from Unicode and @w{ISO 10646} one has to use UTF-16 surrogate
120 characters, which is in fact a multi-wide-character encoding.  But
121 resorting to multi-wide-character encoding contradicts the purpose of the
122 @code{wchar_t} type.
123 @end deftp
125 @deftp {Data type} wint_t
126 @standards{ISO, wchar.h}
127 @code{wint_t} is a data type used for parameters and variables that
128 contain a single wide character.  As the name suggests this type is the
129 equivalent of @code{int} when using the normal @code{char} strings.  The
130 types @code{wchar_t} and @code{wint_t} often have the same
131 representation if their size is 32 bits wide but if @code{wchar_t} is
132 defined as @code{char} the type @code{wint_t} must be defined as
133 @code{int} due to the parameter promotion.
135 @pindex wchar.h
136 This type is defined in @file{wchar.h} and was introduced in
137 @w{Amendment 1} to @w{ISO C90}.
138 @end deftp
140 As there are for the @code{char} data type macros are available for
141 specifying the minimum and maximum value representable in an object of
142 type @code{wchar_t}.
144 @deftypevr Macro wint_t WCHAR_MIN
145 @standards{ISO, wchar.h}
146 The macro @code{WCHAR_MIN} evaluates to the minimum value representable
147 by an object of type @code{wint_t}.
149 This macro was introduced in @w{Amendment 1} to @w{ISO C90}.
150 @end deftypevr
152 @deftypevr Macro wint_t WCHAR_MAX
153 @standards{ISO, wchar.h}
154 The macro @code{WCHAR_MAX} evaluates to the maximum value representable
155 by an object of type @code{wint_t}.
157 This macro was introduced in @w{Amendment 1} to @w{ISO C90}.
158 @end deftypevr
160 Another special wide character value is the equivalent to @code{EOF}.
162 @deftypevr Macro wint_t WEOF
163 @standards{ISO, wchar.h}
164 The macro @code{WEOF} evaluates to a constant expression of type
165 @code{wint_t} whose value is different from any member of the extended
166 character set.
168 @code{WEOF} need not be the same value as @code{EOF} and unlike
169 @code{EOF} it also need @emph{not} be negative.  In other words, sloppy
170 code like
172 @smallexample
174   int c;
175   @dots{}
176   while ((c = getc (fp)) < 0)
177     @dots{}
179 @end smallexample
181 @noindent
182 has to be rewritten to use @code{WEOF} explicitly when wide characters
183 are used:
185 @smallexample
187   wint_t c;
188   @dots{}
189   while ((c = wgetc (fp)) != WEOF)
190     @dots{}
192 @end smallexample
194 @pindex wchar.h
195 This macro was introduced in @w{Amendment 1} to @w{ISO C90} and is
196 defined in @file{wchar.h}.
197 @end deftypevr
200 These internal representations present problems when it comes to storage
201 and transmittal.  Because each single wide character consists of more
202 than one byte, they are affected by byte-ordering.  Thus, machines with
203 different endianesses would see different values when accessing the same
204 data.  This byte ordering concern also applies for communication protocols
205 that are all byte-based and therefore require that the sender has to
206 decide about splitting the wide character in bytes.  A last (but not least
207 important) point is that wide characters often require more storage space
208 than a customized byte-oriented character set.
210 @cindex multibyte character
211 @cindex EBCDIC
212 For all the above reasons, an external encoding that is different from
213 the internal encoding is often used if the latter is UCS-2 or UCS-4.
214 The external encoding is byte-based and can be chosen appropriately for
215 the environment and for the texts to be handled.  A variety of different
216 character sets can be used for this external encoding (information that
217 will not be exhaustively presented here--instead, a description of the
218 major groups will suffice).  All of the ASCII-based character sets
219 fulfill one requirement: they are "filesystem safe."  This means that
220 the character @code{'/'} is used in the encoding @emph{only} to
221 represent itself.  Things are a bit different for character sets like
222 EBCDIC (Extended Binary Coded Decimal Interchange Code, a character set
223 family used by IBM), but if the operating system does not understand
224 EBCDIC directly the parameters-to-system calls have to be converted
225 first anyhow.
227 @itemize @bullet
228 @item
229 The simplest character sets are single-byte character sets.  There can
230 be only up to 256 characters (for @w{8 bit} character sets), which is
231 not sufficient to cover all languages but might be sufficient to handle
232 a specific text.  Handling of a @w{8 bit} character sets is simple.  This
233 is not true for other kinds presented later, and therefore, the
234 application one uses might require the use of @w{8 bit} character sets.
236 @cindex ISO 2022
237 @item
238 The @w{ISO 2022} standard defines a mechanism for extended character
239 sets where one character @emph{can} be represented by more than one
240 byte.  This is achieved by associating a state with the text.
241 Characters that can be used to change the state can be embedded in the
242 text.  Each byte in the text might have a different interpretation in each
243 state.  The state might even influence whether a given byte stands for a
244 character on its own or whether it has to be combined with some more
245 bytes.
247 @cindex EUC
248 @cindex Shift_JIS
249 @cindex SJIS
250 In most uses of @w{ISO 2022} the defined character sets do not allow
251 state changes that cover more than the next character.  This has the
252 big advantage that whenever one can identify the beginning of the byte
253 sequence of a character one can interpret a text correctly.  Examples of
254 character sets using this policy are the various EUC character sets
255 (used by Sun's operating systems, EUC-JP, EUC-KR, EUC-TW, and EUC-CN)
256 or Shift_JIS (SJIS, a Japanese encoding).
258 But there are also character sets using a state that is valid for more
259 than one character and has to be changed by another byte sequence.
260 Examples for this are ISO-2022-JP, ISO-2022-KR, and ISO-2022-CN.
262 @item
263 @cindex ISO 6937
264 Early attempts to fix 8 bit character sets for other languages using the
265 Roman alphabet lead to character sets like @w{ISO 6937}.  Here bytes
266 representing characters like the acute accent do not produce output
267 themselves: one has to combine them with other characters to get the
268 desired result.  For example, the byte sequence @code{0xc2 0x61}
269 (non-spacing acute accent, followed by lower-case `a') to get the ``small
270 a with  acute'' character.  To get the acute accent character on its own,
271 one has to write @code{0xc2 0x20} (the non-spacing acute followed by a
272 space).
274 Character sets like @w{ISO 6937} are used in some embedded systems such
275 as teletex.
277 @item
278 @cindex UTF-8
279 Instead of converting the Unicode or @w{ISO 10646} text used internally,
280 it is often also sufficient to simply use an encoding different than
281 UCS-2/UCS-4.  The Unicode and @w{ISO 10646} standards even specify such an
282 encoding: UTF-8.  This encoding is able to represent all of @w{ISO
283 10646} 31 bits in a byte string of length one to six.
285 @cindex UTF-7
286 There were a few other attempts to encode @w{ISO 10646} such as UTF-7,
287 but UTF-8 is today the only encoding that should be used.  In fact, with
288 any luck UTF-8 will soon be the only external encoding that has to be
289 supported.  It proves to be universally usable and its only disadvantage
290 is that it favors Roman languages by making the byte string
291 representation of other scripts (Cyrillic, Greek, Asian scripts) longer
292 than necessary if using a specific character set for these scripts.
293 Methods like the Unicode compression scheme can alleviate these
294 problems.
295 @end itemize
297 The question remaining is: how to select the character set or encoding
298 to use.  The answer: you cannot decide about it yourself, it is decided
299 by the developers of the system or the majority of the users.  Since the
300 goal is interoperability one has to use whatever the other people one
301 works with use.  If there are no constraints, the selection is based on
302 the requirements the expected circle of users will have.  In other words,
303 if a project is expected to be used in only, say, Russia it is fine to use
304 KOI8-R or a similar character set.  But if at the same time people from,
305 say, Greece are participating one should use a character set that allows
306 all people to collaborate.
308 The most widely useful solution seems to be: go with the most general
309 character set, namely @w{ISO 10646}.  Use UTF-8 as the external encoding
310 and problems about users not being able to use their own language
311 adequately are a thing of the past.
313 One final comment about the choice of the wide character representation
314 is necessary at this point.  We have said above that the natural choice
315 is using Unicode or @w{ISO 10646}.  This is not required, but at least
316 encouraged, by the @w{ISO C} standard.  The standard defines at least a
317 macro @code{__STDC_ISO_10646__} that is only defined on systems where
318 the @code{wchar_t} type encodes @w{ISO 10646} characters.  If this
319 symbol is not defined one should avoid making assumptions about the wide
320 character representation.  If the programmer uses only the functions
321 provided by the C library to handle wide character strings there should
322 be no compatibility problems with other systems.
324 @node Charset Function Overview
325 @section Overview about Character Handling Functions
327 A Unix @w{C library} contains three different sets of functions in two
328 families to handle character set conversion.  One of the function families
329 (the most commonly used) is specified in the @w{ISO C90} standard and,
330 therefore, is portable even beyond the Unix world.  Unfortunately this
331 family is the least useful one.  These functions should be avoided
332 whenever possible, especially when developing libraries (as opposed to
333 applications).
335 The second family of functions got introduced in the early Unix standards
336 (XPG2) and is still part of the latest and greatest Unix standard:
337 @w{Unix 98}.  It is also the most powerful and useful set of functions.
338 But we will start with the functions defined in @w{Amendment 1} to
339 @w{ISO C90}.
341 @node Restartable multibyte conversion
342 @section Restartable Multibyte Conversion Functions
344 The @w{ISO C} standard defines functions to convert strings from a
345 multibyte representation to wide character strings.  There are a number
346 of peculiarities:
348 @itemize @bullet
349 @item
350 The character set assumed for the multibyte encoding is not specified
351 as an argument to the functions.  Instead the character set specified by
352 the @code{LC_CTYPE} category of the current locale is used; see
353 @ref{Locale Categories}.
355 @item
356 The functions handling more than one character at a time require NUL
357 terminated strings as the argument (i.e., converting blocks of text
358 does not work unless one can add a NUL byte at an appropriate place).
359 @Theglibc{} contains some extensions to the standard that allow
360 specifying a size, but basically they also expect terminated strings.
361 @end itemize
363 Despite these limitations the @w{ISO C} functions can be used in many
364 contexts.  In graphical user interfaces, for instance, it is not
365 uncommon to have functions that require text to be displayed in a wide
366 character string if the text is not simple ASCII.  The text itself might
367 come from a file with translations and the user should decide about the
368 current locale, which determines the translation and therefore also the
369 external encoding used.  In such a situation (and many others) the
370 functions described here are perfect.  If more freedom while performing
371 the conversion is necessary take a look at the @code{iconv} functions
372 (@pxref{Generic Charset Conversion}).
374 @menu
375 * Selecting the Conversion::     Selecting the conversion and its properties.
376 * Keeping the state::            Representing the state of the conversion.
377 * Converting a Character::       Converting Single Characters.
378 * Converting Strings::           Converting Multibyte and Wide Character
379                                   Strings.
380 * Multibyte Conversion Example:: A Complete Multibyte Conversion Example.
381 @end menu
383 @node Selecting the Conversion
384 @subsection Selecting the conversion and its properties
386 We already said above that the currently selected locale for the
387 @code{LC_CTYPE} category decides the conversion that is performed
388 by the functions we are about to describe.  Each locale uses its own
389 character set (given as an argument to @code{localedef}) and this is the
390 one assumed as the external multibyte encoding.  The wide character
391 set is always UCS-4 in @theglibc{}.
393 A characteristic of each multibyte character set is the maximum number
394 of bytes that can be necessary to represent one character.  This
395 information is quite important when writing code that uses the
396 conversion functions (as shown in the examples below).
397 The @w{ISO C} standard defines two macros that provide this information.
400 @deftypevr Macro int MB_LEN_MAX
401 @standards{ISO, limits.h}
402 @code{MB_LEN_MAX} specifies the maximum number of bytes in the multibyte
403 sequence for a single character in any of the supported locales.  It is
404 a compile-time constant and is defined in @file{limits.h}.
405 @pindex limits.h
406 @end deftypevr
408 @deftypevr Macro int MB_CUR_MAX
409 @standards{ISO, stdlib.h}
410 @code{MB_CUR_MAX} expands into a positive integer expression that is the
411 maximum number of bytes in a multibyte character in the current locale.
412 The value is never greater than @code{MB_LEN_MAX}.  Unlike
413 @code{MB_LEN_MAX} this macro need not be a compile-time constant, and in
414 @theglibc{} it is not.
416 @pindex stdlib.h
417 @code{MB_CUR_MAX} is defined in @file{stdlib.h}.
418 @end deftypevr
420 Two different macros are necessary since strictly @w{ISO C90} compilers
421 do not allow variable length array definitions, but still it is desirable
422 to avoid dynamic allocation.  This incomplete piece of code shows the
423 problem:
425 @smallexample
427   char buf[MB_LEN_MAX];
428   ssize_t len = 0;
430   while (! feof (fp))
431     @{
432       fread (&buf[len], 1, MB_CUR_MAX - len, fp);
433       /* @r{@dots{} process} buf */
434       len -= used;
435     @}
437 @end smallexample
439 The code in the inner loop is expected to have always enough bytes in
440 the array @var{buf} to convert one multibyte character.  The array
441 @var{buf} has to be sized statically since many compilers do not allow a
442 variable size.  The @code{fread} call makes sure that @code{MB_CUR_MAX}
443 bytes are always available in @var{buf}.  Note that it isn't
444 a problem if @code{MB_CUR_MAX} is not a compile-time constant.
447 @node Keeping the state
448 @subsection Representing the state of the conversion
450 @cindex stateful
451 In the introduction of this chapter it was said that certain character
452 sets use a @dfn{stateful} encoding.  That is, the encoded values depend
453 in some way on the previous bytes in the text.
455 Since the conversion functions allow converting a text in more than one
456 step we must have a way to pass this information from one call of the
457 functions to another.
459 @deftp {Data type} mbstate_t
460 @standards{ISO, wchar.h}
461 @cindex shift state
462 A variable of type @code{mbstate_t} can contain all the information
463 about the @dfn{shift state} needed from one call to a conversion
464 function to another.
466 @pindex wchar.h
467 @code{mbstate_t} is defined in @file{wchar.h}.  It was introduced in
468 @w{Amendment 1} to @w{ISO C90}.
469 @end deftp
471 To use objects of type @code{mbstate_t} the programmer has to define such
472 objects (normally as local variables on the stack) and pass a pointer to
473 the object to the conversion functions.  This way the conversion function
474 can update the object if the current multibyte character set is stateful.
476 There is no specific function or initializer to put the state object in
477 any specific state.  The rules are that the object should always
478 represent the initial state before the first use, and this is achieved by
479 clearing the whole variable with code such as follows:
481 @smallexample
483   mbstate_t state;
484   memset (&state, '\0', sizeof (state));
485   /* @r{from now on @var{state} can be used.}  */
486   @dots{}
488 @end smallexample
490 When using the conversion functions to generate output it is often
491 necessary to test whether the current state corresponds to the initial
492 state.  This is necessary, for example, to decide whether to emit
493 escape sequences to set the state to the initial state at certain
494 sequence points.  Communication protocols often require this.
496 @deftypefun int mbsinit (const mbstate_t *@var{ps})
497 @standards{ISO, wchar.h}
498 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
499 @c ps is dereferenced once, unguarded.  This would call for @mtsrace:ps,
500 @c but since a single word-sized field is (atomically) accessed, any
501 @c race here would be harmless.  Other functions that take an optional
502 @c mbstate_t* argument named ps are marked with @mtasurace:<func>/!ps,
503 @c to indicate that the function uses a static buffer if ps is NULL.
504 @c These could also have been marked with @mtsrace:ps, but we'll omit
505 @c that for brevity, for it's somewhat redundant with the @mtasurace.
506 The @code{mbsinit} function determines whether the state object pointed
507 to by @var{ps} is in the initial state.  If @var{ps} is a null pointer or
508 the object is in the initial state the return value is nonzero.  Otherwise
509 it is zero.
511 @pindex wchar.h
512 @code{mbsinit} was introduced in @w{Amendment 1} to @w{ISO C90} and is
513 declared in @file{wchar.h}.
514 @end deftypefun
516 Code using @code{mbsinit} often looks similar to this:
518 @c Fix the example to explicitly say how to generate the escape sequence
519 @c to restore the initial state.
520 @smallexample
522   mbstate_t state;
523   memset (&state, '\0', sizeof (state));
524   /* @r{Use @var{state}.}  */
525   @dots{}
526   if (! mbsinit (&state))
527     @{
528       /* @r{Emit code to return to initial state.}  */
529       const wchar_t empty[] = L"";
530       const wchar_t *srcp = empty;
531       wcsrtombs (outbuf, &srcp, outbuflen, &state);
532     @}
533   @dots{}
535 @end smallexample
537 The code to emit the escape sequence to get back to the initial state is
538 interesting.  The @code{wcsrtombs} function can be used to determine the
539 necessary output code (@pxref{Converting Strings}).  Please note that with
540 @theglibc{} it is not necessary to perform this extra action for the
541 conversion from multibyte text to wide character text since the wide
542 character encoding is not stateful.  But there is nothing mentioned in
543 any standard that prohibits making @code{wchar_t} use a stateful
544 encoding.
546 @node Converting a Character
547 @subsection Converting Single Characters
549 The most fundamental of the conversion functions are those dealing with
550 single characters.  Please note that this does not always mean single
551 bytes.  But since there is very often a subset of the multibyte
552 character set that consists of single byte sequences, there are
553 functions to help with converting bytes.  Frequently, ASCII is a subset
554 of the multibyte character set.  In such a scenario, each ASCII character
555 stands for itself, and all other characters have at least a first byte
556 that is beyond the range @math{0} to @math{127}.
558 @deftypefun wint_t btowc (int @var{c})
559 @standards{ISO, wchar.h}
560 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
561 @c Calls btowc_fct or __fct; reads from locale, and from the
562 @c get_gconv_fcts result multiple times.  get_gconv_fcts calls
563 @c __wcsmbs_load_conv to initialize the ctype if it's null.
564 @c wcsmbs_load_conv takes a non-recursive wrlock before allocating
565 @c memory for the fcts structure, initializing it, and then storing it
566 @c in the locale object.  The initialization involves dlopening and a
567 @c lot more.
568 The @code{btowc} function (``byte to wide character'') converts a valid
569 single byte character @var{c} in the initial shift state into the wide
570 character equivalent using the conversion rules from the currently
571 selected locale of the @code{LC_CTYPE} category.
573 If @code{(unsigned char) @var{c}} is no valid single byte multibyte
574 character or if @var{c} is @code{EOF}, the function returns @code{WEOF}.
576 Please note the restriction of @var{c} being tested for validity only in
577 the initial shift state.  No @code{mbstate_t} object is used from
578 which the state information is taken, and the function also does not use
579 any static state.
581 @pindex wchar.h
582 The @code{btowc} function was introduced in @w{Amendment 1} to @w{ISO C90}
583 and is declared in @file{wchar.h}.
584 @end deftypefun
586 Despite the limitation that the single byte value is always interpreted
587 in the initial state, this function is actually useful most of the time.
588 Most characters are either entirely single-byte character sets or they
589 are extensions to ASCII.  But then it is possible to write code like this
590 (not that this specific example is very useful):
592 @smallexample
593 wchar_t *
594 itow (unsigned long int val)
596   static wchar_t buf[30];
597   wchar_t *wcp = &buf[29];
598   *wcp = L'\0';
599   while (val != 0)
600     @{
601       *--wcp = btowc ('0' + val % 10);
602       val /= 10;
603     @}
604   if (wcp == &buf[29])
605     *--wcp = L'0';
606   return wcp;
608 @end smallexample
610 Why is it necessary to use such a complicated implementation and not
611 simply cast @code{'0' + val % 10} to a wide character?  The answer is
612 that there is no guarantee that one can perform this kind of arithmetic
613 on the character of the character set used for @code{wchar_t}
614 representation.  In other situations the bytes are not constant at
615 compile time and so the compiler cannot do the work.  In situations like
616 this, using @code{btowc} is required.
618 @noindent
619 There is also a function for the conversion in the other direction.
621 @deftypefun int wctob (wint_t @var{c})
622 @standards{ISO, wchar.h}
623 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
624 The @code{wctob} function (``wide character to byte'') takes as the
625 parameter a valid wide character.  If the multibyte representation for
626 this character in the initial state is exactly one byte long, the return
627 value of this function is this character.  Otherwise the return value is
628 @code{EOF}.
630 @pindex wchar.h
631 @code{wctob} was introduced in @w{Amendment 1} to @w{ISO C90} and
632 is declared in @file{wchar.h}.
633 @end deftypefun
635 There are more general functions to convert single characters from
636 multibyte representation to wide characters and vice versa.  These
637 functions pose no limit on the length of the multibyte representation
638 and they also do not require it to be in the initial state.
640 @deftypefun size_t mbrtowc (wchar_t *restrict @var{pwc}, const char *restrict @var{s}, size_t @var{n}, mbstate_t *restrict @var{ps})
641 @standards{ISO, wchar.h}
642 @safety{@prelim{}@mtunsafe{@mtasurace{:mbrtowc/!ps}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
643 @cindex stateful
644 The @code{mbrtowc} function (``multibyte restartable to wide
645 character'') converts the next multibyte character in the string pointed
646 to by @var{s} into a wide character and stores it in the wide character
647 string pointed to by @var{pwc}.  The conversion is performed according
648 to the locale currently selected for the @code{LC_CTYPE} category.  If
649 the conversion for the character set used in the locale requires a state,
650 the multibyte string is interpreted in the state represented by the
651 object pointed to by @var{ps}.  If @var{ps} is a null pointer, a static,
652 internal state variable used only by the @code{mbrtowc} function is
653 used.
655 If the next multibyte character corresponds to the NUL wide character,
656 the return value of the function is @math{0} and the state object is
657 afterwards in the initial state.  If the next @var{n} or fewer bytes
658 form a correct multibyte character, the return value is the number of
659 bytes starting from @var{s} that form the multibyte character.  The
660 conversion state is updated according to the bytes consumed in the
661 conversion.  In both cases the wide character (either the @code{L'\0'}
662 or the one found in the conversion) is stored in the string pointed to
663 by @var{pwc} if @var{pwc} is not null.
665 If the first @var{n} bytes of the multibyte string possibly form a valid
666 multibyte character but there are more than @var{n} bytes needed to
667 complete it, the return value of the function is @code{(size_t) -2} and
668 no value is stored.  Please note that this can happen even if @var{n}
669 has a value greater than or equal to @code{MB_CUR_MAX} since the input
670 might contain redundant shift sequences.
672 If the first @code{n} bytes of the multibyte string cannot possibly form
673 a valid multibyte character, no value is stored, the global variable
674 @code{errno} is set to the value @code{EILSEQ}, and the function returns
675 @code{(size_t) -1}.  The conversion state is afterwards undefined.
677 @pindex wchar.h
678 @code{mbrtowc} was introduced in @w{Amendment 1} to @w{ISO C90} and
679 is declared in @file{wchar.h}.
680 @end deftypefun
682 Use of @code{mbrtowc} is straightforward.  A function that copies a
683 multibyte string into a wide character string while at the same time
684 converting all lowercase characters into uppercase could look like this
685 (this is not the final version, just an example; it has no error
686 checking, and sometimes leaks memory):
688 @smallexample
689 wchar_t *
690 mbstouwcs (const char *s)
692   size_t len = strlen (s);
693   wchar_t *result = malloc ((len + 1) * sizeof (wchar_t));
694   wchar_t *wcp = result;
695   wchar_t tmp[1];
696   mbstate_t state;
697   size_t nbytes;
699   memset (&state, '\0', sizeof (state));
700   while ((nbytes = mbrtowc (tmp, s, len, &state)) > 0)
701     @{
702       if (nbytes >= (size_t) -2)
703         /* Invalid input string.  */
704         return NULL;
705       *wcp++ = towupper (tmp[0]);
706       len -= nbytes;
707       s += nbytes;
708     @}
709   return result;
711 @end smallexample
713 The use of @code{mbrtowc} should be clear.  A single wide character is
714 stored in @code{@var{tmp}[0]}, and the number of consumed bytes is stored
715 in the variable @var{nbytes}.  If the conversion is successful, the
716 uppercase variant of the wide character is stored in the @var{result}
717 array and the pointer to the input string and the number of available
718 bytes is adjusted.
720 The only non-obvious thing about @code{mbrtowc} might be the way memory
721 is allocated for the result.  The above code uses the fact that there
722 can never be more wide characters in the converted result than there are
723 bytes in the multibyte input string.  This method yields a pessimistic
724 guess about the size of the result, and if many wide character strings
725 have to be constructed this way or if the strings are long, the extra
726 memory required to be allocated because the input string contains
727 multibyte characters might be significant.  The allocated memory block can
728 be resized to the correct size before returning it, but a better solution
729 might be to allocate just the right amount of space for the result right
730 away.  Unfortunately there is no function to compute the length of the wide
731 character string directly from the multibyte string.  There is, however, a
732 function that does part of the work.
734 @deftypefun size_t mbrlen (const char *restrict @var{s}, size_t @var{n}, mbstate_t *@var{ps})
735 @standards{ISO, wchar.h}
736 @safety{@prelim{}@mtunsafe{@mtasurace{:mbrlen/!ps}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
737 The @code{mbrlen} function (``multibyte restartable length'') computes
738 the number of at most @var{n} bytes starting at @var{s}, which form the
739 next valid and complete multibyte character.
741 If the next multibyte character corresponds to the NUL wide character,
742 the return value is @math{0}.  If the next @var{n} bytes form a valid
743 multibyte character, the number of bytes belonging to this multibyte
744 character byte sequence is returned.
746 If the first @var{n} bytes possibly form a valid multibyte
747 character but the character is incomplete, the return value is
748 @code{(size_t) -2}.  Otherwise the multibyte character sequence is invalid
749 and the return value is @code{(size_t) -1}.
751 The multibyte sequence is interpreted in the state represented by the
752 object pointed to by @var{ps}.  If @var{ps} is a null pointer, a state
753 object local to @code{mbrlen} is used.
755 @pindex wchar.h
756 @code{mbrlen} was introduced in @w{Amendment 1} to @w{ISO C90} and
757 is declared in @file{wchar.h}.
758 @end deftypefun
760 The attentive reader now will note that @code{mbrlen} can be implemented
763 @smallexample
764 mbrtowc (NULL, s, n, ps != NULL ? ps : &internal)
765 @end smallexample
767 This is true and in fact is mentioned in the official specification.
768 How can this function be used to determine the length of the wide
769 character string created from a multibyte character string?  It is not
770 directly usable, but we can define a function @code{mbslen} using it:
772 @smallexample
773 size_t
774 mbslen (const char *s)
776   mbstate_t state;
777   size_t result = 0;
778   size_t nbytes;
779   memset (&state, '\0', sizeof (state));
780   while ((nbytes = mbrlen (s, MB_LEN_MAX, &state)) > 0)
781     @{
782       if (nbytes >= (size_t) -2)
783         /* @r{Something is wrong.}  */
784         return (size_t) -1;
785       s += nbytes;
786       ++result;
787     @}
788   return result;
790 @end smallexample
792 This function simply calls @code{mbrlen} for each multibyte character
793 in the string and counts the number of function calls.  Please note that
794 we here use @code{MB_LEN_MAX} as the size argument in the @code{mbrlen}
795 call.  This is acceptable since a) this value is larger than the length of
796 the longest multibyte character sequence and b) we know that the string
797 @var{s} ends with a NUL byte, which cannot be part of any other multibyte
798 character sequence but the one representing the NUL wide character.
799 Therefore, the @code{mbrlen} function will never read invalid memory.
801 Now that this function is available (just to make this clear, this
802 function is @emph{not} part of @theglibc{}) we can compute the
803 number of wide characters required to store the converted multibyte
804 character string @var{s} using
806 @smallexample
807 wcs_bytes = (mbslen (s) + 1) * sizeof (wchar_t);
808 @end smallexample
810 Please note that the @code{mbslen} function is quite inefficient.  The
811 implementation of @code{mbstouwcs} with @code{mbslen} would have to
812 perform the conversion of the multibyte character input string twice, and
813 this conversion might be quite expensive.  So it is necessary to think
814 about the consequences of using the easier but imprecise method before
815 doing the work twice.
817 @deftypefun size_t wcrtomb (char *restrict @var{s}, wchar_t @var{wc}, mbstate_t *restrict @var{ps})
818 @standards{ISO, wchar.h}
819 @safety{@prelim{}@mtunsafe{@mtasurace{:wcrtomb/!ps}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
820 @c wcrtomb uses a static, non-thread-local unguarded state variable when
821 @c PS is NULL.  When a state is passed in, and it's not used
822 @c concurrently in other threads, this function behaves safely as long
823 @c as gconv modules don't bring MT safety issues of their own.
824 @c Attempting to load gconv modules or to build conversion chains in
825 @c signal handlers may encounter gconv databases or caches in a
826 @c partially-updated state, and asynchronous cancellation may leave them
827 @c in such states, besides leaking the lock that guards them.
828 @c get_gconv_fcts ok
829 @c    wcsmbs_load_conv ok
830 @c      norm_add_slashes ok
831 @c      wcsmbs_getfct ok
832 @c        gconv_find_transform ok
833 @c          gconv_read_conf (libc_once)
834 @c          gconv_lookup_cache ok
835 @c            find_module_idx ok
836 @c            find_module ok
837 @c              gconv_find_shlib (ok)
838 @c              ->init_fct (assumed ok)
839 @c            gconv_get_builtin_trans ok
840 @c            gconv_release_step ok
841 @c          do_lookup_alias ok
842 @c          find_derivation ok
843 @c            derivation_lookup ok
844 @c            increment_counter ok
845 @c              gconv_find_shlib ok
846 @c              step->init_fct (assumed ok)
847 @c            gen_steps ok
848 @c              gconv_find_shlib ok
849 @c                dlopen (presumed ok)
850 @c                dlsym (presumed ok)
851 @c              step->init_fct (assumed ok)
852 @c              step->end_fct (assumed ok)
853 @c              gconv_get_builtin_trans ok
854 @c              gconv_release_step ok
855 @c            add_derivation ok
856 @c      gconv_close_transform ok
857 @c        gconv_release_step ok
858 @c          step->end_fct (assumed ok)
859 @c          gconv_release_shlib ok
860 @c            dlclose (presumed ok)
861 @c        gconv_release_cache ok
862 @c  ->tomb->__fct (assumed ok)
863 The @code{wcrtomb} function (``wide character restartable to
864 multibyte'') converts a single wide character into a multibyte string
865 corresponding to that wide character.
867 If @var{s} is a null pointer, the function resets the state stored in
868 the object pointed to by @var{ps} (or the internal @code{mbstate_t}
869 object) to the initial state.  This can also be achieved by a call like
870 this:
872 @smallexample
873 wcrtombs (temp_buf, L'\0', ps)
874 @end smallexample
876 @noindent
877 since, if @var{s} is a null pointer, @code{wcrtomb} performs as if it
878 writes into an internal buffer, which is guaranteed to be large enough.
880 If @var{wc} is the NUL wide character, @code{wcrtomb} emits, if
881 necessary, a shift sequence to get the state @var{ps} into the initial
882 state followed by a single NUL byte, which is stored in the string
883 @var{s}.
885 Otherwise a byte sequence (possibly including shift sequences) is written
886 into the string @var{s}.  This only happens if @var{wc} is a valid wide
887 character (i.e., it has a multibyte representation in the character set
888 selected by locale of the @code{LC_CTYPE} category).  If @var{wc} is no
889 valid wide character, nothing is stored in the strings @var{s},
890 @code{errno} is set to @code{EILSEQ}, the conversion state in @var{ps}
891 is undefined and the return value is @code{(size_t) -1}.
893 If no error occurred the function returns the number of bytes stored in
894 the string @var{s}.  This includes all bytes representing shift
895 sequences.
897 One word about the interface of the function: there is no parameter
898 specifying the length of the array @var{s}.  Instead the function
899 assumes that there are at least @code{MB_CUR_MAX} bytes available since
900 this is the maximum length of any byte sequence representing a single
901 character.  So the caller has to make sure that there is enough space
902 available, otherwise buffer overruns can occur.
904 @pindex wchar.h
905 @code{wcrtomb} was introduced in @w{Amendment 1} to @w{ISO C90} and is
906 declared in @file{wchar.h}.
907 @end deftypefun
909 Using @code{wcrtomb} is as easy as using @code{mbrtowc}.  The following
910 example appends a wide character string to a multibyte character string.
911 Again, the code is not really useful (or correct), it is simply here to
912 demonstrate the use and some problems.
914 @smallexample
915 char *
916 mbscatwcs (char *s, size_t len, const wchar_t *ws)
918   mbstate_t state;
919   /* @r{Find the end of the existing string.}  */
920   char *wp = strchr (s, '\0');
921   len -= wp - s;
922   memset (&state, '\0', sizeof (state));
923   do
924     @{
925       size_t nbytes;
926       if (len < MB_CUR_LEN)
927         @{
928           /* @r{We cannot guarantee that the next}
929              @r{character fits into the buffer, so}
930              @r{return an error.}  */
931           errno = E2BIG;
932           return NULL;
933         @}
934       nbytes = wcrtomb (wp, *ws, &state);
935       if (nbytes == (size_t) -1)
936         /* @r{Error in the conversion.}  */
937         return NULL;
938       len -= nbytes;
939       wp += nbytes;
940     @}
941   while (*ws++ != L'\0');
942   return s;
944 @end smallexample
946 First the function has to find the end of the string currently in the
947 array @var{s}.  The @code{strchr} call does this very efficiently since a
948 requirement for multibyte character representations is that the NUL byte
949 is never used except to represent itself (and in this context, the end
950 of the string).
952 After initializing the state object the loop is entered where the first
953 task is to make sure there is enough room in the array @var{s}.  We
954 abort if there are not at least @code{MB_CUR_LEN} bytes available.  This
955 is not always optimal but we have no other choice.  We might have less
956 than @code{MB_CUR_LEN} bytes available but the next multibyte character
957 might also be only one byte long.  At the time the @code{wcrtomb} call
958 returns it is too late to decide whether the buffer was large enough.  If
959 this solution is unsuitable, there is a very slow but more accurate
960 solution.
962 @smallexample
963   @dots{}
964   if (len < MB_CUR_LEN)
965     @{
966       mbstate_t temp_state;
967       memcpy (&temp_state, &state, sizeof (state));
968       if (wcrtomb (NULL, *ws, &temp_state) > len)
969         @{
970           /* @r{We cannot guarantee that the next}
971              @r{character fits into the buffer, so}
972              @r{return an error.}  */
973           errno = E2BIG;
974           return NULL;
975         @}
976     @}
977   @dots{}
978 @end smallexample
980 Here we perform the conversion that might overflow the buffer so that
981 we are afterwards in the position to make an exact decision about the
982 buffer size.  Please note the @code{NULL} argument for the destination
983 buffer in the new @code{wcrtomb} call; since we are not interested in the
984 converted text at this point, this is a nice way to express this.  The
985 most unusual thing about this piece of code certainly is the duplication
986 of the conversion state object, but if a change of the state is necessary
987 to emit the next multibyte character, we want to have the same shift state
988 change performed in the real conversion.  Therefore, we have to preserve
989 the initial shift state information.
991 There are certainly many more and even better solutions to this problem.
992 This example is only provided for educational purposes.
994 @node Converting Strings
995 @subsection Converting Multibyte and Wide Character Strings
997 The functions described in the previous section only convert a single
998 character at a time.  Most operations to be performed in real-world
999 programs include strings and therefore the @w{ISO C} standard also
1000 defines conversions on entire strings.  However, the defined set of
1001 functions is quite limited; therefore, @theglibc{} contains a few
1002 extensions that can help in some important situations.
1004 @deftypefun size_t mbsrtowcs (wchar_t *restrict @var{dst}, const char **restrict @var{src}, size_t @var{len}, mbstate_t *restrict @var{ps})
1005 @standards{ISO, wchar.h}
1006 @safety{@prelim{}@mtunsafe{@mtasurace{:mbsrtowcs/!ps}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1007 The @code{mbsrtowcs} function (``multibyte string restartable to wide
1008 character string'') converts the NUL-terminated multibyte character
1009 string at @code{*@var{src}} into an equivalent wide character string,
1010 including the NUL wide character at the end.  The conversion is started
1011 using the state information from the object pointed to by @var{ps} or
1012 from an internal object of @code{mbsrtowcs} if @var{ps} is a null
1013 pointer.  Before returning, the state object is updated to match the state
1014 after the last converted character.  The state is the initial state if the
1015 terminating NUL byte is reached and converted.
1017 If @var{dst} is not a null pointer, the result is stored in the array
1018 pointed to by @var{dst}; otherwise, the conversion result is not
1019 available since it is stored in an internal buffer.
1021 If @var{len} wide characters are stored in the array @var{dst} before
1022 reaching the end of the input string, the conversion stops and @var{len}
1023 is returned.  If @var{dst} is a null pointer, @var{len} is never checked.
1025 Another reason for a premature return from the function call is if the
1026 input string contains an invalid multibyte sequence.  In this case the
1027 global variable @code{errno} is set to @code{EILSEQ} and the function
1028 returns @code{(size_t) -1}.
1030 @c XXX The ISO C9x draft seems to have a problem here.  It says that PS
1031 @c is not updated if DST is NULL.  This is not said straightforward and
1032 @c none of the other functions is described like this.  It would make sense
1033 @c to define the function this way but I don't think it is meant like this.
1035 In all other cases the function returns the number of wide characters
1036 converted during this call.  If @var{dst} is not null, @code{mbsrtowcs}
1037 stores in the pointer pointed to by @var{src} either a null pointer (if
1038 the NUL byte in the input string was reached) or the address of the byte
1039 following the last converted multibyte character.
1041 @pindex wchar.h
1042 @code{mbsrtowcs} was introduced in @w{Amendment 1} to @w{ISO C90} and is
1043 declared in @file{wchar.h}.
1044 @end deftypefun
1046 The definition of the @code{mbsrtowcs} function has one important
1047 limitation.  The requirement that @var{dst} has to be a NUL-terminated
1048 string provides problems if one wants to convert buffers with text.  A
1049 buffer is not normally a collection of NUL-terminated strings but instead a
1050 continuous collection of lines, separated by newline characters.  Now
1051 assume that a function to convert one line from a buffer is needed.  Since
1052 the line is not NUL-terminated, the source pointer cannot directly point
1053 into the unmodified text buffer.  This means, either one inserts the NUL
1054 byte at the appropriate place for the time of the @code{mbsrtowcs}
1055 function call (which is not doable for a read-only buffer or in a
1056 multi-threaded application) or one copies the line in an extra buffer
1057 where it can be terminated by a NUL byte.  Note that it is not in general
1058 possible to limit the number of characters to convert by setting the
1059 parameter @var{len} to any specific value.  Since it is not known how
1060 many bytes each multibyte character sequence is in length, one can only
1061 guess.
1063 @cindex stateful
1064 There is still a problem with the method of NUL-terminating a line right
1065 after the newline character, which could lead to very strange results.
1066 As said in the description of the @code{mbsrtowcs} function above, the
1067 conversion state is guaranteed to be in the initial shift state after
1068 processing the NUL byte at the end of the input string.  But this NUL
1069 byte is not really part of the text (i.e., the conversion state after
1070 the newline in the original text could be something different than the
1071 initial shift state and therefore the first character of the next line
1072 is encoded using this state).  But the state in question is never
1073 accessible to the user since the conversion stops after the NUL byte
1074 (which resets the state).  Most stateful character sets in use today
1075 require that the shift state after a newline be the initial state--but
1076 this is not a strict guarantee.  Therefore, simply NUL-terminating a
1077 piece of a running text is not always an adequate solution and,
1078 therefore, should never be used in generally used code.
1080 The generic conversion interface (@pxref{Generic Charset Conversion})
1081 does not have this limitation (it simply works on buffers, not
1082 strings), and @theglibc{} contains a set of functions that take
1083 additional parameters specifying the maximal number of bytes that are
1084 consumed from the input string.  This way the problem of
1085 @code{mbsrtowcs}'s example above could be solved by determining the line
1086 length and passing this length to the function.
1088 @deftypefun size_t wcsrtombs (char *restrict @var{dst}, const wchar_t **restrict @var{src}, size_t @var{len}, mbstate_t *restrict @var{ps})
1089 @standards{ISO, wchar.h}
1090 @safety{@prelim{}@mtunsafe{@mtasurace{:wcsrtombs/!ps}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1091 The @code{wcsrtombs} function (``wide character string restartable to
1092 multibyte string'') converts the NUL-terminated wide character string at
1093 @code{*@var{src}} into an equivalent multibyte character string and
1094 stores the result in the array pointed to by @var{dst}.  The NUL wide
1095 character is also converted.  The conversion starts in the state
1096 described in the object pointed to by @var{ps} or by a state object
1097 local to @code{wcsrtombs} in case @var{ps} is a null pointer.  If
1098 @var{dst} is a null pointer, the conversion is performed as usual but the
1099 result is not available.  If all characters of the input string were
1100 successfully converted and if @var{dst} is not a null pointer, the
1101 pointer pointed to by @var{src} gets assigned a null pointer.
1103 If one of the wide characters in the input string has no valid multibyte
1104 character equivalent, the conversion stops early, sets the global
1105 variable @code{errno} to @code{EILSEQ}, and returns @code{(size_t) -1}.
1107 Another reason for a premature stop is if @var{dst} is not a null
1108 pointer and the next converted character would require more than
1109 @var{len} bytes in total to the array @var{dst}.  In this case (and if
1110 @var{dst} is not a null pointer) the pointer pointed to by @var{src} is
1111 assigned a value pointing to the wide character right after the last one
1112 successfully converted.
1114 Except in the case of an encoding error the return value of the
1115 @code{wcsrtombs} function is the number of bytes in all the multibyte
1116 character sequences stored in @var{dst}.  Before returning, the state in
1117 the object pointed to by @var{ps} (or the internal object in case
1118 @var{ps} is a null pointer) is updated to reflect the state after the
1119 last conversion.  The state is the initial shift state in case the
1120 terminating NUL wide character was converted.
1122 @pindex wchar.h
1123 The @code{wcsrtombs} function was introduced in @w{Amendment 1} to
1124 @w{ISO C90} and is declared in @file{wchar.h}.
1125 @end deftypefun
1127 The restriction mentioned above for the @code{mbsrtowcs} function applies
1128 here also.  There is no possibility of directly controlling the number of
1129 input characters.  One has to place the NUL wide character at the correct
1130 place or control the consumed input indirectly via the available output
1131 array size (the @var{len} parameter).
1133 @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})
1134 @standards{GNU, wchar.h}
1135 @safety{@prelim{}@mtunsafe{@mtasurace{:mbsnrtowcs/!ps}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1136 The @code{mbsnrtowcs} function is very similar to the @code{mbsrtowcs}
1137 function.  All the parameters are the same except for @var{nmc}, which is
1138 new.  The return value is the same as for @code{mbsrtowcs}.
1140 This new parameter specifies how many bytes at most can be used from the
1141 multibyte character string.  In other words, the multibyte character
1142 string @code{*@var{src}} need not be NUL-terminated.  But if a NUL byte
1143 is found within the @var{nmc} first bytes of the string, the conversion
1144 stops there.
1146 This function is a GNU extension.  It is meant to work around the
1147 problems mentioned above.  Now it is possible to convert a buffer with
1148 multibyte character text piece by piece without having to care about
1149 inserting NUL bytes and the effect of NUL bytes on the conversion state.
1150 @end deftypefun
1152 A function to convert a multibyte string into a wide character string
1153 and display it could be written like this (this is not a really useful
1154 example):
1156 @smallexample
1157 void
1158 showmbs (const char *src, FILE *fp)
1160   mbstate_t state;
1161   int cnt = 0;
1162   memset (&state, '\0', sizeof (state));
1163   while (1)
1164     @{
1165       wchar_t linebuf[100];
1166       const char *endp = strchr (src, '\n');
1167       size_t n;
1169       /* @r{Exit if there is no more line.}  */
1170       if (endp == NULL)
1171         break;
1173       n = mbsnrtowcs (linebuf, &src, endp - src, 99, &state);
1174       linebuf[n] = L'\0';
1175       fprintf (fp, "line %d: \"%S\"\n", linebuf);
1176     @}
1178 @end smallexample
1180 There is no problem with the state after a call to @code{mbsnrtowcs}.
1181 Since we don't insert characters in the strings that were not in there
1182 right from the beginning and we use @var{state} only for the conversion
1183 of the given buffer, there is no problem with altering the state.
1185 @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})
1186 @standards{GNU, wchar.h}
1187 @safety{@prelim{}@mtunsafe{@mtasurace{:wcsnrtombs/!ps}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1188 The @code{wcsnrtombs} function implements the conversion from wide
1189 character strings to multibyte character strings.  It is similar to
1190 @code{wcsrtombs} but, just like @code{mbsnrtowcs}, it takes an extra
1191 parameter, which specifies the length of the input string.
1193 No more than @var{nwc} wide characters from the input string
1194 @code{*@var{src}} are converted.  If the input string contains a NUL
1195 wide character in the first @var{nwc} characters, the conversion stops at
1196 this place.
1198 The @code{wcsnrtombs} function is a GNU extension and just like
1199 @code{mbsnrtowcs} helps in situations where no NUL-terminated input
1200 strings are available.
1201 @end deftypefun
1204 @node Multibyte Conversion Example
1205 @subsection A Complete Multibyte Conversion Example
1207 The example programs given in the last sections are only brief and do
1208 not contain all the error checking, etc.  Presented here is a complete
1209 and documented example.  It features the @code{mbrtowc} function but it
1210 should be easy to derive versions using the other functions.
1212 @smallexample
1214 file_mbsrtowcs (int input, int output)
1216   /* @r{Note the use of @code{MB_LEN_MAX}.}
1217      @r{@code{MB_CUR_MAX} cannot portably be used here.}  */
1218   char buffer[BUFSIZ + MB_LEN_MAX];
1219   mbstate_t state;
1220   int filled = 0;
1221   int eof = 0;
1223   /* @r{Initialize the state.}  */
1224   memset (&state, '\0', sizeof (state));
1226   while (!eof)
1227     @{
1228       ssize_t nread;
1229       ssize_t nwrite;
1230       char *inp = buffer;
1231       wchar_t outbuf[BUFSIZ];
1232       wchar_t *outp = outbuf;
1234       /* @r{Fill up the buffer from the input file.}  */
1235       nread = read (input, buffer + filled, BUFSIZ);
1236       if (nread < 0)
1237         @{
1238           perror ("read");
1239           return 0;
1240         @}
1241       /* @r{If we reach end of file, make a note to read no more.} */
1242       if (nread == 0)
1243         eof = 1;
1245       /* @r{@code{filled} is now the number of bytes in @code{buffer}.} */
1246       filled += nread;
1248       /* @r{Convert those bytes to wide characters--as many as we can.} */
1249       while (1)
1250         @{
1251           size_t thislen = mbrtowc (outp, inp, filled, &state);
1252           /* @r{Stop converting at invalid character;}
1253              @r{this can mean we have read just the first part}
1254              @r{of a valid character.}  */
1255           if (thislen == (size_t) -1)
1256             break;
1257           /* @r{We want to handle embedded NUL bytes}
1258              @r{but the return value is 0.  Correct this.}  */
1259           if (thislen == 0)
1260             thislen = 1;
1261           /* @r{Advance past this character.} */
1262           inp += thislen;
1263           filled -= thislen;
1264           ++outp;
1265         @}
1267       /* @r{Write the wide characters we just made.}  */
1268       nwrite = write (output, outbuf,
1269                       (outp - outbuf) * sizeof (wchar_t));
1270       if (nwrite < 0)
1271         @{
1272           perror ("write");
1273           return 0;
1274         @}
1276       /* @r{See if we have a @emph{real} invalid character.} */
1277       if ((eof && filled > 0) || filled >= MB_CUR_MAX)
1278         @{
1279           error (0, 0, "invalid multibyte character");
1280           return 0;
1281         @}
1283       /* @r{If any characters must be carried forward,}
1284          @r{put them at the beginning of @code{buffer}.} */
1285       if (filled > 0)
1286         memmove (buffer, inp, filled);
1287     @}
1289   return 1;
1291 @end smallexample
1294 @node Non-reentrant Conversion
1295 @section Non-reentrant Conversion Function
1297 The functions described in the previous chapter are defined in
1298 @w{Amendment 1} to @w{ISO C90}, but the original @w{ISO C90} standard
1299 also contained functions for character set conversion.  The reason that
1300 these original functions are not described first is that they are almost
1301 entirely useless.
1303 The problem is that all the conversion functions described in the
1304 original @w{ISO C90} use a local state.  Using a local state implies that
1305 multiple conversions at the same time (not only when using threads)
1306 cannot be done, and that you cannot first convert single characters and
1307 then strings since you cannot tell the conversion functions which state
1308 to use.
1310 These original functions are therefore usable only in a very limited set
1311 of situations.  One must complete converting the entire string before
1312 starting a new one, and each string/text must be converted with the same
1313 function (there is no problem with the library itself; it is guaranteed
1314 that no library function changes the state of any of these functions).
1315 @strong{For the above reasons it is highly requested that the functions
1316 described in the previous section be used in place of non-reentrant
1317 conversion functions.}
1319 @menu
1320 * Non-reentrant Character Conversion::  Non-reentrant Conversion of Single
1321                                          Characters.
1322 * Non-reentrant String Conversion::     Non-reentrant Conversion of Strings.
1323 * Shift State::                         States in Non-reentrant Functions.
1324 @end menu
1326 @node Non-reentrant Character Conversion
1327 @subsection Non-reentrant Conversion of Single Characters
1329 @deftypefun int mbtowc (wchar_t *restrict @var{result}, const char *restrict @var{string}, size_t @var{size})
1330 @standards{ISO, stdlib.h}
1331 @safety{@prelim{}@mtunsafe{@mtasurace{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1332 The @code{mbtowc} (``multibyte to wide character'') function when called
1333 with non-null @var{string} converts the first multibyte character
1334 beginning at @var{string} to its corresponding wide character code.  It
1335 stores the result in @code{*@var{result}}.
1337 @code{mbtowc} never examines more than @var{size} bytes.  (The idea is
1338 to supply for @var{size} the number of bytes of data you have in hand.)
1340 @code{mbtowc} with non-null @var{string} distinguishes three
1341 possibilities: the first @var{size} bytes at @var{string} start with
1342 valid multibyte characters, they start with an invalid byte sequence or
1343 just part of a character, or @var{string} points to an empty string (a
1344 null character).
1346 For a valid multibyte character, @code{mbtowc} converts it to a wide
1347 character and stores that in @code{*@var{result}}, and returns the
1348 number of bytes in that character (always at least @math{1} and never
1349 more than @var{size}).
1351 For an invalid byte sequence, @code{mbtowc} returns @math{-1}.  For an
1352 empty string, it returns @math{0}, also storing @code{'\0'} in
1353 @code{*@var{result}}.
1355 If the multibyte character code uses shift characters, then
1356 @code{mbtowc} maintains and updates a shift state as it scans.  If you
1357 call @code{mbtowc} with a null pointer for @var{string}, that
1358 initializes the shift state to its standard initial value.  It also
1359 returns nonzero if the multibyte character code in use actually has a
1360 shift state.  @xref{Shift State}.
1361 @end deftypefun
1363 @deftypefun int wctomb (char *@var{string}, wchar_t @var{wchar})
1364 @standards{ISO, stdlib.h}
1365 @safety{@prelim{}@mtunsafe{@mtasurace{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1366 The @code{wctomb} (``wide character to multibyte'') function converts
1367 the wide character code @var{wchar} to its corresponding multibyte
1368 character sequence, and stores the result in bytes starting at
1369 @var{string}.  At most @code{MB_CUR_MAX} characters are stored.
1371 @code{wctomb} with non-null @var{string} distinguishes three
1372 possibilities for @var{wchar}: a valid wide character code (one that can
1373 be translated to a multibyte character), an invalid code, and
1374 @code{L'\0'}.
1376 Given a valid code, @code{wctomb} converts it to a multibyte character,
1377 storing the bytes starting at @var{string}.  Then it returns the number
1378 of bytes in that character (always at least @math{1} and never more
1379 than @code{MB_CUR_MAX}).
1381 If @var{wchar} is an invalid wide character code, @code{wctomb} returns
1382 @math{-1}.  If @var{wchar} is @code{L'\0'}, it returns @code{0}, also
1383 storing @code{'\0'} in @code{*@var{string}}.
1385 If the multibyte character code uses shift characters, then
1386 @code{wctomb} maintains and updates a shift state as it scans.  If you
1387 call @code{wctomb} with a null pointer for @var{string}, that
1388 initializes the shift state to its standard initial value.  It also
1389 returns nonzero if the multibyte character code in use actually has a
1390 shift state.  @xref{Shift State}.
1392 Calling this function with a @var{wchar} argument of zero when
1393 @var{string} is not null has the side-effect of reinitializing the
1394 stored shift state @emph{as well as} storing the multibyte character
1395 @code{'\0'} and returning @math{0}.
1396 @end deftypefun
1398 Similar to @code{mbrlen} there is also a non-reentrant function that
1399 computes the length of a multibyte character.  It can be defined in
1400 terms of @code{mbtowc}.
1402 @deftypefun int mblen (const char *@var{string}, size_t @var{size})
1403 @standards{ISO, stdlib.h}
1404 @safety{@prelim{}@mtunsafe{@mtasurace{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1405 The @code{mblen} function with a non-null @var{string} argument returns
1406 the number of bytes that make up the multibyte character beginning at
1407 @var{string}, never examining more than @var{size} bytes.  (The idea is
1408 to supply for @var{size} the number of bytes of data you have in hand.)
1410 The return value of @code{mblen} distinguishes three possibilities: the
1411 first @var{size} bytes at @var{string} start with valid multibyte
1412 characters, they start with an invalid byte sequence or just part of a
1413 character, or @var{string} points to an empty string (a null character).
1415 For a valid multibyte character, @code{mblen} returns the number of
1416 bytes in that character (always at least @code{1} and never more than
1417 @var{size}).  For an invalid byte sequence, @code{mblen} returns
1418 @math{-1}.  For an empty string, it returns @math{0}.
1420 If the multibyte character code uses shift characters, then @code{mblen}
1421 maintains and updates a shift state as it scans.  If you call
1422 @code{mblen} with a null pointer for @var{string}, that initializes the
1423 shift state to its standard initial value.  It also returns a nonzero
1424 value if the multibyte character code in use actually has a shift state.
1425 @xref{Shift State}.
1427 @pindex stdlib.h
1428 The function @code{mblen} is declared in @file{stdlib.h}.
1429 @end deftypefun
1432 @node Non-reentrant String Conversion
1433 @subsection Non-reentrant Conversion of Strings
1435 For convenience the @w{ISO C90} standard also defines functions to
1436 convert entire strings instead of single characters.  These functions
1437 suffer from the same problems as their reentrant counterparts from
1438 @w{Amendment 1} to @w{ISO C90}; see @ref{Converting Strings}.
1440 @deftypefun size_t mbstowcs (wchar_t *@var{wstring}, const char *@var{string}, size_t @var{size})
1441 @standards{ISO, stdlib.h}
1442 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1443 @c Odd...  Although this was supposed to be non-reentrant, the internal
1444 @c state is not a static buffer, but an automatic variable.
1445 The @code{mbstowcs} (``multibyte string to wide character string'')
1446 function converts the null-terminated string of multibyte characters
1447 @var{string} to an array of wide character codes, storing not more than
1448 @var{size} wide characters into the array beginning at @var{wstring}.
1449 The terminating null character counts towards the size, so if @var{size}
1450 is less than the actual number of wide characters resulting from
1451 @var{string}, no terminating null character is stored.
1453 The conversion of characters from @var{string} begins in the initial
1454 shift state.
1456 If an invalid multibyte character sequence is found, the @code{mbstowcs}
1457 function returns a value of @math{-1}.  Otherwise, it returns the number
1458 of wide characters stored in the array @var{wstring}.  This number does
1459 not include the terminating null character, which is present if the
1460 number is less than @var{size}.
1462 Here is an example showing how to convert a string of multibyte
1463 characters, allocating enough space for the result.
1465 @smallexample
1466 wchar_t *
1467 mbstowcs_alloc (const char *string)
1469   size_t size = strlen (string) + 1;
1470   wchar_t *buf = xmalloc (size * sizeof (wchar_t));
1472   size = mbstowcs (buf, string, size);
1473   if (size == (size_t) -1)
1474     return NULL;
1475   buf = xrealloc (buf, (size + 1) * sizeof (wchar_t));
1476   return buf;
1478 @end smallexample
1480 @end deftypefun
1482 @deftypefun size_t wcstombs (char *@var{string}, const wchar_t *@var{wstring}, size_t @var{size})
1483 @standards{ISO, stdlib.h}
1484 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1485 The @code{wcstombs} (``wide character string to multibyte string'')
1486 function converts the null-terminated wide character array @var{wstring}
1487 into a string containing multibyte characters, storing not more than
1488 @var{size} bytes starting at @var{string}, followed by a terminating
1489 null character if there is room.  The conversion of characters begins in
1490 the initial shift state.
1492 The terminating null character counts towards the size, so if @var{size}
1493 is less than or equal to the number of bytes needed in @var{wstring}, no
1494 terminating null character is stored.
1496 If a code that does not correspond to a valid multibyte character is
1497 found, the @code{wcstombs} function returns a value of @math{-1}.
1498 Otherwise, the return value is the number of bytes stored in the array
1499 @var{string}.  This number does not include the terminating null character,
1500 which is present if the number is less than @var{size}.
1501 @end deftypefun
1503 @node Shift State
1504 @subsection States in Non-reentrant Functions
1506 In some multibyte character codes, the @emph{meaning} of any particular
1507 byte sequence is not fixed; it depends on what other sequences have come
1508 earlier in the same string.  Typically there are just a few sequences that
1509 can change the meaning of other sequences; these few are called
1510 @dfn{shift sequences} and we say that they set the @dfn{shift state} for
1511 other sequences that follow.
1513 To illustrate shift state and shift sequences, suppose we decide that
1514 the sequence @code{0200} (just one byte) enters Japanese mode, in which
1515 pairs of bytes in the range from @code{0240} to @code{0377} are single
1516 characters, while @code{0201} enters Latin-1 mode, in which single bytes
1517 in the range from @code{0240} to @code{0377} are characters, and
1518 interpreted according to the ISO Latin-1 character set.  This is a
1519 multibyte code that has two alternative shift states (``Japanese mode''
1520 and ``Latin-1 mode''), and two shift sequences that specify particular
1521 shift states.
1523 When the multibyte character code in use has shift states, then
1524 @code{mblen}, @code{mbtowc}, and @code{wctomb} must maintain and update
1525 the current shift state as they scan the string.  To make this work
1526 properly, you must follow these rules:
1528 @itemize @bullet
1529 @item
1530 Before starting to scan a string, call the function with a null pointer
1531 for the multibyte character address---for example, @code{mblen (NULL,
1532 0)}.  This initializes the shift state to its standard initial value.
1534 @item
1535 Scan the string one character at a time, in order.  Do not ``back up''
1536 and rescan characters already scanned, and do not intersperse the
1537 processing of different strings.
1538 @end itemize
1540 Here is an example of using @code{mblen} following these rules:
1542 @smallexample
1543 void
1544 scan_string (char *s)
1546   int length = strlen (s);
1548   /* @r{Initialize shift state.}  */
1549   mblen (NULL, 0);
1551   while (1)
1552     @{
1553       int thischar = mblen (s, length);
1554       /* @r{Deal with end of string and invalid characters.}  */
1555       if (thischar == 0)
1556         break;
1557       if (thischar == -1)
1558         @{
1559           error ("invalid multibyte character");
1560           break;
1561         @}
1562       /* @r{Advance past this character.}  */
1563       s += thischar;
1564       length -= thischar;
1565     @}
1567 @end smallexample
1569 The functions @code{mblen}, @code{mbtowc} and @code{wctomb} are not
1570 reentrant when using a multibyte code that uses a shift state.  However,
1571 no other library functions call these functions, so you don't have to
1572 worry that the shift state will be changed mysteriously.
1575 @node Generic Charset Conversion
1576 @section Generic Charset Conversion
1578 The conversion functions mentioned so far in this chapter all had in
1579 common that they operate on character sets that are not directly
1580 specified by the functions.  The multibyte encoding used is specified by
1581 the currently selected locale for the @code{LC_CTYPE} category.  The
1582 wide character set is fixed by the implementation (in the case of @theglibc{}
1583 it is always UCS-4 encoded @w{ISO 10646}).
1585 This has of course several problems when it comes to general character
1586 conversion:
1588 @itemize @bullet
1589 @item
1590 For every conversion where neither the source nor the destination
1591 character set is the character set of the locale for the @code{LC_CTYPE}
1592 category, one has to change the @code{LC_CTYPE} locale using
1593 @code{setlocale}.
1595 Changing the @code{LC_CTYPE} locale introduces major problems for the rest
1596 of the programs since several more functions (e.g., the character
1597 classification functions, @pxref{Classification of Characters}) use the
1598 @code{LC_CTYPE} category.
1600 @item
1601 Parallel conversions to and from different character sets are not
1602 possible since the @code{LC_CTYPE} selection is global and shared by all
1603 threads.
1605 @item
1606 If neither the source nor the destination character set is the character
1607 set used for @code{wchar_t} representation, there is at least a two-step
1608 process necessary to convert a text using the functions above.  One would
1609 have to select the source character set as the multibyte encoding,
1610 convert the text into a @code{wchar_t} text, select the destination
1611 character set as the multibyte encoding, and convert the wide character
1612 text to the multibyte (@math{=} destination) character set.
1614 Even if this is possible (which is not guaranteed) it is a very tiring
1615 work.  Plus it suffers from the other two raised points even more due to
1616 the steady changing of the locale.
1617 @end itemize
1619 The XPG2 standard defines a completely new set of functions, which has
1620 none of these limitations.  They are not at all coupled to the selected
1621 locales, and they have no constraints on the character sets selected for
1622 source and destination.  Only the set of available conversions limits
1623 them.  The standard does not specify that any conversion at all must be
1624 available.  Such availability is a measure of the quality of the
1625 implementation.
1627 In the following text first the interface to @code{iconv} and then the
1628 conversion function, will be described.  Comparisons with other
1629 implementations will show what obstacles stand in the way of portable
1630 applications.  Finally, the implementation is described in so far as might
1631 interest the advanced user who wants to extend conversion capabilities.
1633 @menu
1634 * Generic Conversion Interface::    Generic Character Set Conversion Interface.
1635 * iconv Examples::                  A complete @code{iconv} example.
1636 * Other iconv Implementations::     Some Details about other @code{iconv}
1637                                      Implementations.
1638 * glibc iconv Implementation::      The @code{iconv} Implementation in the GNU C
1639                                      library.
1640 @end menu
1642 @node Generic Conversion Interface
1643 @subsection Generic Character Set Conversion Interface
1645 This set of functions follows the traditional cycle of using a resource:
1646 open--use--close.  The interface consists of three functions, each of
1647 which implements one step.
1649 Before the interfaces are described it is necessary to introduce a
1650 data type.  Just like other open--use--close interfaces the functions
1651 introduced here work using handles and the @file{iconv.h} header
1652 defines a special type for the handles used.
1654 @deftp {Data Type} iconv_t
1655 @standards{XPG2, iconv.h}
1656 This data type is an abstract type defined in @file{iconv.h}.  The user
1657 must not assume anything about the definition of this type; it must be
1658 completely opaque.
1660 Objects of this type can be assigned handles for the conversions using
1661 the @code{iconv} functions.  The objects themselves need not be freed, but
1662 the conversions for which the handles stand for have to.
1663 @end deftp
1665 @noindent
1666 The first step is the function to create a handle.
1668 @deftypefun iconv_t iconv_open (const char *@var{tocode}, const char *@var{fromcode})
1669 @standards{XPG2, iconv.h}
1670 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1671 @c Calls malloc if tocode and/or fromcode are too big for alloca.  Calls
1672 @c strip and upstr on both, then gconv_open.  strip and upstr call
1673 @c isalnum_l and toupper_l with the C locale.  gconv_open may MT-safely
1674 @c tokenize toset, replace unspecified codesets with the current locale
1675 @c (possibly two different accesses), and finally it calls
1676 @c gconv_find_transform and initializes the gconv_t result with all the
1677 @c steps in the conversion sequence, running each one's initializer,
1678 @c destructing and releasing them all if anything fails.
1680 The @code{iconv_open} function has to be used before starting a
1681 conversion.  The two parameters this function takes determine the
1682 source and destination character set for the conversion, and if the
1683 implementation has the possibility to perform such a conversion, the
1684 function returns a handle.
1686 If the wanted conversion is not available, the @code{iconv_open} function
1687 returns @code{(iconv_t) -1}.  In this case the global variable
1688 @code{errno} can have the following values:
1690 @table @code
1691 @item EMFILE
1692 The process already has @code{OPEN_MAX} file descriptors open.
1693 @item ENFILE
1694 The system limit of open files is reached.
1695 @item ENOMEM
1696 Not enough memory to carry out the operation.
1697 @item EINVAL
1698 The conversion from @var{fromcode} to @var{tocode} is not supported.
1699 @end table
1701 It is not possible to use the same descriptor in different threads to
1702 perform independent conversions.  The data structures associated
1703 with the descriptor include information about the conversion state.
1704 This must not be messed up by using it in different conversions.
1706 An @code{iconv} descriptor is like a file descriptor as for every use a
1707 new descriptor must be created.  The descriptor does not stand for all
1708 of the conversions from @var{fromset} to @var{toset}.
1710 The @glibcadj{} implementation of @code{iconv_open} has one
1711 significant extension to other implementations.  To ease the extension
1712 of the set of available conversions, the implementation allows storing
1713 the necessary files with data and code in an arbitrary number of
1714 directories.  How this extension must be written will be explained below
1715 (@pxref{glibc iconv Implementation}).  Here it is only important to say
1716 that all directories mentioned in the @code{GCONV_PATH} environment
1717 variable are considered only if they contain a file @file{gconv-modules}.
1718 These directories need not necessarily be created by the system
1719 administrator.  In fact, this extension is introduced to help users
1720 writing and using their own, new conversions.  Of course, this does not
1721 work for security reasons in SUID binaries; in this case only the system
1722 directory is considered and this normally is
1723 @file{@var{prefix}/lib/gconv}.  The @code{GCONV_PATH} environment
1724 variable is examined exactly once at the first call of the
1725 @code{iconv_open} function.  Later modifications of the variable have no
1726 effect.
1728 @pindex iconv.h
1729 The @code{iconv_open} function was introduced early in the X/Open
1730 Portability Guide, @w{version 2}.  It is supported by all commercial
1731 Unices as it is required for the Unix branding.  However, the quality and
1732 completeness of the implementation varies widely.  The @code{iconv_open}
1733 function is declared in @file{iconv.h}.
1734 @end deftypefun
1736 The @code{iconv} implementation can associate large data structure with
1737 the handle returned by @code{iconv_open}.  Therefore, it is crucial to
1738 free all the resources once all conversions are carried out and the
1739 conversion is not needed anymore.
1741 @deftypefun int iconv_close (iconv_t @var{cd})
1742 @standards{XPG2, iconv.h}
1743 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{}}}
1744 @c Calls gconv_close to destruct and release each of the conversion
1745 @c steps, release the gconv_t object, then call gconv_close_transform.
1746 @c Access to the gconv_t object is not guarded, but calling iconv_close
1747 @c concurrently with any other use is undefined.
1749 The @code{iconv_close} function frees all resources associated with the
1750 handle @var{cd}, which must have been returned by a successful call to
1751 the @code{iconv_open} function.
1753 If the function call was successful the return value is @math{0}.
1754 Otherwise it is @math{-1} and @code{errno} is set appropriately.
1755 Defined errors are:
1757 @table @code
1758 @item EBADF
1759 The conversion descriptor is invalid.
1760 @end table
1762 @pindex iconv.h
1763 The @code{iconv_close} function was introduced together with the rest
1764 of the @code{iconv} functions in XPG2 and is declared in @file{iconv.h}.
1765 @end deftypefun
1767 The standard defines only one actual conversion function.  This has,
1768 therefore, the most general interface: it allows conversion from one
1769 buffer to another.  Conversion from a file to a buffer, vice versa, or
1770 even file to file can be implemented on top of it.
1772 @deftypefun size_t iconv (iconv_t @var{cd}, char **@var{inbuf}, size_t *@var{inbytesleft}, char **@var{outbuf}, size_t *@var{outbytesleft})
1773 @standards{XPG2, iconv.h}
1774 @safety{@prelim{}@mtsafe{@mtsrace{:cd}}@assafe{}@acunsafe{@acucorrupt{}}}
1775 @c Without guarding access to the iconv_t object pointed to by cd, call
1776 @c the conversion function to convert inbuf or flush the internal
1777 @c conversion state.
1778 @cindex stateful
1779 The @code{iconv} function converts the text in the input buffer
1780 according to the rules associated with the descriptor @var{cd} and
1781 stores the result in the output buffer.  It is possible to call the
1782 function for the same text several times in a row since for stateful
1783 character sets the necessary state information is kept in the data
1784 structures associated with the descriptor.
1786 The input buffer is specified by @code{*@var{inbuf}} and it contains
1787 @code{*@var{inbytesleft}} bytes.  The extra indirection is necessary for
1788 communicating the used input back to the caller (see below).  It is
1789 important to note that the buffer pointer is of type @code{char} and the
1790 length is measured in bytes even if the input text is encoded in wide
1791 characters.
1793 The output buffer is specified in a similar way.  @code{*@var{outbuf}}
1794 points to the beginning of the buffer with at least
1795 @code{*@var{outbytesleft}} bytes room for the result.  The buffer
1796 pointer again is of type @code{char} and the length is measured in
1797 bytes.  If @var{outbuf} or @code{*@var{outbuf}} is a null pointer, the
1798 conversion is performed but no output is available.
1800 If @var{inbuf} is a null pointer, the @code{iconv} function performs the
1801 necessary action to put the state of the conversion into the initial
1802 state.  This is obviously a no-op for non-stateful encodings, but if the
1803 encoding has a state, such a function call might put some byte sequences
1804 in the output buffer, which perform the necessary state changes.  The
1805 next call with @var{inbuf} not being a null pointer then simply goes on
1806 from the initial state.  It is important that the programmer never makes
1807 any assumption as to whether the conversion has to deal with states.
1808 Even if the input and output character sets are not stateful, the
1809 implementation might still have to keep states.  This is due to the
1810 implementation chosen for @theglibc{} as it is described below.
1811 Therefore an @code{iconv} call to reset the state should always be
1812 performed if some protocol requires this for the output text.
1814 The conversion stops for one of three reasons.  The first is that all
1815 characters from the input buffer are converted.  This actually can mean
1816 two things: either all bytes from the input buffer are consumed or
1817 there are some bytes at the end of the buffer that possibly can form a
1818 complete character but the input is incomplete.  The second reason for a
1819 stop is that the output buffer is full.  And the third reason is that
1820 the input contains invalid characters.
1822 In all of these cases the buffer pointers after the last successful
1823 conversion, for the input and output buffers, are stored in @var{inbuf} and
1824 @var{outbuf}, and the available room in each buffer is stored in
1825 @var{inbytesleft} and @var{outbytesleft}.
1827 Since the character sets selected in the @code{iconv_open} call can be
1828 almost arbitrary, there can be situations where the input buffer contains
1829 valid characters, which have no identical representation in the output
1830 character set.  The behavior in this situation is undefined.  The
1831 @emph{current} behavior of @theglibc{} in this situation is to
1832 return with an error immediately.  This certainly is not the most
1833 desirable solution; therefore, future versions will provide better ones,
1834 but they are not yet finished.
1836 If all input from the input buffer is successfully converted and stored
1837 in the output buffer, the function returns the number of non-reversible
1838 conversions performed.  In all other cases the return value is
1839 @code{(size_t) -1} and @code{errno} is set appropriately.  In such cases
1840 the value pointed to by @var{inbytesleft} is nonzero.
1842 @table @code
1843 @item EILSEQ
1844 The conversion stopped because of an invalid byte sequence in the input.
1845 After the call, @code{*@var{inbuf}} points at the first byte of the
1846 invalid byte sequence.
1848 @item E2BIG
1849 The conversion stopped because it ran out of space in the output buffer.
1851 @item EINVAL
1852 The conversion stopped because of an incomplete byte sequence at the end
1853 of the input buffer.
1855 @item EBADF
1856 The @var{cd} argument is invalid.
1857 @end table
1859 @pindex iconv.h
1860 The @code{iconv} function was introduced in the XPG2 standard and is
1861 declared in the @file{iconv.h} header.
1862 @end deftypefun
1864 The definition of the @code{iconv} function is quite good overall.  It
1865 provides quite flexible functionality.  The only problems lie in the
1866 boundary cases, which are incomplete byte sequences at the end of the
1867 input buffer and invalid input.  A third problem, which is not really
1868 a design problem, is the way conversions are selected.  The standard
1869 does not say anything about the legitimate names, a minimal set of
1870 available conversions.  We will see how this negatively impacts other
1871 implementations, as demonstrated below.
1873 @node iconv Examples
1874 @subsection A complete @code{iconv} example
1876 The example below features a solution for a common problem.  Given that
1877 one knows the internal encoding used by the system for @code{wchar_t}
1878 strings, one often is in the position to read text from a file and store
1879 it in wide character buffers.  One can do this using @code{mbsrtowcs},
1880 but then we run into the problems discussed above.
1882 @smallexample
1884 file2wcs (int fd, const char *charset, wchar_t *outbuf, size_t avail)
1886   char inbuf[BUFSIZ];
1887   size_t insize = 0;
1888   char *wrptr = (char *) outbuf;
1889   int result = 0;
1890   iconv_t cd;
1892   cd = iconv_open ("WCHAR_T", charset);
1893   if (cd == (iconv_t) -1)
1894     @{
1895       /* @r{Something went wrong.}  */
1896       if (errno == EINVAL)
1897         error (0, 0, "conversion from '%s' to wchar_t not available",
1898                charset);
1899       else
1900         perror ("iconv_open");
1902       /* @r{Terminate the output string.}  */
1903       *outbuf = L'\0';
1905       return -1;
1906     @}
1908   while (avail > 0)
1909     @{
1910       size_t nread;
1911       size_t nconv;
1912       char *inptr = inbuf;
1914       /* @r{Read more input.}  */
1915       nread = read (fd, inbuf + insize, sizeof (inbuf) - insize);
1916       if (nread == 0)
1917         @{
1918           /* @r{When we come here the file is completely read.}
1919              @r{This still could mean there are some unused}
1920              @r{characters in the @code{inbuf}.  Put them back.}  */
1921           if (lseek (fd, -insize, SEEK_CUR) == -1)
1922             result = -1;
1924           /* @r{Now write out the byte sequence to get into the}
1925              @r{initial state if this is necessary.}  */
1926           iconv (cd, NULL, NULL, &wrptr, &avail);
1928           break;
1929         @}
1930       insize += nread;
1932       /* @r{Do the conversion.}  */
1933       nconv = iconv (cd, &inptr, &insize, &wrptr, &avail);
1934       if (nconv == (size_t) -1)
1935         @{
1936           /* @r{Not everything went right.  It might only be}
1937              @r{an unfinished byte sequence at the end of the}
1938              @r{buffer.  Or it is a real problem.}  */
1939           if (errno == EINVAL)
1940             /* @r{This is harmless.  Simply move the unused}
1941                @r{bytes to the beginning of the buffer so that}
1942                @r{they can be used in the next round.}  */
1943             memmove (inbuf, inptr, insize);
1944           else
1945             @{
1946               /* @r{It is a real problem.  Maybe we ran out of}
1947                  @r{space in the output buffer or we have invalid}
1948                  @r{input.  In any case back the file pointer to}
1949                  @r{the position of the last processed byte.}  */
1950               lseek (fd, -insize, SEEK_CUR);
1951               result = -1;
1952               break;
1953             @}
1954         @}
1955     @}
1957   /* @r{Terminate the output string.}  */
1958   if (avail >= sizeof (wchar_t))
1959     *((wchar_t *) wrptr) = L'\0';
1961   if (iconv_close (cd) != 0)
1962     perror ("iconv_close");
1964   return (wchar_t *) wrptr - outbuf;
1966 @end smallexample
1968 @cindex stateful
1969 This example shows the most important aspects of using the @code{iconv}
1970 functions.  It shows how successive calls to @code{iconv} can be used to
1971 convert large amounts of text.  The user does not have to care about
1972 stateful encodings as the functions take care of everything.
1974 An interesting point is the case where @code{iconv} returns an error and
1975 @code{errno} is set to @code{EINVAL}.  This is not really an error in the
1976 transformation.  It can happen whenever the input character set contains
1977 byte sequences of more than one byte for some character and texts are not
1978 processed in one piece.  In this case there is a chance that a multibyte
1979 sequence is cut.  The caller can then simply read the remainder of the
1980 takes and feed the offending bytes together with new character from the
1981 input to @code{iconv} and continue the work.  The internal state kept in
1982 the descriptor is @emph{not} unspecified after such an event as is the
1983 case with the conversion functions from the @w{ISO C} standard.
1985 The example also shows the problem of using wide character strings with
1986 @code{iconv}.  As explained in the description of the @code{iconv}
1987 function above, the function always takes a pointer to a @code{char}
1988 array and the available space is measured in bytes.  In the example, the
1989 output buffer is a wide character buffer; therefore, we use a local
1990 variable @var{wrptr} of type @code{char *}, which is used in the
1991 @code{iconv} calls.
1993 This looks rather innocent but can lead to problems on platforms that
1994 have tight restriction on alignment.  Therefore the caller of @code{iconv}
1995 has to make sure that the pointers passed are suitable for access of
1996 characters from the appropriate character set.  Since, in the
1997 above case, the input parameter to the function is a @code{wchar_t}
1998 pointer, this is the case (unless the user violates alignment when
1999 computing the parameter).  But in other situations, especially when
2000 writing generic functions where one does not know what type of character
2001 set one uses and, therefore, treats text as a sequence of bytes, it might
2002 become tricky.
2004 @node Other iconv Implementations
2005 @subsection Some Details about other @code{iconv} Implementations
2007 This is not really the place to discuss the @code{iconv} implementation
2008 of other systems but it is necessary to know a bit about them to write
2009 portable programs.  The above mentioned problems with the specification
2010 of the @code{iconv} functions can lead to portability issues.
2012 The first thing to notice is that, due to the large number of character
2013 sets in use, it is certainly not practical to encode the conversions
2014 directly in the C library.  Therefore, the conversion information must
2015 come from files outside the C library.  This is usually done in one or
2016 both of the following ways:
2018 @itemize @bullet
2019 @item
2020 The C library contains a set of generic conversion functions that can
2021 read the needed conversion tables and other information from data files.
2022 These files get loaded when necessary.
2024 This solution is problematic as it requires a great deal of effort to
2025 apply to all character sets (potentially an infinite set).  The
2026 differences in the structure of the different character sets is so large
2027 that many different variants of the table-processing functions must be
2028 developed.  In addition, the generic nature of these functions make them
2029 slower than specifically implemented functions.
2031 @item
2032 The C library only contains a framework that can dynamically load
2033 object files and execute the conversion functions contained therein.
2035 This solution provides much more flexibility.  The C library itself
2036 contains only very little code and therefore reduces the general memory
2037 footprint.  Also, with a documented interface between the C library and
2038 the loadable modules it is possible for third parties to extend the set
2039 of available conversion modules.  A drawback of this solution is that
2040 dynamic loading must be available.
2041 @end itemize
2043 Some implementations in commercial Unices implement a mixture of these
2044 possibilities; the majority implement only the second solution.  Using
2045 loadable modules moves the code out of the library itself and keeps
2046 the door open for extensions and improvements, but this design is also
2047 limiting on some platforms since not many platforms support dynamic
2048 loading in statically linked programs.  On platforms without this
2049 capability it is therefore not possible to use this interface in
2050 statically linked programs.  @Theglibc{} has, on ELF platforms, no
2051 problems with dynamic loading in these situations; therefore, this
2052 point is moot.  The danger is that one gets acquainted with this
2053 situation and forgets about the restrictions on other systems.
2055 A second thing to know about other @code{iconv} implementations is that
2056 the number of available conversions is often very limited.  Some
2057 implementations provide, in the standard release (not special
2058 international or developer releases), at most 100 to 200 conversion
2059 possibilities.  This does not mean 200 different character sets are
2060 supported; for example, conversions from one character set to a set of 10
2061 others might count as 10 conversions.  Together with the other direction
2062 this makes 20 conversion possibilities used up by one character set.  One
2063 can imagine the thin coverage these platforms provide.  Some Unix vendors
2064 even provide only a handful of conversions, which renders them useless for
2065 almost all uses.
2067 This directly leads to a third and probably the most problematic point.
2068 The way the @code{iconv} conversion functions are implemented on all
2069 known Unix systems and the availability of the conversion functions from
2070 character set @math{@cal{A}} to @math{@cal{B}} and the conversion from
2071 @math{@cal{B}} to @math{@cal{C}} does @emph{not} imply that the
2072 conversion from @math{@cal{A}} to @math{@cal{C}} is available.
2074 This might not seem unreasonable and problematic at first, but it is a
2075 quite big problem as one will notice shortly after hitting it.  To show
2076 the problem we assume to write a program that has to convert from
2077 @math{@cal{A}} to @math{@cal{C}}.  A call like
2079 @smallexample
2080 cd = iconv_open ("@math{@cal{C}}", "@math{@cal{A}}");
2081 @end smallexample
2083 @noindent
2084 fails according to the assumption above.  But what does the program
2085 do now?  The conversion is necessary; therefore, simply giving up is not
2086 an option.
2088 This is a nuisance.  The @code{iconv} function should take care of this.
2089 But how should the program proceed from here on?  If it tries to convert
2090 to character set @math{@cal{B}}, first the two @code{iconv_open}
2091 calls
2093 @smallexample
2094 cd1 = iconv_open ("@math{@cal{B}}", "@math{@cal{A}}");
2095 @end smallexample
2097 @noindent
2100 @smallexample
2101 cd2 = iconv_open ("@math{@cal{C}}", "@math{@cal{B}}");
2102 @end smallexample
2104 @noindent
2105 will succeed, but how to find @math{@cal{B}}?
2107 Unfortunately, the answer is: there is no general solution.  On some
2108 systems guessing might help.  On those systems most character sets can
2109 convert to and from UTF-8 encoded @w{ISO 10646} or Unicode text.  Besides
2110 this only some very system-specific methods can help.  Since the
2111 conversion functions come from loadable modules and these modules must
2112 be stored somewhere in the filesystem, one @emph{could} try to find them
2113 and determine from the available file which conversions are available
2114 and whether there is an indirect route from @math{@cal{A}} to
2115 @math{@cal{C}}.
2117 This example shows one of the design errors of @code{iconv} mentioned
2118 above.  It should at least be possible to determine the list of available
2119 conversions programmatically so that if @code{iconv_open} says there is no
2120 such conversion, one could make sure this also is true for indirect
2121 routes.
2123 @node glibc iconv Implementation
2124 @subsection The @code{iconv} Implementation in @theglibc{}
2126 After reading about the problems of @code{iconv} implementations in the
2127 last section it is certainly good to note that the implementation in
2128 @theglibc{} has none of the problems mentioned above.  What
2129 follows is a step-by-step analysis of the points raised above.  The
2130 evaluation is based on the current state of the development (as of
2131 January 1999).  The development of the @code{iconv} functions is not
2132 complete, but basic functionality has solidified.
2134 @Theglibc{}'s @code{iconv} implementation uses shared loadable
2135 modules to implement the conversions.  A very small number of
2136 conversions are built into the library itself but these are only rather
2137 trivial conversions.
2139 All the benefits of loadable modules are available in the @glibcadj{}
2140 implementation.  This is especially appealing since the interface is
2141 well documented (see below), and it, therefore, is easy to write new
2142 conversion modules.  The drawback of using loadable objects is not a
2143 problem in @theglibc{}, at least on ELF systems.  Since the
2144 library is able to load shared objects even in statically linked
2145 binaries, static linking need not be forbidden in case one wants to use
2146 @code{iconv}.
2148 The second mentioned problem is the number of supported conversions.
2149 Currently, @theglibc{} supports more than 150 character sets.  The
2150 way the implementation is designed the number of supported conversions
2151 is greater than 22350 (@math{150} times @math{149}).  If any conversion
2152 from or to a character set is missing, it can be added easily.
2154 Particularly impressive as it may be, this high number is due to the
2155 fact that the @glibcadj{} implementation of @code{iconv} does not have
2156 the third problem mentioned above (i.e., whenever there is a conversion
2157 from a character set @math{@cal{A}} to @math{@cal{B}} and from
2158 @math{@cal{B}} to @math{@cal{C}} it is always possible to convert from
2159 @math{@cal{A}} to @math{@cal{C}} directly).  If the @code{iconv_open}
2160 returns an error and sets @code{errno} to @code{EINVAL}, there is no
2161 known way, directly or indirectly, to perform the wanted conversion.
2163 @cindex triangulation
2164 Triangulation is achieved by providing for each character set a
2165 conversion from and to UCS-4 encoded @w{ISO 10646}.  Using @w{ISO 10646}
2166 as an intermediate representation it is possible to @dfn{triangulate}
2167 (i.e., convert with an intermediate representation).
2169 There is no inherent requirement to provide a conversion to @w{ISO
2170 10646} for a new character set, and it is also possible to provide other
2171 conversions where neither source nor destination character set is @w{ISO
2172 10646}.  The existing set of conversions is simply meant to cover all
2173 conversions that might be of interest.
2175 @cindex ISO-2022-JP
2176 @cindex EUC-JP
2177 All currently available conversions use the triangulation method above,
2178 making conversion run unnecessarily slow.  If, for example, somebody
2179 often needs the conversion from ISO-2022-JP to EUC-JP, a quicker solution
2180 would involve direct conversion between the two character sets, skipping
2181 the input to @w{ISO 10646} first.  The two character sets of interest
2182 are much more similar to each other than to @w{ISO 10646}.
2184 In such a situation one easily can write a new conversion and provide it
2185 as a better alternative.  The @glibcadj{} @code{iconv} implementation
2186 would automatically use the module implementing the conversion if it is
2187 specified to be more efficient.
2189 @subsubsection Format of @file{gconv-modules} files
2191 All information about the available conversions comes from a file named
2192 @file{gconv-modules}, which can be found in any of the directories along
2193 the @code{GCONV_PATH}.  The @file{gconv-modules} files are line-oriented
2194 text files, where each of the lines has one of the following formats:
2196 @itemize @bullet
2197 @item
2198 If the first non-whitespace character is a @kbd{#} the line contains only
2199 comments and is ignored.
2201 @item
2202 Lines starting with @code{alias} define an alias name for a character
2203 set.  Two more words are expected on the line.  The first word
2204 defines the alias name, and the second defines the original name of the
2205 character set.  The effect is that it is possible to use the alias name
2206 in the @var{fromset} or @var{toset} parameters of @code{iconv_open} and
2207 achieve the same result as when using the real character set name.
2209 This is quite important as a character set has often many different
2210 names.  There is normally an official name but this need not correspond to
2211 the most popular name.  Besides this many character sets have special
2212 names that are somehow constructed.  For example, all character sets
2213 specified by the ISO have an alias of the form @code{ISO-IR-@var{nnn}}
2214 where @var{nnn} is the registration number.  This allows programs that
2215 know about the registration number to construct character set names and
2216 use them in @code{iconv_open} calls.  More on the available names and
2217 aliases follows below.
2219 @item
2220 Lines starting with @code{module} introduce an available conversion
2221 module.  These lines must contain three or four more words.
2223 The first word specifies the source character set, the second word the
2224 destination character set of conversion implemented in this module, and
2225 the third word is the name of the loadable module.  The filename is
2226 constructed by appending the usual shared object suffix (normally
2227 @file{.so}) and this file is then supposed to be found in the same
2228 directory the @file{gconv-modules} file is in.  The last word on the line,
2229 which is optional, is a numeric value representing the cost of the
2230 conversion.  If this word is missing, a cost of @math{1} is assumed.  The
2231 numeric value itself does not matter that much; what counts are the
2232 relative values of the sums of costs for all possible conversion paths.
2233 Below is a more precise description of the use of the cost value.
2234 @end itemize
2236 Returning to the example above where one has written a module to directly
2237 convert from ISO-2022-JP to EUC-JP and back.  All that has to be done is
2238 to put the new module, let its name be ISO2022JP-EUCJP.so, in a directory
2239 and add a file @file{gconv-modules} with the following content in the
2240 same directory:
2242 @smallexample
2243 module  ISO-2022-JP//   EUC-JP//        ISO2022JP-EUCJP    1
2244 module  EUC-JP//        ISO-2022-JP//   ISO2022JP-EUCJP    1
2245 @end smallexample
2247 To see why this is sufficient, it is necessary to understand how the
2248 conversion used by @code{iconv} (and described in the descriptor) is
2249 selected.  The approach to this problem is quite simple.
2251 At the first call of the @code{iconv_open} function the program reads
2252 all available @file{gconv-modules} files and builds up two tables: one
2253 containing all the known aliases and another that contains the
2254 information about the conversions and which shared object implements
2255 them.
2257 @subsubsection Finding the conversion path in @code{iconv}
2259 The set of available conversions form a directed graph with weighted
2260 edges.  The weights on the edges are the costs specified in the
2261 @file{gconv-modules} files.  The @code{iconv_open} function uses an
2262 algorithm suitable for search for the best path in such a graph and so
2263 constructs a list of conversions that must be performed in succession
2264 to get the transformation from the source to the destination character
2265 set.
2267 Explaining why the above @file{gconv-modules} files allows the
2268 @code{iconv} implementation to resolve the specific ISO-2022-JP to
2269 EUC-JP conversion module instead of the conversion coming with the
2270 library itself is straightforward.  Since the latter conversion takes two
2271 steps (from ISO-2022-JP to @w{ISO 10646} and then from @w{ISO 10646} to
2272 EUC-JP), the cost is @math{1+1 = 2}.  The above @file{gconv-modules}
2273 file, however, specifies that the new conversion modules can perform this
2274 conversion with only the cost of @math{1}.
2276 A mysterious item about the @file{gconv-modules} file above (and also
2277 the file coming with @theglibc{}) are the names of the character
2278 sets specified in the @code{module} lines.  Why do almost all the names
2279 end in @code{//}?  And this is not all: the names can actually be
2280 regular expressions.  At this point in time this mystery should not be
2281 revealed, unless you have the relevant spell-casting materials: ashes
2282 from an original @w{DOS 6.2} boot disk burnt in effigy, a crucifix
2283 blessed by St.@: Emacs, assorted herbal roots from Central America, sand
2284 from Cebu, etc.  Sorry!  @strong{The part of the implementation where
2285 this is used is not yet finished.  For now please simply follow the
2286 existing examples.  It'll become clearer once it is. --drepper}
2288 A last remark about the @file{gconv-modules} is about the names not
2289 ending with @code{//}.  A character set named @code{INTERNAL} is often
2290 mentioned.  From the discussion above and the chosen name it should have
2291 become clear that this is the name for the representation used in the
2292 intermediate step of the triangulation.  We have said that this is UCS-4
2293 but actually that is not quite right.  The UCS-4 specification also
2294 includes the specification of the byte ordering used.  Since a UCS-4 value
2295 consists of four bytes, a stored value is affected by byte ordering.  The
2296 internal representation is @emph{not} the same as UCS-4 in case the byte
2297 ordering of the processor (or at least the running process) is not the
2298 same as the one required for UCS-4.  This is done for performance reasons
2299 as one does not want to perform unnecessary byte-swapping operations if
2300 one is not interested in actually seeing the result in UCS-4.  To avoid
2301 trouble with endianness, the internal representation consistently is named
2302 @code{INTERNAL} even on big-endian systems where the representations are
2303 identical.
2305 @subsubsection @code{iconv} module data structures
2307 So far this section has described how modules are located and considered
2308 to be used.  What remains to be described is the interface of the modules
2309 so that one can write new ones.  This section describes the interface as
2310 it is in use in January 1999.  The interface will change a bit in the
2311 future but, with luck, only in an upwardly compatible way.
2313 The definitions necessary to write new modules are publicly available
2314 in the non-standard header @file{gconv.h}.  The following text,
2315 therefore, describes the definitions from this header file.  First,
2316 however, it is necessary to get an overview.
2318 From the perspective of the user of @code{iconv} the interface is quite
2319 simple: the @code{iconv_open} function returns a handle that can be used
2320 in calls to @code{iconv}, and finally the handle is freed with a call to
2321 @code{iconv_close}.  The problem is that the handle has to be able to
2322 represent the possibly long sequences of conversion steps and also the
2323 state of each conversion since the handle is all that is passed to the
2324 @code{iconv} function.  Therefore, the data structures are really the
2325 elements necessary to understanding the implementation.
2327 We need two different kinds of data structures.  The first describes the
2328 conversion and the second describes the state etc.  There are really two
2329 type definitions like this in @file{gconv.h}.
2330 @pindex gconv.h
2332 @deftp {Data type} {struct __gconv_step}
2333 @standards{GNU, gconv.h}
2334 This data structure describes one conversion a module can perform.  For
2335 each function in a loaded module with conversion functions there is
2336 exactly one object of this type.  This object is shared by all users of
2337 the conversion (i.e., this object does not contain any information
2338 corresponding to an actual conversion; it only describes the conversion
2339 itself).
2341 @table @code
2342 @item struct __gconv_loaded_object *__shlib_handle
2343 @itemx const char *__modname
2344 @itemx int __counter
2345 All these elements of the structure are used internally in the C library
2346 to coordinate loading and unloading the shared object.  One must not expect any
2347 of the other elements to be available or initialized.
2349 @item const char *__from_name
2350 @itemx const char *__to_name
2351 @code{__from_name} and @code{__to_name} contain the names of the source and
2352 destination character sets.  They can be used to identify the actual
2353 conversion to be carried out since one module might implement conversions
2354 for more than one character set and/or direction.
2356 @item gconv_fct __fct
2357 @itemx gconv_init_fct __init_fct
2358 @itemx gconv_end_fct __end_fct
2359 These elements contain pointers to the functions in the loadable module.
2360 The interface will be explained below.
2362 @item int __min_needed_from
2363 @itemx int __max_needed_from
2364 @itemx int __min_needed_to
2365 @itemx int __max_needed_to;
2366 These values have to be supplied in the init function of the module.  The
2367 @code{__min_needed_from} value specifies how many bytes a character of
2368 the source character set at least needs.  The @code{__max_needed_from}
2369 specifies the maximum value that also includes possible shift sequences.
2371 The @code{__min_needed_to} and @code{__max_needed_to} values serve the
2372 same purpose as @code{__min_needed_from} and @code{__max_needed_from} but
2373 this time for the destination character set.
2375 It is crucial that these values be accurate since otherwise the
2376 conversion functions will have problems or not work at all.
2378 @item int __stateful
2379 This element must also be initialized by the init function.
2380 @code{int __stateful} is nonzero if the source character set is stateful.
2381 Otherwise it is zero.
2383 @item void *__data
2384 This element can be used freely by the conversion functions in the
2385 module.  @code{void *__data} can be used to communicate extra information
2386 from one call to another.  @code{void *__data} need not be initialized if
2387 not needed at all.  If @code{void *__data} element is assigned a pointer
2388 to dynamically allocated memory (presumably in the init function) it has
2389 to be made sure that the end function deallocates the memory.  Otherwise
2390 the application will leak memory.
2392 It is important to be aware that this data structure is shared by all
2393 users of this specification conversion and therefore the @code{__data}
2394 element must not contain data specific to one specific use of the
2395 conversion function.
2396 @end table
2397 @end deftp
2399 @deftp {Data type} {struct __gconv_step_data}
2400 @standards{GNU, gconv.h}
2401 This is the data structure that contains the information specific to
2402 each use of the conversion functions.
2405 @table @code
2406 @item char *__outbuf
2407 @itemx char *__outbufend
2408 These elements specify the output buffer for the conversion step.  The
2409 @code{__outbuf} element points to the beginning of the buffer, and
2410 @code{__outbufend} points to the byte following the last byte in the
2411 buffer.  The conversion function must not assume anything about the size
2412 of the buffer but it can be safely assumed there is room for at
2413 least one complete character in the output buffer.
2415 Once the conversion is finished, if the conversion is the last step, the
2416 @code{__outbuf} element must be modified to point after the last byte
2417 written into the buffer to signal how much output is available.  If this
2418 conversion step is not the last one, the element must not be modified.
2419 The @code{__outbufend} element must not be modified.
2421 @item int __is_last
2422 This element is nonzero if this conversion step is the last one.  This
2423 information is necessary for the recursion.  See the description of the
2424 conversion function internals below.  This element must never be
2425 modified.
2427 @item int __invocation_counter
2428 The conversion function can use this element to see how many calls of
2429 the conversion function already happened.  Some character sets require a
2430 certain prolog when generating output, and by comparing this value with
2431 zero, one can find out whether it is the first call and whether,
2432 therefore, the prolog should be emitted.  This element must never be
2433 modified.
2435 @item int __internal_use
2436 This element is another one rarely used but needed in certain
2437 situations.  It is assigned a nonzero value in case the conversion
2438 functions are used to implement @code{mbsrtowcs} et.al.@: (i.e., the
2439 function is not used directly through the @code{iconv} interface).
2441 This sometimes makes a difference as it is expected that the
2442 @code{iconv} functions are used to translate entire texts while the
2443 @code{mbsrtowcs} functions are normally used only to convert single
2444 strings and might be used multiple times to convert entire texts.
2446 But in this situation we would have problem complying with some rules of
2447 the character set specification.  Some character sets require a prolog,
2448 which must appear exactly once for an entire text.  If a number of
2449 @code{mbsrtowcs} calls are used to convert the text, only the first call
2450 must add the prolog.  However, because there is no communication between the
2451 different calls of @code{mbsrtowcs}, the conversion functions have no
2452 possibility to find this out.  The situation is different for sequences
2453 of @code{iconv} calls since the handle allows access to the needed
2454 information.
2456 The @code{int __internal_use} element is mostly used together with
2457 @code{__invocation_counter} as follows:
2459 @smallexample
2460 if (!data->__internal_use
2461      && data->__invocation_counter == 0)
2462   /* @r{Emit prolog.}  */
2463   @dots{}
2464 @end smallexample
2466 This element must never be modified.
2468 @item mbstate_t *__statep
2469 The @code{__statep} element points to an object of type @code{mbstate_t}
2470 (@pxref{Keeping the state}).  The conversion of a stateful character
2471 set must use the object pointed to by @code{__statep} to store
2472 information about the conversion state.  The @code{__statep} element
2473 itself must never be modified.
2475 @item mbstate_t __state
2476 This element must @emph{never} be used directly.  It is only part of
2477 this structure to have the needed space allocated.
2478 @end table
2479 @end deftp
2481 @subsubsection @code{iconv} module interfaces
2483 With the knowledge about the data structures we now can describe the
2484 conversion function itself.  To understand the interface a bit of
2485 knowledge is necessary about the functionality in the C library that
2486 loads the objects with the conversions.
2488 It is often the case that one conversion is used more than once (i.e.,
2489 there are several @code{iconv_open} calls for the same set of character
2490 sets during one program run).  The @code{mbsrtowcs} et.al.@: functions in
2491 @theglibc{} also use the @code{iconv} functionality, which
2492 increases the number of uses of the same functions even more.
2494 Because of this multiple use of conversions, the modules do not get
2495 loaded exclusively for one conversion.  Instead a module once loaded can
2496 be used by an arbitrary number of @code{iconv} or @code{mbsrtowcs} calls
2497 at the same time.  The splitting of the information between conversion-
2498 function-specific information and conversion data makes this possible.
2499 The last section showed the two data structures used to do this.
2501 This is of course also reflected in the interface and semantics of the
2502 functions that the modules must provide.  There are three functions that
2503 must have the following names:
2505 @table @code
2506 @item gconv_init
2507 The @code{gconv_init} function initializes the conversion function
2508 specific data structure.  This very same object is shared by all
2509 conversions that use this conversion and, therefore, no state information
2510 about the conversion itself must be stored in here.  If a module
2511 implements more than one conversion, the @code{gconv_init} function will
2512 be called multiple times.
2514 @item gconv_end
2515 The @code{gconv_end} function is responsible for freeing all resources
2516 allocated by the @code{gconv_init} function.  If there is nothing to do,
2517 this function can be missing.  Special care must be taken if the module
2518 implements more than one conversion and the @code{gconv_init} function
2519 does not allocate the same resources for all conversions.
2521 @item gconv
2522 This is the actual conversion function.  It is called to convert one
2523 block of text.  It gets passed the conversion step information
2524 initialized by @code{gconv_init} and the conversion data, specific to
2525 this use of the conversion functions.
2526 @end table
2528 There are three data types defined for the three module interface
2529 functions and these define the interface.
2531 @deftypevr {Data type} int {(*__gconv_init_fct)} (struct __gconv_step *)
2532 @standards{GNU, gconv.h}
2533 This specifies the interface of the initialization function of the
2534 module.  It is called exactly once for each conversion the module
2535 implements.
2537 As explained in the description of the @code{struct __gconv_step} data
2538 structure above the initialization function has to initialize parts of
2541 @table @code
2542 @item __min_needed_from
2543 @itemx __max_needed_from
2544 @itemx __min_needed_to
2545 @itemx __max_needed_to
2546 These elements must be initialized to the exact numbers of the minimum
2547 and maximum number of bytes used by one character in the source and
2548 destination character sets, respectively.  If the characters all have the
2549 same size, the minimum and maximum values are the same.
2551 @item __stateful
2552 This element must be initialized to a nonzero value if the source
2553 character set is stateful.  Otherwise it must be zero.
2554 @end table
2556 If the initialization function needs to communicate some information
2557 to the conversion function, this communication can happen using the
2558 @code{__data} element of the @code{__gconv_step} structure.  But since
2559 this data is shared by all the conversions, it must not be modified by
2560 the conversion function.  The example below shows how this can be used.
2562 @smallexample
2563 #define MIN_NEEDED_FROM         1
2564 #define MAX_NEEDED_FROM         4
2565 #define MIN_NEEDED_TO           4
2566 #define MAX_NEEDED_TO           4
2569 gconv_init (struct __gconv_step *step)
2571   /* @r{Determine which direction.}  */
2572   struct iso2022jp_data *new_data;
2573   enum direction dir = illegal_dir;
2574   enum variant var = illegal_var;
2575   int result;
2577   if (__strcasecmp (step->__from_name, "ISO-2022-JP//") == 0)
2578     @{
2579       dir = from_iso2022jp;
2580       var = iso2022jp;
2581     @}
2582   else if (__strcasecmp (step->__to_name, "ISO-2022-JP//") == 0)
2583     @{
2584       dir = to_iso2022jp;
2585       var = iso2022jp;
2586     @}
2587   else if (__strcasecmp (step->__from_name, "ISO-2022-JP-2//") == 0)
2588     @{
2589       dir = from_iso2022jp;
2590       var = iso2022jp2;
2591     @}
2592   else if (__strcasecmp (step->__to_name, "ISO-2022-JP-2//") == 0)
2593     @{
2594       dir = to_iso2022jp;
2595       var = iso2022jp2;
2596     @}
2598   result = __GCONV_NOCONV;
2599   if (dir != illegal_dir)
2600     @{
2601       new_data = (struct iso2022jp_data *)
2602         malloc (sizeof (struct iso2022jp_data));
2604       result = __GCONV_NOMEM;
2605       if (new_data != NULL)
2606         @{
2607           new_data->dir = dir;
2608           new_data->var = var;
2609           step->__data = new_data;
2611           if (dir == from_iso2022jp)
2612             @{
2613               step->__min_needed_from = MIN_NEEDED_FROM;
2614               step->__max_needed_from = MAX_NEEDED_FROM;
2615               step->__min_needed_to = MIN_NEEDED_TO;
2616               step->__max_needed_to = MAX_NEEDED_TO;
2617             @}
2618           else
2619             @{
2620               step->__min_needed_from = MIN_NEEDED_TO;
2621               step->__max_needed_from = MAX_NEEDED_TO;
2622               step->__min_needed_to = MIN_NEEDED_FROM;
2623               step->__max_needed_to = MAX_NEEDED_FROM + 2;
2624             @}
2626           /* @r{Yes, this is a stateful encoding.}  */
2627           step->__stateful = 1;
2629           result = __GCONV_OK;
2630         @}
2631     @}
2633   return result;
2635 @end smallexample
2637 The function first checks which conversion is wanted.  The module from
2638 which this function is taken implements four different conversions;
2639 which one is selected can be determined by comparing the names.  The
2640 comparison should always be done without paying attention to the case.
2642 Next, a data structure, which contains the necessary information about
2643 which conversion is selected, is allocated.  The data structure
2644 @code{struct iso2022jp_data} is locally defined since, outside the
2645 module, this data is not used at all.  Please note that if all four
2646 conversions this module supports are requested there are four data
2647 blocks.
2649 One interesting thing is the initialization of the @code{__min_} and
2650 @code{__max_} elements of the step data object.  A single ISO-2022-JP
2651 character can consist of one to four bytes.  Therefore the
2652 @code{MIN_NEEDED_FROM} and @code{MAX_NEEDED_FROM} macros are defined
2653 this way.  The output is always the @code{INTERNAL} character set (aka
2654 UCS-4) and therefore each character consists of exactly four bytes.  For
2655 the conversion from @code{INTERNAL} to ISO-2022-JP we have to take into
2656 account that escape sequences might be necessary to switch the character
2657 sets.  Therefore the @code{__max_needed_to} element for this direction
2658 gets assigned @code{MAX_NEEDED_FROM + 2}.  This takes into account the
2659 two bytes needed for the escape sequences to signal the switching.  The
2660 asymmetry in the maximum values for the two directions can be explained
2661 easily: when reading ISO-2022-JP text, escape sequences can be handled
2662 alone (i.e., it is not necessary to process a real character since the
2663 effect of the escape sequence can be recorded in the state information).
2664 The situation is different for the other direction.  Since it is in
2665 general not known which character comes next, one cannot emit escape
2666 sequences to change the state in advance.  This means the escape
2667 sequences have to be emitted together with the next character.
2668 Therefore one needs more room than only for the character itself.
2670 The possible return values of the initialization function are:
2672 @table @code
2673 @item __GCONV_OK
2674 The initialization succeeded
2675 @item __GCONV_NOCONV
2676 The requested conversion is not supported in the module.  This can
2677 happen if the @file{gconv-modules} file has errors.
2678 @item __GCONV_NOMEM
2679 Memory required to store additional information could not be allocated.
2680 @end table
2681 @end deftypevr
2683 The function called before the module is unloaded is significantly
2684 easier.  It often has nothing at all to do; in which case it can be left
2685 out completely.
2687 @deftypevr {Data type} void {(*__gconv_end_fct)} (struct gconv_step *)
2688 @standards{GNU, gconv.h}
2689 The task of this function is to free all resources allocated in the
2690 initialization function.  Therefore only the @code{__data} element of
2691 the object pointed to by the argument is of interest.  Continuing the
2692 example from the initialization function, the finalization function
2693 looks like this:
2695 @smallexample
2696 void
2697 gconv_end (struct __gconv_step *data)
2699   free (data->__data);
2701 @end smallexample
2702 @end deftypevr
2704 The most important function is the conversion function itself, which can
2705 get quite complicated for complex character sets.  But since this is not
2706 of interest here, we will only describe a possible skeleton for the
2707 conversion function.
2709 @deftypevr {Data type} int {(*__gconv_fct)} (struct __gconv_step *, struct __gconv_step_data *, const char **, const char *, size_t *, int)
2710 @standards{GNU, gconv.h}
2711 The conversion function can be called for two basic reasons: to convert
2712 text or to reset the state.  From the description of the @code{iconv}
2713 function it can be seen why the flushing mode is necessary.  What mode
2714 is selected is determined by the sixth argument, an integer.  This
2715 argument being nonzero means that flushing is selected.
2717 Common to both modes is where the output buffer can be found.  The
2718 information about this buffer is stored in the conversion step data.  A
2719 pointer to this information is passed as the second argument to this
2720 function.  The description of the @code{struct __gconv_step_data}
2721 structure has more information on the conversion step data.
2723 @cindex stateful
2724 What has to be done for flushing depends on the source character set.
2725 If the source character set is not stateful, nothing has to be done.
2726 Otherwise the function has to emit a byte sequence to bring the state
2727 object into the initial state.  Once this all happened the other
2728 conversion modules in the chain of conversions have to get the same
2729 chance.  Whether another step follows can be determined from the
2730 @code{__is_last} element of the step data structure to which the first
2731 parameter points.
2733 The more interesting mode is when actual text has to be converted.  The
2734 first step in this case is to convert as much text as possible from the
2735 input buffer and store the result in the output buffer.  The start of the
2736 input buffer is determined by the third argument, which is a pointer to a
2737 pointer variable referencing the beginning of the buffer.  The fourth
2738 argument is a pointer to the byte right after the last byte in the buffer.
2740 The conversion has to be performed according to the current state if the
2741 character set is stateful.  The state is stored in an object pointed to
2742 by the @code{__statep} element of the step data (second argument).  Once
2743 either the input buffer is empty or the output buffer is full the
2744 conversion stops.  At this point, the pointer variable referenced by the
2745 third parameter must point to the byte following the last processed
2746 byte (i.e., if all of the input is consumed, this pointer and the fourth
2747 parameter have the same value).
2749 What now happens depends on whether this step is the last one.  If it is
2750 the last step, the only thing that has to be done is to update the
2751 @code{__outbuf} element of the step data structure to point after the
2752 last written byte.  This update gives the caller the information on how
2753 much text is available in the output buffer.  In addition, the variable
2754 pointed to by the fifth parameter, which is of type @code{size_t}, must
2755 be incremented by the number of characters (@emph{not bytes}) that were
2756 converted in a non-reversible way.  Then, the function can return.
2758 In case the step is not the last one, the later conversion functions have
2759 to get a chance to do their work.  Therefore, the appropriate conversion
2760 function has to be called.  The information about the functions is
2761 stored in the conversion data structures, passed as the first parameter.
2762 This information and the step data are stored in arrays, so the next
2763 element in both cases can be found by simple pointer arithmetic:
2765 @smallexample
2767 gconv (struct __gconv_step *step, struct __gconv_step_data *data,
2768        const char **inbuf, const char *inbufend, size_t *written,
2769        int do_flush)
2771   struct __gconv_step *next_step = step + 1;
2772   struct __gconv_step_data *next_data = data + 1;
2773   @dots{}
2774 @end smallexample
2776 The @code{next_step} pointer references the next step information and
2777 @code{next_data} the next data record.  The call of the next function
2778 therefore will look similar to this:
2780 @smallexample
2781   next_step->__fct (next_step, next_data, &outerr, outbuf,
2782                     written, 0)
2783 @end smallexample
2785 But this is not yet all.  Once the function call returns the conversion
2786 function might have some more to do.  If the return value of the function
2787 is @code{__GCONV_EMPTY_INPUT}, more room is available in the output
2788 buffer.  Unless the input buffer is empty, the conversion functions start
2789 all over again and process the rest of the input buffer.  If the return
2790 value is not @code{__GCONV_EMPTY_INPUT}, something went wrong and we have
2791 to recover from this.
2793 A requirement for the conversion function is that the input buffer
2794 pointer (the third argument) always point to the last character that
2795 was put in converted form into the output buffer.  This is trivially
2796 true after the conversion performed in the current step, but if the
2797 conversion functions deeper downstream stop prematurely, not all
2798 characters from the output buffer are consumed and, therefore, the input
2799 buffer pointers must be backed off to the right position.
2801 Correcting the input buffers is easy to do if the input and output
2802 character sets have a fixed width for all characters.  In this situation
2803 we can compute how many characters are left in the output buffer and,
2804 therefore, can correct the input buffer pointer appropriately with a
2805 similar computation.  Things are getting tricky if either character set
2806 has characters represented with variable length byte sequences, and it
2807 gets even more complicated if the conversion has to take care of the
2808 state.  In these cases the conversion has to be performed once again, from
2809 the known state before the initial conversion (i.e., if necessary the
2810 state of the conversion has to be reset and the conversion loop has to be
2811 executed again).  The difference now is that it is known how much input
2812 must be created, and the conversion can stop before converting the first
2813 unused character.  Once this is done the input buffer pointers must be
2814 updated again and the function can return.
2816 One final thing should be mentioned.  If it is necessary for the
2817 conversion to know whether it is the first invocation (in case a prolog
2818 has to be emitted), the conversion function should increment the
2819 @code{__invocation_counter} element of the step data structure just
2820 before returning to the caller.  See the description of the @code{struct
2821 __gconv_step_data} structure above for more information on how this can
2822 be used.
2824 The return value must be one of the following values:
2826 @table @code
2827 @item __GCONV_EMPTY_INPUT
2828 All input was consumed and there is room left in the output buffer.
2829 @item __GCONV_FULL_OUTPUT
2830 No more room in the output buffer.  In case this is not the last step
2831 this value is propagated down from the call of the next conversion
2832 function in the chain.
2833 @item __GCONV_INCOMPLETE_INPUT
2834 The input buffer is not entirely empty since it contains an incomplete
2835 character sequence.
2836 @end table
2838 The following example provides a framework for a conversion function.
2839 In case a new conversion has to be written the holes in this
2840 implementation have to be filled and that is it.
2842 @smallexample
2844 gconv (struct __gconv_step *step, struct __gconv_step_data *data,
2845        const char **inbuf, const char *inbufend, size_t *written,
2846        int do_flush)
2848   struct __gconv_step *next_step = step + 1;
2849   struct __gconv_step_data *next_data = data + 1;
2850   gconv_fct fct = next_step->__fct;
2851   int status;
2853   /* @r{If the function is called with no input this means we have}
2854      @r{to reset to the initial state.  The possibly partly}
2855      @r{converted input is dropped.}  */
2856   if (do_flush)
2857     @{
2858       status = __GCONV_OK;
2860       /* @r{Possible emit a byte sequence which put the state object}
2861          @r{into the initial state.}  */
2863       /* @r{Call the steps down the chain if there are any but only}
2864          @r{if we successfully emitted the escape sequence.}  */
2865       if (status == __GCONV_OK && ! data->__is_last)
2866         status = fct (next_step, next_data, NULL, NULL,
2867                       written, 1);
2868     @}
2869   else
2870     @{
2871       /* @r{We preserve the initial values of the pointer variables.}  */
2872       const char *inptr = *inbuf;
2873       char *outbuf = data->__outbuf;
2874       char *outend = data->__outbufend;
2875       char *outptr;
2877       do
2878         @{
2879           /* @r{Remember the start value for this round.}  */
2880           inptr = *inbuf;
2881           /* @r{The outbuf buffer is empty.}  */
2882           outptr = outbuf;
2884           /* @r{For stateful encodings the state must be safe here.}  */
2886           /* @r{Run the conversion loop.  @code{status} is set}
2887              @r{appropriately afterwards.}  */
2889           /* @r{If this is the last step, leave the loop.  There is}
2890              @r{nothing we can do.}  */
2891           if (data->__is_last)
2892             @{
2893               /* @r{Store information about how many bytes are}
2894                  @r{available.}  */
2895               data->__outbuf = outbuf;
2897              /* @r{If any non-reversible conversions were performed,}
2898                 @r{add the number to @code{*written}.}  */
2900              break;
2901            @}
2903           /* @r{Write out all output that was produced.}  */
2904           if (outbuf > outptr)
2905             @{
2906               const char *outerr = data->__outbuf;
2907               int result;
2909               result = fct (next_step, next_data, &outerr,
2910                             outbuf, written, 0);
2912               if (result != __GCONV_EMPTY_INPUT)
2913                 @{
2914                   if (outerr != outbuf)
2915                     @{
2916                       /* @r{Reset the input buffer pointer.  We}
2917                          @r{document here the complex case.}  */
2918                       size_t nstatus;
2920                       /* @r{Reload the pointers.}  */
2921                       *inbuf = inptr;
2922                       outbuf = outptr;
2924                       /* @r{Possibly reset the state.}  */
2926                       /* @r{Redo the conversion, but this time}
2927                          @r{the end of the output buffer is at}
2928                          @r{@code{outerr}.}  */
2929                     @}
2931                   /* @r{Change the status.}  */
2932                   status = result;
2933                 @}
2934               else
2935                 /* @r{All the output is consumed, we can make}
2936                    @r{ another run if everything was ok.}  */
2937                 if (status == __GCONV_FULL_OUTPUT)
2938                   status = __GCONV_OK;
2939            @}
2940         @}
2941       while (status == __GCONV_OK);
2943       /* @r{We finished one use of this step.}  */
2944       ++data->__invocation_counter;
2945     @}
2947   return status;
2949 @end smallexample
2950 @end deftypevr
2952 This information should be sufficient to write new modules.  Anybody
2953 doing so should also take a look at the available source code in the
2954 @glibcadj{} sources.  It contains many examples of working and optimized
2955 modules.
2957 @c File charset.texi edited October 2001 by Dennis Grace, IBM Corporation