2
0

cwstring.pp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 2005 by Florian Klaempfl,
  4. member of the Free Pascal development team.
  5. libc based wide string support
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. {$mode objfpc}
  13. {$inline on}
  14. {$implicitexceptions off}
  15. unit cwstring;
  16. interface
  17. procedure SetCWidestringManager;
  18. implementation
  19. {$linklib c}
  20. // Linux (and maybe glibc platforms in general), have iconv in glibc.
  21. {$if defined(linux) or defined(solaris)}
  22. {$define iconv_is_in_libc}
  23. {$endif}
  24. {$ifdef netbsd}
  25. {$ifdef TEST_ICONV_LIBC}
  26. {$define iconv_is_in_libc}
  27. {$endif}
  28. {$endif}
  29. {$ifndef iconv_is_in_libc}
  30. {$if defined(haiku)}
  31. {$linklib textencoding}
  32. {$else}
  33. {$linklib iconv}
  34. {$endif}
  35. {$define useiconv}
  36. {$endif not iconv_is_in_libc}
  37. {$i rtldefs.inc}
  38. Uses
  39. BaseUnix,
  40. ctypes,
  41. unix,
  42. unixtype,
  43. initc,
  44. dynlibs,
  45. unixcp;
  46. Const
  47. {$ifndef useiconv}
  48. libiconvname='c'; // is in libc under Linux.
  49. libprefix='lib';
  50. {$else}
  51. {$ifdef haiku}
  52. libiconvname='textencoding'; // is in libtextencoding under Haiku
  53. libprefix='lib';
  54. {$else}
  55. {$if defined(darwin) or defined(aix)}
  56. libiconvname='libiconv';
  57. libprefix='';
  58. {$else}
  59. libiconvname='iconv';
  60. libprefix='lib';
  61. {$endif}
  62. {$endif}
  63. {$endif}
  64. { helper functions from libc }
  65. function towlower(__wc:wint_t):wint_t;cdecl;external clib name 'towlower';
  66. function towupper(__wc:wint_t):wint_t;cdecl;external clib name 'towupper';
  67. function wcscoll (__s1:pwchar_t; __s2:pwchar_t):cint;cdecl;external clib name 'wcscoll';
  68. function strcoll (__s1:pchar; __s2:pchar):cint;cdecl;external clib name 'strcoll';
  69. {$ifdef netbsd}
  70. { NetBSD has a new setlocale function defined in /usr/include/locale.h
  71. that should be used }
  72. function setlocale(category: cint; locale: pchar): pchar; cdecl; external clib name '__setlocale_mb_len_max_32';
  73. {$else}
  74. function setlocale(category: cint; locale: pchar): pchar; cdecl; external clib name 'setlocale';
  75. {$endif}
  76. {$if not(defined(beos) and not defined(haiku))}
  77. function mbrtowc(pwc: pwchar_t; const s: pchar; n: size_t; ps: pmbstate_t): size_t; cdecl; external clib name 'mbrtowc';
  78. function wcrtomb(s: pchar; wc: wchar_t; ps: pmbstate_t): size_t; cdecl; external clib name 'wcrtomb';
  79. function mbrlen(const s: pchar; n: size_t; ps: pmbstate_t): size_t; cdecl; external clib name 'mbrlen';
  80. {$else beos}
  81. function mbtowc(pwc: pwchar_t; const s: pchar; n: size_t): size_t; cdecl; external clib name 'mbtowc';
  82. function wctomb(s: pchar; wc: wchar_t): size_t; cdecl; external clib name 'wctomb';
  83. function mblen(const s: pchar; n: size_t): size_t; cdecl; external clib name 'mblen';
  84. {$endif beos}
  85. const
  86. {$if defined(linux)}
  87. __LC_CTYPE = 0;
  88. LC_ALL = 6;
  89. _NL_CTYPE_CLASS = (__LC_CTYPE shl 16);
  90. _NL_CTYPE_CODESET_NAME = (_NL_CTYPE_CLASS)+14;
  91. CODESET = _NL_CTYPE_CODESET_NAME;
  92. {$elseif defined(darwin)}
  93. CODESET = 0;
  94. LC_ALL = 0;
  95. {$elseif defined(FreeBSD)} // actually FreeBSD5. internationalisation is afaik not default on 4.
  96. __LC_CTYPE = 0;
  97. LC_ALL = 0;
  98. _NL_CTYPE_CLASS = (__LC_CTYPE shl 16);
  99. _NL_CTYPE_CODESET_NAME = (_NL_CTYPE_CLASS)+14;
  100. CODESET = 0; // _NL_CTYPE_CODESET_NAME;
  101. {$elseif defined(solaris)}
  102. {$define ACCEPT_646}
  103. CODESET=49;
  104. LC_ALL = 6;
  105. {$elseif defined(beos)}
  106. {$ifdef haiku}
  107. CODESET= 0; // Checked for Haiku
  108. LC_ALL = 0; // Checked for Haiku
  109. {$else}
  110. {$warning check correct value for BeOS}
  111. CODESET=49;
  112. LC_ALL = 6; // Checked for BeOS
  113. {$endif}
  114. ESysEILSEQ = EILSEQ;
  115. {$elseif defined(OpenBSD)}
  116. {$define ACCEPT_646}
  117. CODESET = 51;
  118. LC_ALL = 0;
  119. {$elseif defined(NetBSD)}
  120. {$define ACCEPT_646}
  121. CODESET = 51;
  122. LC_ALL = 0;
  123. {$elseif defined(aix)}
  124. CODESET = 49;
  125. LC_ALL = -1;
  126. {$elseif defined(dragonfly)}
  127. CODESET = 0;
  128. LC_ALL = 0;
  129. __LC_CTYPE = 0;
  130. _NL_CTYPE_CLASS = (__LC_CTYPE shl 16);
  131. _NL_CTYPE_CODESET_NAME = (_NL_CTYPE_CLASS)+14;
  132. {$else not aix}
  133. {$error lookup the value of CODESET in /usr/include/langinfo.h, and the value of LC_ALL in /usr/include/locale.h for your OS }
  134. // and while doing it, check if iconv is in libc, and if the symbols are prefixed with iconv_ or libiconv_
  135. {$endif}
  136. { unicode encoding name }
  137. {$ifdef FPC_LITTLE_ENDIAN}
  138. unicode_encoding2 = 'UTF-16LE';
  139. unicode_encoding4 = 'UCS-4LE';
  140. {$else FPC_LITTLE_ENDIAN}
  141. {$ifdef AIX}
  142. unicode_encoding2 = 'UTF-16';
  143. {$else AIX}
  144. unicode_encoding2 = 'UTF-16BE';
  145. unicode_encoding4 = 'UCS-4BE';
  146. {$endif AIX}
  147. {$endif FPC_LITTLE_ENDIAN}
  148. { en_US.UTF-8 needs maximally 6 chars, UCS-4/UTF-32 needs 4 }
  149. { -> 10 should be enough? Should actually use MB_CUR_MAX, but }
  150. { that's a libc macro mapped to internal functions/variables }
  151. { and thus not a stable external API on systems where libc }
  152. { breaks backwards compatibility every now and then }
  153. MB_CUR_MAX = 10;
  154. { Requests for iconvctl }
  155. ICONV_TRIVIALP = 0; // int *argument
  156. ICONV_GET_TRANSLITERATE = 1; // int *argument
  157. ICONV_SET_TRANSLITERATE = 2; // const int *argument
  158. ICONV_GET_DISCARD_ILSEQ = 3; // int *argument
  159. ICONV_SET_DISCARD_ILSEQ = 4; // const int *argument
  160. ICONV_SET_HOOKS = 5; // const struct iconv_hooks *argument
  161. ICONV_SET_FALLBACKS = 6; // const struct iconv_fallbacks *argument
  162. type
  163. piconv_t = ^iconv_t;
  164. iconv_t = pointer;
  165. nl_item = cint;
  166. {$ifdef haiku}
  167. function nl_langinfo(__item:nl_item):pchar;cdecl;external 'root' name 'nl_langinfo';
  168. {$else}
  169. {$ifndef beos}
  170. function nl_langinfo(__item:nl_item):pchar;cdecl;external libiconvname name 'nl_langinfo';
  171. {$endif}
  172. {$endif}
  173. {$if (not defined(bsd) and not defined(beos)) or defined(iconv_is_in_libc) or (defined(darwin) and not defined(cpupowerpc32))}
  174. function iconv_open(__tocode:pchar; __fromcode:pchar):iconv_t;cdecl;external libiconvname name 'iconv_open';
  175. function iconv(__cd:iconv_t; __inbuf:ppchar; __inbytesleft:psize_t; __outbuf:ppchar; __outbytesleft:psize_t):size_t;cdecl;external libiconvname name 'iconv';
  176. function iconv_close(__cd:iconv_t):cint;cdecl;external libiconvname name 'iconv_close';
  177. const
  178. iconvctlname='iconvctl';
  179. {$else}
  180. function iconv_open(__tocode:pchar; __fromcode:pchar):iconv_t;cdecl;external libiconvname name 'libiconv_open';
  181. function iconv(__cd:iconv_t; __inbuf:ppchar; __inbytesleft:psize_t; __outbuf:ppchar; __outbytesleft:psize_t):size_t;cdecl;external libiconvname name 'libiconv';
  182. function iconv_close(__cd:iconv_t):cint;cdecl;external libiconvname name 'libiconv_close';
  183. const
  184. iconvctlname='libiconvctl';
  185. {$endif}
  186. var
  187. iconvctl:function(__cd:iconv_t; __request:cint; __argument:pointer):cint;cdecl;
  188. procedure fpc_rangeerror; [external name 'FPC_RANGEERROR'];
  189. threadvar
  190. iconv_ansi2wide,
  191. iconv_wide2ansi : iconv_t;
  192. { since we cache the iconv_t converters, we have to do the same
  193. for the DefaultSystemCodePage variable since if it changes, we
  194. have to re-initialize the converters too. We can't do that via
  195. a callback in the widestring manager because DefaultSystemCodePage
  196. is not a threadvar and we can't automatically change this in all
  197. threads }
  198. current_DefaultSystemCodePage: TSystemCodePage;
  199. procedure InitThread;
  200. var
  201. transliterate: cint;
  202. iconvindex: longint;
  203. {$if not(defined(darwin) and (defined(cpuarm) or defined(cpuaarch64))) and not defined(iphonesim)}
  204. iconvname: rawbytestring;
  205. {$endif}
  206. begin
  207. current_DefaultSystemCodePage:=DefaultSystemCodePage;
  208. {$if not(defined(darwin) and (defined(cpuarm) or defined(cpuaarch64))) and not defined(iphonesim)}
  209. iconvindex:=GetCodepageData(DefaultSystemCodePage);
  210. if iconvindex<>-1 then
  211. iconvname:=UnixCpMap[iconvindex].name
  212. else
  213. { default to UTF-8 on Unix platforms }
  214. iconvname:='UTF-8';
  215. iconv_wide2ansi:=iconv_open(pchar(iconvname),unicode_encoding2);
  216. iconv_ansi2wide:=iconv_open(unicode_encoding2,pchar(iconvname));
  217. {$else}
  218. { Unix locale settings are ignored on iPhoneOS/iPhoneSimulator }
  219. iconv_wide2ansi:=iconv_open('UTF-8',unicode_encoding2);
  220. iconv_ansi2wide:=iconv_open(unicode_encoding2,'UTF-8');
  221. {$endif}
  222. if assigned(iconvctl) and
  223. (iconv_wide2ansi<>iconv_t(-1)) then
  224. begin
  225. transliterate:=1;
  226. iconvctl(iconv_wide2ansi,ICONV_SET_TRANSLITERATE,@transliterate);
  227. end;
  228. end;
  229. procedure FiniThread;
  230. begin
  231. if (iconv_wide2ansi <> iconv_t(-1)) then
  232. iconv_close(iconv_wide2ansi);
  233. if (iconv_ansi2wide <> iconv_t(-1)) then
  234. iconv_close(iconv_ansi2wide);
  235. end;
  236. {$if defined(beos) and not defined(haiku)}
  237. function nl_langinfo(__item:nl_item):pchar;
  238. begin
  239. {$warning TODO BeOS nl_langinfo or more uptodate port of iconv...}
  240. // Now implement the minimum required to correctly initialize WideString support
  241. case __item of
  242. CODESET : Result := 'UTF-8'; // BeOS use UTF-8
  243. else
  244. begin
  245. Assert(False, 'nl_langinfo was called with an unknown nl_item value');
  246. Result := '';
  247. end;
  248. end;
  249. end;
  250. {$endif}
  251. function open_iconv_for_cps(cp: TSystemCodePage; const otherencoding: pchar; cp_is_from: boolean): iconv_t;
  252. var
  253. iconvindex: longint;
  254. begin
  255. { TODO: add caching (then we also don't need separate code for
  256. the default system page and other ones)
  257. -- typecasting an ansistring function result to pchar is
  258. unsafe normally, but these are constant strings -> no
  259. problem }
  260. open_iconv_for_cps:=iconv_t(-1);
  261. iconvindex:=GetCodepageData(cp);
  262. if iconvindex=-1 then
  263. exit;
  264. repeat
  265. if cp_is_from then
  266. open_iconv_for_cps:=iconv_open(otherencoding,pchar(UnixCpMap[iconvindex].name))
  267. else
  268. open_iconv_for_cps:=iconv_open(pchar(UnixCpMap[iconvindex].name),otherencoding);
  269. inc(iconvindex);
  270. until (open_iconv_for_cps<>iconv_t(-1)) or
  271. (iconvindex>high(UnixCpMap)) or
  272. (UnixCpMap[iconvindex].cp<>cp);
  273. end;
  274. {$ifdef aix}
  275. {$i cwstraix.inc}
  276. {$endif aix}
  277. procedure Wide2AnsiMove(source:pwidechar; var dest:RawByteString; cp:TSystemCodePage; len:SizeInt);
  278. var
  279. outlength,
  280. outoffset,
  281. srclen,
  282. outleft : size_t;
  283. use_iconv: iconv_t;
  284. srcpos : pwidechar;
  285. destpos: pchar;
  286. mynil : pchar;
  287. my0 : size_t;
  288. err : longint;
  289. transliterate: cint;
  290. free_iconv: boolean;
  291. {$ifdef aix}
  292. intermediate: rawbytestring;
  293. {$endif aix}
  294. begin
  295. {$ifdef aix}
  296. { AIX libiconv does not support converting cp866 to anything else except
  297. for iso-8859-5 -> always first convert to iso-8859-5, then to UTF-16 }
  298. if cp=866 then
  299. begin
  300. Wide2AnsiMove(source,intermediate,28595,len);
  301. if handle_aix_intermediate(pchar(intermediate),28595,cp,dest,len) then
  302. exit;
  303. end;
  304. {$endif aix}
  305. if (cp=DefaultSystemCodePage) then
  306. begin
  307. { update iconv converter in case the DefaultSystemCodePage has been
  308. changed }
  309. if current_DefaultSystemCodePage<>DefaultSystemCodePage then
  310. begin
  311. FiniThread;
  312. InitThread;
  313. end;
  314. use_iconv:=iconv_wide2ansi;
  315. free_iconv:=false;
  316. end
  317. else
  318. begin
  319. use_iconv:=open_iconv_for_cps(cp,unicode_encoding2,false);
  320. if (use_iconv<>iconv_t(-1)) and
  321. assigned(iconvctl) then
  322. begin
  323. transliterate:=1;
  324. iconvctl(use_iconv,ICONV_SET_TRANSLITERATE,@transliterate);
  325. end;
  326. free_iconv:=true;
  327. end;
  328. { unsupported encoding -> default move }
  329. if use_iconv=iconv_t(-1) then
  330. begin
  331. DefaultUnicode2AnsiMove(source,dest,DefaultSystemCodePage,len);
  332. exit;
  333. end;
  334. mynil:=nil;
  335. my0:=0;
  336. { rought estimation }
  337. setlength(dest,len*3);
  338. outlength:=len*3;
  339. srclen:=len*2;
  340. srcpos:=source;
  341. destpos:=pchar(dest);
  342. outleft:=outlength;
  343. while iconv(use_iconv,ppchar(@srcpos),@srclen,@destpos,@outleft)=size_t(-1) do
  344. begin
  345. err:=fpgetCerrno;
  346. case err of
  347. { last character is incomplete sequence }
  348. ESysEINVAL,
  349. { incomplete sequence in the middle }
  350. ESysEILSEQ:
  351. begin
  352. { skip and set to '?' }
  353. inc(srcpos);
  354. dec(srclen,2);
  355. destpos^:='?';
  356. inc(destpos);
  357. dec(outleft);
  358. { reset }
  359. iconv(use_iconv,@mynil,@my0,@mynil,@my0);
  360. if err=ESysEINVAL then
  361. break;
  362. end;
  363. ESysE2BIG:
  364. begin
  365. outoffset:=destpos-pchar(dest);
  366. { extend }
  367. setlength(dest,outlength+len*3);
  368. inc(outleft,len*3);
  369. inc(outlength,len*3);
  370. { string could have been moved }
  371. destpos:=pchar(dest)+outoffset;
  372. end;
  373. else
  374. runerror(231);
  375. end;
  376. end;
  377. // truncate string
  378. setlength(dest,length(dest)-outleft);
  379. SetCodePage(dest,cp,false);
  380. if free_iconv then
  381. iconv_close(use_iconv);
  382. end;
  383. procedure Ansi2WideMove(source:pchar; cp:TSystemCodePage; var dest:widestring; len:SizeInt);
  384. var
  385. outlength,
  386. outoffset,
  387. outleft : size_t;
  388. use_iconv: iconv_t;
  389. srcpos,
  390. destpos: pchar;
  391. mynil : pchar;
  392. my0 : size_t;
  393. err: cint;
  394. iconvindex: longint;
  395. free_iconv: boolean;
  396. {$ifdef aix}
  397. intermediate: rawbytestring;
  398. {$endif aix}
  399. begin
  400. {$ifdef aix}
  401. { AIX libiconv does not support converting cp866 to anything else except
  402. for iso-8859-5 -> always first convert to iso-8859-5, then to UTF-16 }
  403. if cp=866 then
  404. begin
  405. if handle_aix_intermediate(source,cp,cp,intermediate,len) then
  406. source:=pchar(intermediate);
  407. end;
  408. {$endif aix}
  409. if (cp=DefaultSystemCodePage) then
  410. begin
  411. { update iconv converter in case the DefaultSystemCodePage has been
  412. changed }
  413. if current_DefaultSystemCodePage<>DefaultSystemCodePage then
  414. begin
  415. FiniThread;
  416. InitThread;
  417. end;
  418. use_iconv:=iconv_ansi2wide;
  419. free_iconv:=false;
  420. end
  421. else
  422. begin
  423. { TODO: add caching (then we also don't need separate code for
  424. the default system page and other ones)
  425. -- typecasting an ansistring function result to pchar is
  426. unsafe normally, but these are constant strings -> no
  427. problem }
  428. use_iconv:=open_iconv_for_cps(cp,unicode_encoding2,true);
  429. free_iconv:=true;
  430. end;
  431. { unsupported encoding -> default move }
  432. if use_iconv=iconv_t(-1) then
  433. begin
  434. DefaultAnsi2UnicodeMove(source,DefaultSystemCodePage,dest,len);
  435. exit;
  436. end;
  437. mynil:=nil;
  438. my0:=0;
  439. // extra space
  440. outlength:=len+1;
  441. setlength(dest,outlength);
  442. srcpos:=source;
  443. destpos:=pchar(dest);
  444. outleft:=outlength*2;
  445. while iconv(use_iconv,@srcpos,psize(@len),@destpos,@outleft)=size_t(-1) do
  446. begin
  447. err:=fpgetCerrno;
  448. case err of
  449. ESysEINVAL,
  450. ESysEILSEQ:
  451. begin
  452. { skip and set to '?' }
  453. inc(srcpos);
  454. dec(len);
  455. pwidechar(destpos)^:='?';
  456. inc(destpos,2);
  457. dec(outleft,2);
  458. { reset }
  459. iconv(use_iconv,@mynil,@my0,@mynil,@my0);
  460. if err=ESysEINVAL then
  461. break;
  462. end;
  463. ESysE2BIG:
  464. begin
  465. outoffset:=destpos-pchar(dest);
  466. { extend }
  467. setlength(dest,outlength+len);
  468. inc(outleft,len*2);
  469. inc(outlength,len);
  470. { string could have been moved }
  471. destpos:=pchar(dest)+outoffset;
  472. end;
  473. else
  474. runerror(231);
  475. end;
  476. end;
  477. // truncate string
  478. setlength(dest,length(dest)-outleft div 2);
  479. if free_iconv then
  480. iconv_close(use_iconv);
  481. end;
  482. function LowerWideString(const s : WideString) : WideString;
  483. var
  484. i : SizeInt;
  485. begin
  486. SetLength(result,length(s));
  487. for i:=0 to length(s)-1 do
  488. pwidechar(result)[i]:=WideChar(towlower(wint_t(s[i+1])));
  489. end;
  490. function UpperWideString(const s : WideString) : WideString;
  491. var
  492. i : SizeInt;
  493. begin
  494. SetLength(result,length(s));
  495. for i:=0 to length(s)-1 do
  496. pwidechar(result)[i]:=WideChar(towupper(wint_t(s[i+1])));
  497. end;
  498. procedure EnsureAnsiLen(var S: AnsiString; const len: SizeInt); inline;
  499. begin
  500. if (len>length(s)) then
  501. if (length(s) < 10*256) then
  502. setlength(s,length(s)+10)
  503. else
  504. setlength(s,length(s)+length(s) shr 8);
  505. end;
  506. procedure ConcatCharToAnsiStr(const c: char; var S: AnsiString; var index: SizeInt);
  507. begin
  508. EnsureAnsiLen(s,index);
  509. pchar(@s[index])^:=c;
  510. inc(index);
  511. end;
  512. { concatenates an utf-32 char to a widestring. S *must* be unique when entering. }
  513. {$if not(defined(beos) and not defined(haiku))}
  514. procedure ConcatUTF32ToAnsiStr(const nc: wint_t; var S: AnsiString; var index: SizeInt; var mbstate: mbstate_t);
  515. {$else not beos}
  516. procedure ConcatUTF32ToAnsiStr(const nc: wint_t; var S: AnsiString; var index: SizeInt);
  517. {$endif beos}
  518. var
  519. p : pchar;
  520. mblen : size_t;
  521. begin
  522. { we know that s is unique -> avoid uniquestring calls}
  523. p:=@s[index];
  524. if (nc<=127) then
  525. ConcatCharToAnsiStr(char(nc),s,index)
  526. else
  527. begin
  528. EnsureAnsiLen(s,index+MB_CUR_MAX);
  529. {$if not(defined(beos) and not defined(haiku))}
  530. mblen:=wcrtomb(p,wchar_t(nc),@mbstate);
  531. {$else not beos}
  532. mblen:=wctomb(p,wchar_t(nc));
  533. {$endif not beos}
  534. if (mblen<>size_t(-1)) then
  535. inc(index,mblen)
  536. else
  537. begin
  538. { invalid wide char }
  539. p^:='?';
  540. inc(index);
  541. end;
  542. end;
  543. end;
  544. function LowerAnsiString(const s : AnsiString) : AnsiString;
  545. var
  546. i, slen,
  547. resindex : SizeInt;
  548. mblen : size_t;
  549. {$if not(defined(beos) and not defined(haiku))}
  550. ombstate,
  551. nmbstate : mbstate_t;
  552. {$endif beos}
  553. wc : wchar_t;
  554. begin
  555. {$if not(defined(beos) and not defined(haiku))}
  556. fillchar(ombstate,sizeof(ombstate),0);
  557. fillchar(nmbstate,sizeof(nmbstate),0);
  558. {$endif beos}
  559. slen:=length(s);
  560. SetLength(result,slen+10);
  561. i:=1;
  562. resindex:=1;
  563. while (i<=slen) do
  564. begin
  565. if (s[i]<=#127) then
  566. begin
  567. wc:=wchar_t(s[i]);
  568. mblen:= 1;
  569. end
  570. else
  571. {$if not(defined(beos) and not defined(haiku))}
  572. mblen:=mbrtowc(@wc, pchar(@s[i]), slen-i+1, @ombstate);
  573. {$else not beos}
  574. mblen:=mbtowc(@wc, pchar(@s[i]), slen-i+1);
  575. {$endif not beos}
  576. case mblen of
  577. size_t(-2):
  578. begin
  579. { partial invalid character, copy literally }
  580. while (i<=slen) do
  581. begin
  582. ConcatCharToAnsiStr(s[i],result,resindex);
  583. inc(i);
  584. end;
  585. end;
  586. size_t(-1), 0:
  587. begin
  588. { invalid or null character }
  589. ConcatCharToAnsiStr(s[i],result,resindex);
  590. inc(i);
  591. end;
  592. else
  593. begin
  594. { a valid sequence }
  595. { even if mblen = 1, the lowercase version may have a }
  596. { different length }
  597. { We can't do anything special if wchar_t is 16 bit... }
  598. {$if not(defined(beos) and not defined(haiku))}
  599. ConcatUTF32ToAnsiStr(towlower(wint_t(wc)),result,resindex,nmbstate);
  600. {$else not beos}
  601. ConcatUTF32ToAnsiStr(towlower(wint_t(wc)),result,resindex);
  602. {$endif not beos}
  603. inc(i,mblen);
  604. end;
  605. end;
  606. end;
  607. SetLength(result,resindex-1);
  608. end;
  609. function UpperAnsiString(const s : AnsiString) : AnsiString;
  610. var
  611. i, slen,
  612. resindex : SizeInt;
  613. mblen : size_t;
  614. {$if not(defined(beos) and not defined(haiku))}
  615. ombstate,
  616. nmbstate : mbstate_t;
  617. {$endif beos}
  618. wc : wchar_t;
  619. begin
  620. {$if not(defined(beos) and not defined(haiku))}
  621. fillchar(ombstate,sizeof(ombstate),0);
  622. fillchar(nmbstate,sizeof(nmbstate),0);
  623. {$endif beos}
  624. slen:=length(s);
  625. SetLength(result,slen+10);
  626. i:=1;
  627. resindex:=1;
  628. while (i<=slen) do
  629. begin
  630. if (s[i]<=#127) then
  631. begin
  632. wc:=wchar_t(s[i]);
  633. mblen:= 1;
  634. end
  635. else
  636. {$if not(defined(beos) and not defined(haiku))}
  637. mblen:=mbrtowc(@wc, pchar(@s[i]), slen-i+1, @ombstate);
  638. {$else not beos}
  639. mblen:=mbtowc(@wc, pchar(@s[i]), slen-i+1);
  640. {$endif beos}
  641. case mblen of
  642. size_t(-2):
  643. begin
  644. { partial invalid character, copy literally }
  645. while (i<=slen) do
  646. begin
  647. ConcatCharToAnsiStr(s[i],result,resindex);
  648. inc(i);
  649. end;
  650. end;
  651. size_t(-1), 0:
  652. begin
  653. { invalid or null character }
  654. ConcatCharToAnsiStr(s[i],result,resindex);
  655. inc(i);
  656. end;
  657. else
  658. begin
  659. { a valid sequence }
  660. { even if mblen = 1, the uppercase version may have a }
  661. { different length }
  662. { We can't do anything special if wchar_t is 16 bit... }
  663. {$if not(defined(beos) and not defined(haiku))}
  664. ConcatUTF32ToAnsiStr(towupper(wint_t(wc)),result,resindex,nmbstate);
  665. {$else not beos}
  666. ConcatUTF32ToAnsiStr(towupper(wint_t(wc)),result,resindex);
  667. {$endif not beos}
  668. inc(i,mblen);
  669. end;
  670. end;
  671. end;
  672. SetLength(result,resindex-1);
  673. end;
  674. function WideStringToUCS4StringNoNulls(const s : WideString) : UCS4String;
  675. var
  676. i, slen,
  677. destindex : SizeInt;
  678. uch : UCS4Char;
  679. begin
  680. slen:=length(s);
  681. setlength(result,slen+1);
  682. i:=1;
  683. destindex:=0;
  684. while (i<=slen) do
  685. begin
  686. uch:=UCS4Char(s[i]);
  687. if (uch=0) then
  688. result[destindex]:=32
  689. else if (uch<=$d7ff) or (uch>=$e000) then
  690. result[destindex]:=uch
  691. else if (uch<=$dbff) and
  692. (i<slen) and
  693. (s[i+1]>=#$dc00) and
  694. (s[i+1]<=#$dfff) then
  695. begin
  696. result[destindex]:=(UCS4Char(uch-$d7c0) shl 10)+(UCS4Char(s[i+1]) xor $dc00);
  697. inc(i);
  698. end
  699. else { invalid surrogate pair }
  700. result[destindex]:=uch;
  701. inc(i);
  702. inc(destindex);
  703. end;
  704. result[destindex]:=UCS4Char(0);
  705. { Trimming length in this particular case is just a waste of time,
  706. because result will be interpreted as null-terminated and discarded
  707. almost immediately }
  708. end;
  709. function CompareWideString(const s1, s2 : WideString) : PtrInt;
  710. {$if not(defined (aix) and defined(cpupowerpc32))}
  711. var
  712. hs1,hs2 : UCS4String;
  713. begin
  714. { wcscoll interprets null chars as end-of-string -> filter out }
  715. hs1:=WideStringToUCS4StringNoNulls(s1);
  716. hs2:=WideStringToUCS4StringNoNulls(s2);
  717. result:=wcscoll(pwchar_t(hs1),pwchar_t(hs2));
  718. end;
  719. {$else}
  720. { AIX/PPC32 has a 16 bit wchar_t }
  721. var
  722. i, len: longint;
  723. hs1, hs2: array of widechar;
  724. begin
  725. len:=length(s1);
  726. setlength(hs1,len+1);
  727. for i:=1 to len do
  728. if s1[i]<>#0 then
  729. hs1[i-1]:=s1[i]
  730. else
  731. hs1[i-1]:=#32;
  732. hs1[len]:=#0;
  733. len:=length(s2);
  734. setlength(hs2,len+1);
  735. for i:=1 to len do
  736. if s2[i]<>#0 then
  737. hs2[i-1]:=s2[i]
  738. else
  739. hs2[i-1]:=#32;
  740. hs2[len]:=#0;
  741. result:=wcscoll(pwchar_t(hs1),pwchar_t(hs2));
  742. end;
  743. {$endif}
  744. function CompareTextWideString(const s1, s2 : WideString): PtrInt;
  745. begin
  746. result:=CompareWideString(UpperWideString(s1),UpperWideString(s2));
  747. end;
  748. { return value: number of code points in the string. Whenever an invalid
  749. code point is encountered, all characters part of this invalid code point
  750. are considered to form one "character" and the next character is
  751. considered to be the start of a new (possibly also invalid) code point }
  752. function CharLengthPChar(const Str: PChar): PtrInt;
  753. var
  754. nextlen: ptrint;
  755. s: pchar;
  756. {$if not(defined(beos) and not defined(haiku))}
  757. mbstate: mbstate_t;
  758. {$endif not beos}
  759. begin
  760. result:=0;
  761. s:=str;
  762. {$if not(defined(beos) and not defined(haiku))}
  763. fillchar(mbstate,sizeof(mbstate),0);
  764. {$endif not beos}
  765. repeat
  766. {$if defined(beos) and not defined(haiku)}
  767. nextlen:=ptrint(mblen(s,MB_CUR_MAX));
  768. {$else beos}
  769. nextlen:=ptrint(mbrlen(s,MB_CUR_MAX,@mbstate));
  770. {$endif beos}
  771. { skip invalid/incomplete sequences }
  772. if (nextlen<0) then
  773. nextlen:=1;
  774. inc(result,1);
  775. inc(s,nextlen);
  776. until (nextlen=0);
  777. end;
  778. function CodePointLength(const Str: PChar; maxlookahead: ptrint): PtrInt;
  779. {$if not(defined(beos) and not defined(haiku))}
  780. var
  781. mbstate: mbstate_t;
  782. {$endif not beos}
  783. begin
  784. {$if defined(beos) and not defined(haiku)}
  785. result:=ptrint(mblen(str,maxlookahead));
  786. {$else beos}
  787. fillchar(mbstate,sizeof(mbstate),0);
  788. result:=ptrint(mbrlen(str,maxlookahead,@mbstate));
  789. { mbrlen can also return -2 for "incomplete but potially valid character
  790. and data has been processed" }
  791. if result<0 then
  792. result:=-1;
  793. {$endif beos}
  794. end;
  795. function StrCompAnsiIntern(s1,s2 : PChar; len1, len2: PtrInt; canmodifys1, canmodifys2: boolean): PtrInt;
  796. var
  797. a,b: pchar;
  798. i: PtrInt;
  799. begin
  800. if not(canmodifys1) then
  801. getmem(a,len1+1)
  802. else
  803. a:=s1;
  804. for i:=0 to len1-1 do
  805. if s1[i]<>#0 then
  806. a[i]:=s1[i]
  807. else
  808. a[i]:=#32;
  809. a[len1]:=#0;
  810. if not(canmodifys2) then
  811. getmem(b,len2+1)
  812. else
  813. b:=s2;
  814. for i:=0 to len2-1 do
  815. if s2[i]<>#0 then
  816. b[i]:=s2[i]
  817. else
  818. b[i]:=#32;
  819. b[len2]:=#0;
  820. result:=strcoll(a,b);
  821. if not(canmodifys1) then
  822. freemem(a);
  823. if not(canmodifys2) then
  824. freemem(b);
  825. end;
  826. function CompareStrAnsiString(const s1, s2: ansistring): PtrInt;
  827. begin
  828. result:=StrCompAnsiIntern(pchar(s1),pchar(s2),length(s1),length(s2),false,false);
  829. end;
  830. function StrCompAnsi(s1,s2 : PChar): PtrInt;
  831. begin
  832. result:=strcoll(s1,s2);
  833. end;
  834. function AnsiCompareText(const S1, S2: ansistring): PtrInt;
  835. var
  836. a, b: AnsiString;
  837. begin
  838. a:=UpperAnsistring(s1);
  839. b:=UpperAnsistring(s2);
  840. result:=StrCompAnsiIntern(pchar(a),pchar(b),length(a),length(b),true,true);
  841. end;
  842. function AnsiStrIComp(S1, S2: PChar): PtrInt;
  843. begin
  844. result:=AnsiCompareText(ansistring(s1),ansistring(s2));
  845. end;
  846. function AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  847. var
  848. a, b: pchar;
  849. begin
  850. if (maxlen=0) then
  851. exit(0);
  852. if (s1[maxlen]<>#0) then
  853. begin
  854. getmem(a,maxlen+1);
  855. move(s1^,a^,maxlen);
  856. a[maxlen]:=#0;
  857. end
  858. else
  859. a:=s1;
  860. if (s2[maxlen]<>#0) then
  861. begin
  862. getmem(b,maxlen+1);
  863. move(s2^,b^,maxlen);
  864. b[maxlen]:=#0;
  865. end
  866. else
  867. b:=s2;
  868. result:=StrCompAnsiIntern(a,b,maxlen,maxlen,a<>s1,b<>s2);
  869. if (a<>s1) then
  870. freemem(a);
  871. if (b<>s2) then
  872. freemem(b);
  873. end;
  874. function AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  875. var
  876. a, b: ansistring;
  877. begin
  878. if (maxlen=0) then
  879. exit(0);
  880. setlength(a,maxlen);
  881. move(s1^,a[1],maxlen);
  882. setlength(b,maxlen);
  883. move(s2^,b[1],maxlen);
  884. result:=AnsiCompareText(a,b);
  885. end;
  886. procedure ansi2pchar(const s: ansistring; const orgp: pchar; out p: pchar);
  887. var
  888. newlen: sizeint;
  889. begin
  890. newlen:=length(s);
  891. if newlen>strlen(orgp) then
  892. fpc_rangeerror;
  893. p:=orgp;
  894. if (newlen>0) then
  895. move(s[1],p[0],newlen);
  896. p[newlen]:=#0;
  897. end;
  898. function AnsiStrLower(Str: PChar): PChar;
  899. var
  900. temp: ansistring;
  901. begin
  902. temp:=loweransistring(str);
  903. ansi2pchar(temp,str,result);
  904. end;
  905. function AnsiStrUpper(Str: PChar): PChar;
  906. var
  907. temp: ansistring;
  908. begin
  909. temp:=upperansistring(str);
  910. ansi2pchar(temp,str,result);
  911. end;
  912. function envvarset(const varname: pchar): boolean;
  913. var
  914. varval: pchar;
  915. begin
  916. varval:=fpgetenv(varname);
  917. result:=
  918. assigned(varval) and
  919. (varval[0]<>#0);
  920. end;
  921. function GetStandardCodePage(const stdcp: TStandardCodePageEnum): TSystemCodePage;
  922. var
  923. langinfo: pchar;
  924. begin
  925. {$ifdef FPCRTL_FILESYSTEM_UTF8}
  926. if stdcp=scpFileSystemSingleByte then
  927. begin
  928. result:=CP_UTF8;
  929. exit;
  930. end;
  931. {$endif}
  932. { if none of the relevant LC_* environment variables are set, fall back to
  933. UTF-8 (this happens under some versions of OS X for GUI applications, which
  934. otherwise get CP_ASCII) }
  935. if envvarset('LC_ALL') or
  936. envvarset('LC_CTYPE') or
  937. envvarset('LANG') then
  938. begin
  939. langinfo:=nl_langinfo(CODESET);
  940. { there's a bug in the Mac OS X 10.5 libc (based on FreeBSD's)
  941. that causes it to return an empty string of UTF-8 locales
  942. -> patch up (and in general, UTF-8 is a good default on
  943. Unix platforms) }
  944. if not assigned(langinfo) or
  945. (langinfo^=#0) then
  946. langinfo:='UTF-8';
  947. Result:=GetCodepageByName(ansistring(langinfo));
  948. end
  949. else
  950. Result:=unixcp.GetSystemCodepage;
  951. end;
  952. {$ifdef FPC_HAS_CPSTRING}
  953. procedure SetStdIOCodePage(var T: Text); inline;
  954. begin
  955. case TextRec(T).Mode of
  956. fmInput:TextRec(T).CodePage:=GetStandardCodePage(scpConsoleInput);
  957. fmOutput:TextRec(T).CodePage:=GetStandardCodePage(scpConsoleOutput);
  958. end;
  959. end;
  960. procedure SetStdIOCodePages; inline;
  961. begin
  962. SetStdIOCodePage(Input);
  963. SetStdIOCodePage(Output);
  964. SetStdIOCodePage(ErrOutput);
  965. SetStdIOCodePage(StdOut);
  966. SetStdIOCodePage(StdErr);
  967. end;
  968. {$endif FPC_HAS_CPSTRING}
  969. var
  970. OrgWideStringManager: TUnicodeStringManager;
  971. Procedure SetCWideStringManager;
  972. Var
  973. CWideStringManager : TUnicodeStringManager;
  974. begin
  975. GetUnicodeStringManager(OrgWideStringManager);
  976. CWideStringManager:=OrgWideStringManager;
  977. With CWideStringManager do
  978. begin
  979. Wide2AnsiMoveProc:=@Wide2AnsiMove;
  980. Ansi2WideMoveProc:=@Ansi2WideMove;
  981. UpperWideStringProc:=@UpperWideString;
  982. LowerWideStringProc:=@LowerWideString;
  983. CompareWideStringProc:=@CompareWideString;
  984. CompareTextWideStringProc:=@CompareTextWideString;
  985. CharLengthPCharProc:=@CharLengthPChar;
  986. CodePointLengthProc:=@CodePointLength;
  987. UpperAnsiStringProc:=@UpperAnsiString;
  988. LowerAnsiStringProc:=@LowerAnsiString;
  989. CompareStrAnsiStringProc:=@CompareStrAnsiString;
  990. CompareTextAnsiStringProc:=@AnsiCompareText;
  991. StrCompAnsiStringProc:=@StrCompAnsi;
  992. StrICompAnsiStringProc:=@AnsiStrIComp;
  993. StrLCompAnsiStringProc:=@AnsiStrLComp;
  994. StrLICompAnsiStringProc:=@AnsiStrLIComp;
  995. StrLowerAnsiStringProc:=@AnsiStrLower;
  996. StrUpperAnsiStringProc:=@AnsiStrUpper;
  997. ThreadInitProc:=@InitThread;
  998. ThreadFiniProc:=@FiniThread;
  999. { Unicode }
  1000. Unicode2AnsiMoveProc:=@Wide2AnsiMove;
  1001. Ansi2UnicodeMoveProc:=@Ansi2WideMove;
  1002. UpperUnicodeStringProc:=@UpperWideString;
  1003. LowerUnicodeStringProc:=@LowerWideString;
  1004. CompareUnicodeStringProc:=@CompareWideString;
  1005. CompareTextUnicodeStringProc:=@CompareTextWideString;
  1006. { CodePage }
  1007. GetStandardCodePageProc:=@GetStandardCodePage;
  1008. end;
  1009. SetUnicodeStringManager(CWideStringManager);
  1010. end;
  1011. var
  1012. iconvlib:TLibHandle;
  1013. initialization
  1014. SetCWideStringManager;
  1015. { you have to call setlocale(LC_ALL,'') to initialise the langinfo stuff }
  1016. { with the information from the environment variables according to POSIX }
  1017. { (some OSes do this automatically, but e.g. Darwin and Solaris don't) }
  1018. setlocale(LC_ALL,'');
  1019. { load iconvctl function }
  1020. iconvlib:=LoadLibrary(libprefix+libiconvname+'.'+SharedSuffix);
  1021. if iconvlib<>0 then
  1022. pointer(iconvctl):=GetProcAddress(iconvlib,iconvctlname);
  1023. { set the DefaultSystemCodePage }
  1024. DefaultSystemCodePage:=GetStandardCodePage(scpAnsi);
  1025. DefaultFileSystemCodePage:=GetStandardCodePage(scpFileSystemSingleByte);
  1026. DefaultRTLFileSystemCodePage:=DefaultFileSystemCodePage;
  1027. {$ifdef FPC_HAS_CPSTRING}
  1028. SetStdIOCodePages;
  1029. {$endif FPC_HAS_CPSTRING}
  1030. { init conversion tables for main program }
  1031. InitThread;
  1032. finalization
  1033. { fini conversion tables for main program }
  1034. FiniThread;
  1035. { unload iconv library }
  1036. if iconvlib<>0 then
  1037. FreeLibrary(iconvlib);
  1038. { restore previous (probably default) widestring manager so that subsequent calls
  1039. into the widestring manager won't trigger the finalized functionality }
  1040. SetWideStringManager(OrgWideStringManager);
  1041. end.