cwstring.pp 26 KB

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