cwstring.pp 30 KB

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