charset.texi 129 KB

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