DEADSOFTWARE

f5f762c6e983c96a5dd7c54ad3fb68c82110d058
[d2df-sdl.git] / src / shared / utils.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE a_modes.inc}
16 unit utils;
18 interface
20 uses
21 SysUtils, Classes, md5;
24 // ////////////////////////////////////////////////////////////////////////// //
25 type
26 SSArray = array of ShortString;
29 const wadExtensions: array [0..6] of AnsiString = (
30 '.dfz',
31 '.wad',
32 '.dfwad',
33 '.pk3',
34 '.pak',
35 '.zip',
36 '.dfzip'
37 );
40 // ////////////////////////////////////////////////////////////////////////// //
41 type
42 TUtf8DecoderFast = packed record
43 public
44 const Replacement = $FFFD; // replacement char for invalid unicode
45 const Accept = 0;
46 const Reject = 12;
48 private
49 state: LongWord;
51 public
52 codepoint: LongWord; // decoded codepoint (valid only when decoder is in "complete" state)
54 public
55 constructor Create (v: Boolean{fuck you, fpc});
57 procedure reset (); inline;
59 function complete (): Boolean; inline; // is current character complete? take `codepoint` then
60 function invalid (): Boolean; inline;
61 function completeOrInvalid (): Boolean; inline;
63 // process one byte, return `true` if codepoint is ready
64 function decode (b: Byte): Boolean; inline; overload;
65 function decode (c: AnsiChar): Boolean; inline; overload;
66 end;
69 // ////////////////////////////////////////////////////////////////////////// //
70 function getFilenameExt (const fn: AnsiString): AnsiString;
71 function setFilenameExt (const fn, ext: AnsiString): AnsiString;
72 function forceFilenameExt (const fn, ext: AnsiString): AnsiString;
74 // rewrites slashes to '/'
75 function fixSlashes (s: AnsiString): AnsiString;
77 // replaces all the shitty characters with '_'
78 // (everything except alphanumerics, '_', '.')
79 function sanitizeFilename (s: AnsiString): AnsiString;
81 function isAbsolutePath (const s: AnsiString): Boolean;
82 function isRootPath (const s: AnsiString): Boolean;
84 // strips out name from `fn`, leaving trailing slash
85 function getFilenamePath (const fn: AnsiString): AnsiString;
87 // ends with '/' or '\'?
88 function isFilenamePath (const fn: AnsiString): Boolean;
90 // strips extra trailing slashes in `path, and extra leading slashes in `fn`
91 // will add slash to `path`, even if `fn` is empty!
92 function filenameConcat (const path, fn: AnsiString): AnsiString;
94 // does filename have one of ".wad", ".pk3", ".zip" extensions?
95 function hasWadExtension (const fn: AnsiString): Boolean;
97 // does filepath have ".XXX:\" in it?
98 function isWadPath (const fn: AnsiString): Boolean;
100 // adds ".wad" extension if filename doesn't have one of ".wad", ".pk3", ".zip"
101 function addWadExtension (const fn: AnsiString): AnsiString;
103 // check wad signature
104 function isWadData (data: Pointer; len: LongWord): Boolean;
106 // convert number to strig with nice commas
107 function int64ToStrComma (i: Int64): AnsiString;
109 function upcase1251 (ch: AnsiChar): AnsiChar; inline;
110 function locase1251 (ch: AnsiChar): AnsiChar; inline;
111 function IsValid1251 (ch: Word): Boolean;
112 function IsPrintable1251 (ch: AnsiChar): Boolean;
114 function toLowerCase1251 (const s: AnsiString): AnsiString;
116 // `true` if strings are equal; ignoring case for cp1251
117 function strEquCI1251 (const s0, s1: AnsiString): Boolean;
119 function utf8Valid (const s: AnsiString): Boolean;
121 function utf8to1251 (s: AnsiString): AnsiString;
123 // findFileCI takes case-insensitive path, traverses it, and rewrites it to
124 // a case-sensetive one (using real on-disk names). return value means 'success'.
125 // if some dir or file wasn't found, pathname is undefined (destroyed, but not
126 // necessarily cleared).
127 // last name assumed to be a file, not directory (unless `lastIsDir` flag is set).
128 function findFileCI (var pathname: AnsiString; lastIsDir: Boolean=false): Boolean;
130 // findDiskWad tries to find the wad file using common wad extensions
131 // (see `wadExtensions` array).
132 // returns real on-disk filename, or empty string.
133 // original wad extension is used as a hint for the first try.
134 // also, this automatically performs `findFileCI()`.
135 function findDiskWad (fname: AnsiString): AnsiString;
136 // slashes must be normalized!
137 function isWadNamesEqu (wna, wnb: AnsiString): Boolean;
139 // they throws
140 function openDiskFileRO (pathname: AnsiString): TStream;
141 function createDiskFile (pathname: AnsiString): TStream;
142 // create file if necessary, but don't truncate the existing one
143 function openDiskFileRW (pathname: AnsiString): TStream;
145 // little endian
146 procedure writeSign (st: TStream; const sign: AnsiString);
147 function checkSign (st: TStream; const sign: AnsiString): Boolean;
149 procedure writeBool (st: TStream; b: Boolean);
150 function readBool (st: TStream): Boolean;
152 procedure writeStr (st: TStream; const str: AnsiString; maxlen: LongWord=65535);
153 function readStr (st: TStream; maxlen: LongWord=65535): AnsiString;
155 procedure writeInt (st: TStream; v: Byte); overload;
156 procedure writeInt (st: TStream; v: ShortInt); overload;
157 procedure writeInt (st: TStream; v: Word); overload;
158 procedure writeInt (st: TStream; v: SmallInt); overload;
159 procedure writeInt (st: TStream; v: LongWord); overload;
160 procedure writeInt (st: TStream; v: LongInt); overload;
161 procedure writeInt (st: TStream; v: Int64); overload;
162 procedure writeInt (st: TStream; v: UInt64); overload;
164 function readByte (st: TStream): Byte;
165 function readShortInt (st: TStream): ShortInt;
166 function readWord (st: TStream): Word;
167 function readSmallInt (st: TStream): SmallInt;
168 function readLongWord (st: TStream): LongWord;
169 function readLongInt (st: TStream): LongInt;
170 function readInt64 (st: TStream): Int64;
171 function readUInt64 (st: TStream): UInt64;
173 // big endian
174 procedure writeIntBE (st: TStream; v: Byte); overload;
175 procedure writeIntBE (st: TStream; v: ShortInt); overload;
176 procedure writeIntBE (st: TStream; v: Word); overload;
177 procedure writeIntBE (st: TStream; v: SmallInt); overload;
178 procedure writeIntBE (st: TStream; v: LongWord); overload;
179 procedure writeIntBE (st: TStream; v: LongInt); overload;
180 procedure writeIntBE (st: TStream; v: Int64); overload;
181 procedure writeIntBE (st: TStream; v: UInt64); overload;
183 function readByteBE (st: TStream): Byte;
184 function readShortIntBE (st: TStream): ShortInt;
185 function readWordBE (st: TStream): Word;
186 function readSmallIntBE (st: TStream): SmallInt;
187 function readLongWordBE (st: TStream): LongWord;
188 function readLongIntBE (st: TStream): LongInt;
189 function readInt64BE (st: TStream): Int64;
190 function readUInt64BE (st: TStream): UInt64;
193 function nmin (a, b: Byte): Byte; inline; overload;
194 function nmin (a, b: ShortInt): ShortInt; inline; overload;
195 function nmin (a, b: Word): Word; inline; overload;
196 function nmin (a, b: SmallInt): SmallInt; inline; overload;
197 function nmin (a, b: LongWord): LongWord; inline; overload;
198 function nmin (a, b: LongInt): LongInt; inline; overload;
199 function nmin (a, b: Int64): Int64; inline; overload;
200 function nmin (a, b: UInt64): UInt64; inline; overload;
201 function nmin (a, b: Single): Single; inline; overload;
202 function nmin (a, b: Double): Double; inline; overload;
203 {$IF DEFINED(CPU386) OR DEFINED(CPUAMD64)}
204 function nmin (a, b: Extended): Extended; inline; overload;
205 {$ENDIF}
207 function nmax (a, b: Byte): Byte; inline; overload;
208 function nmax (a, b: ShortInt): ShortInt; inline; overload;
209 function nmax (a, b: Word): Word; inline; overload;
210 function nmax (a, b: SmallInt): SmallInt; inline; overload;
211 function nmax (a, b: LongWord): LongWord; inline; overload;
212 function nmax (a, b: LongInt): LongInt; inline; overload;
213 function nmax (a, b: Int64): Int64; inline; overload;
214 function nmax (a, b: UInt64): UInt64; inline; overload;
215 function nmax (a, b: Single): Single; inline; overload;
216 function nmax (a, b: Double): Double; inline; overload;
217 {$IF DEFINED(CPU386) OR DEFINED(CPUAMD64)}
218 function nmax (a, b: Extended): Extended; inline; overload;
219 {$ENDIF}
220 function nclamp (v, a, b: Byte): Byte; inline; overload;
221 function nclamp (v, a, b: ShortInt): ShortInt; inline; overload;
222 function nclamp (v, a, b: Word): Word; inline; overload;
223 function nclamp (v, a, b: SmallInt): SmallInt; inline; overload;
224 function nclamp (v, a, b: LongWord): LongWord; inline; overload;
225 function nclamp (v, a, b: LongInt): LongInt; inline; overload;
226 function nclamp (v, a, b: Int64): Int64; inline; overload;
227 function nclamp (v, a, b: UInt64): UInt64; inline; overload;
228 function nclamp (v, a, b: Single): Single; inline; overload;
229 function nclamp (v, a, b: Double): Double; inline; overload;
230 {$IF DEFINED(CPU386) OR DEFINED(CPUAMD64)}
231 function nclamp (v, a, b: Extended): Extended; inline; overload;
232 {$ENDIF}
234 type
235 TFormatStrFCallback = procedure (constref buf; len: SizeUInt);
237 // returns formatted string if `writerCB` is `nil`, empty string otherwise
238 function formatstrf (const fmt: AnsiString; const args: array of const; writerCB: TFormatStrFCallback=nil): AnsiString;
240 function wchar2win (wc: WideChar): AnsiChar; inline;
241 function utf2win (const s: AnsiString): AnsiString;
242 function win2utf (const s: AnsiString): AnsiString;
243 function digitInBase (ch: AnsiChar; base: Integer): Integer;
245 // returns string in single or double quotes
246 // single quotes supports only pascal-style '' for single quote char
247 // double quotes supports c-style escapes
248 // function will select quote mode automatically
249 function quoteStr (const s: AnsiString): AnsiString;
252 type
253 generic TSimpleList<ItemT> = class
254 private
255 //type PItemT = ^ItemT;
256 type TItemArr = array of ItemT;
258 public
259 type
260 TEnumerator = record
261 private
262 mItems: TItemArr;
263 mCount: Integer;
264 mCurrent: Integer;
265 public
266 constructor Create (const aitems: TItemArr; acount: Integer);
267 function MoveNext: Boolean;
268 function getCurrent (): ItemT;
269 property Current: ItemT read getCurrent;
270 end;
272 private
273 mItems: TItemArr;
274 mCount: Integer; // can be less than `mItems` size
276 private
277 function getAt (idx: Integer): ItemT; inline;
278 procedure setAt (idx: Integer; const it: ItemT); inline;
280 function getCapacity (): Integer; inline;
281 procedure setCapacity (v: Integer); inline;
283 public
284 constructor Create (acapacity: Integer=-1);
285 destructor Destroy (); override;
287 //WARNING! don't change list contents in `for ... in`!
288 function GetEnumerator (): TEnumerator;
290 procedure reset (); inline; // won't resize `mItems`
291 procedure clear (); inline;
293 procedure append (constref it: ItemT); inline;
294 procedure delete (idx: Integer); inline;
295 function remove (idx: Integer): ItemT; inline;
297 public
298 property count: Integer read mCount;
299 property capacity: Integer read getCapacity write setCapacity;
300 property at[idx: Integer]: ItemT read getAt write setAt; default;
301 end;
304 procedure FillMemory (Dest: Pointer; Len: LongWord; Ch: Byte); inline;
305 procedure CopyMemory (Dest: Pointer; Src: Pointer; Len: LongWord); inline;
306 procedure ZeroMemory (Dest: Pointer; Len: LongWord); inline;
309 type
310 TDiskFileInfo = record
311 diskName: AnsiString;
312 size: LongInt;
313 age: LongInt;
314 // not changed by info getter; used in other parts of the code
315 userName: AnsiString;
316 tag: Integer;
317 hash: TMD5Digest;
318 udata: Pointer;
319 end;
321 function GetDiskFileInfo (fname: AnsiString; var info: TDiskFileInfo): Boolean;
324 implementation
326 uses
327 xstreams;
329 // ////////////////////////////////////////////////////////////////////////// //
330 procedure CopyMemory (Dest: Pointer; Src: Pointer; Len: LongWord); inline;
331 begin
332 Move(Src^, Dest^, Len);
333 end;
335 procedure FillMemory (Dest: Pointer; Len: LongWord; Ch: Byte); inline;
336 begin
337 FillChar(Dest^, Len, Ch);
338 end;
340 procedure ZeroMemory (Dest: Pointer; Len: LongWord); inline;
341 begin
342 FillChar(Dest^, Len, 0);
343 end;
346 // ////////////////////////////////////////////////////////////////////////// //
347 // rewrites slashes to '/'
348 function fixSlashes (s: AnsiString): AnsiString;
349 {$IFDEF WINDOWS}
350 var
351 f: Integer;
352 {$ENDIF}
353 begin
354 result := s;
355 {$IFDEF WINDOWS}
356 for f := 1 to length(result) do if (result[f] = '\') then result[f] := '/';
357 {$ENDIF}
358 end;
360 // replaces all the shitty characters with '_'
361 // (everything except alphanumerics, '_', '.')
362 function sanitizeFilename (s: AnsiString): AnsiString;
363 var
364 i: Integer;
365 const
366 leaveChars: set of Char = [ '0'..'9', 'A'..'Z', 'a'..'z', '_', '.', #192..#255 ];
367 replaceWith: Char = '_';
368 begin
369 result := s;
370 for i := 1 to length(result) do
371 if not (result[i] in leaveChars) then
372 result[i] := replaceWith;
373 end;
375 function isAbsolutePath (const s: AnsiString): Boolean;
376 begin
377 result := false;
378 if (length(s) = 0) then exit;
379 {$IFDEF WINDOWS}
380 if (s[1] = '/') or (s[1] = '\') then begin result := true; exit; end;
381 if (length(s) > 2) and (s[2] = ':') and ((s[3] = '/') or (s[3] = '\')) then begin result := true; exit; end;
382 {$ELSE}
383 result := (s[1] = '/');
384 {$ENDIF}
385 end;
388 function isRootPath (const s: AnsiString): Boolean;
389 begin
390 result := false;
391 if (length(s) = 0) then exit;
392 {$IFDEF WINDOWS}
393 if (s = '/') or (s = '\') then begin result := true; exit; end;
394 if (length(s) = 3) and (s[2] = ':') and ((s[3] = '/') or (s[3] = '\')) then begin result := true; exit; end;
395 {$ELSE}
396 result := (s = '/');
397 {$ENDIF}
398 end;
401 // ////////////////////////////////////////////////////////////////////////// //
402 constructor TSimpleList.TEnumerator.Create (const aitems: TItemArr; acount: Integer);
403 begin
404 mItems := aitems;
405 mCurrent := -1;
406 mCount := acount;
407 end;
409 function TSimpleList.TEnumerator.MoveNext: Boolean;
410 begin
411 Inc(mCurrent);
412 result := (mCurrent < mCount);
413 end;
415 function TSimpleList.TEnumerator.getCurrent (): ItemT;
416 begin
417 result := mItems[mCurrent];
418 end;
421 // ////////////////////////////////////////////////////////////////////////// //
422 constructor TSimpleList.Create (acapacity: Integer=-1);
423 begin
424 mItems := nil;
425 if (acapacity > 0) then SetLength(mItems, acapacity);
426 mCount := 0;
427 end;
430 destructor TSimpleList.Destroy ();
431 begin
432 mItems := nil;
433 inherited;
434 end;
437 function TSimpleList.getCapacity (): Integer; inline;
438 begin
439 result := Length(mItems);
440 end;
443 procedure TSimpleList.setCapacity (v: Integer); inline;
444 begin
445 if (v < mCount) then v := mCount;
446 if (v <> Length(mItems)) then SetLength(mItems, v);
447 end;
450 function TSimpleList.GetEnumerator (): TEnumerator;
451 begin
452 if (Length(mItems) > 0) then result := TEnumerator.Create(mItems, mCount)
453 else result := TEnumerator.Create(nil, -1);
454 end;
457 procedure TSimpleList.reset (); inline;
458 begin
459 mCount := 0;
460 end;
463 procedure TSimpleList.clear (); inline;
464 begin
465 mItems := nil;
466 mCount := 0;
467 end;
470 function TSimpleList.getAt (idx: Integer): ItemT; inline;
471 begin
472 if (idx >= 0) and (idx < mCount) then result := mItems[idx] else result := Default(ItemT);
473 end;
476 procedure TSimpleList.setAt (idx: Integer; const it: ItemT); inline;
477 begin
478 if (idx >= 0) and (idx < mCount) then mItems[idx] := it;
479 end;
482 procedure TSimpleList.append (constref it: ItemT); inline;
483 var
484 newsz: Integer;
485 begin
486 if (mCount >= Length(mItems)) then
487 begin
488 newsz := mCount+(mCount div 3)+128;
489 SetLength(mItems, newsz);
490 end;
491 mItems[mCount] := it;
492 Inc(mCount);
493 end;
496 procedure TSimpleList.delete (idx: Integer); inline;
497 var
498 f: Integer;
499 begin
500 if (idx >= 0) and (idx < mCount) then
501 begin
502 for f := idx+1 to mCount-1 do mItems[f-1] := mItems[f];
503 end;
504 end;
507 function TSimpleList.remove (idx: Integer): ItemT; inline;
508 var
509 f: Integer;
510 begin
511 if (idx >= 0) and (idx < mCount) then
512 begin
513 result := mItems[idx];
514 for f := idx+1 to mCount-1 do mItems[f-1] := mItems[f];
515 end
516 else
517 begin
518 result := Default(ItemT);
519 end;
520 end;
523 // ////////////////////////////////////////////////////////////////////////// //
524 var
525 wc2shitmap: array[0..65535] of AnsiChar;
526 wc2shitmapInited: Boolean = false;
529 // ////////////////////////////////////////////////////////////////////////// //
530 const
531 cp1251: array[0..127] of Word = (
532 $0402,$0403,$201A,$0453,$201E,$2026,$2020,$2021,$20AC,$2030,$0409,$2039,$040A,$040C,$040B,$040F,
533 $0452,$2018,$2019,$201C,$201D,$2022,$2013,$2014,$FFFD,$2122,$0459,$203A,$045A,$045C,$045B,$045F,
534 $00A0,$040E,$045E,$0408,$00A4,$0490,$00A6,$00A7,$0401,$00A9,$0404,$00AB,$00AC,$00AD,$00AE,$0407,
535 $00B0,$00B1,$0406,$0456,$0491,$00B5,$00B6,$00B7,$0451,$2116,$0454,$00BB,$0458,$0405,$0455,$0457,
536 $0410,$0411,$0412,$0413,$0414,$0415,$0416,$0417,$0418,$0419,$041A,$041B,$041C,$041D,$041E,$041F,
537 $0420,$0421,$0422,$0423,$0424,$0425,$0426,$0427,$0428,$0429,$042A,$042B,$042C,$042D,$042E,$042F,
538 $0430,$0431,$0432,$0433,$0434,$0435,$0436,$0437,$0438,$0439,$043A,$043B,$043C,$043D,$043E,$043F,
539 $0440,$0441,$0442,$0443,$0444,$0445,$0446,$0447,$0448,$0449,$044A,$044B,$044C,$044D,$044E,$044F
540 );
543 procedure initShitMap ();
544 var
545 f: Integer;
546 begin
547 for f := 0 to High(wc2shitmap) do wc2shitmap[f] := '?';
548 for f := 0 to 127 do wc2shitmap[f] := AnsiChar(f);
549 for f := 0 to 127 do wc2shitmap[cp1251[f]] := AnsiChar(f+128);
550 wc2shitmapInited := true;
551 end;
554 // ////////////////////////////////////////////////////////////////////////// //
555 // fast state-machine based UTF-8 decoder; using 8 bytes of memory
556 // code points from invalid range will never be valid, this is the property of the state machine
557 const
558 // see http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
559 utf8dfa: array[0..$16c-1] of Byte = (
560 // maps bytes to character classes
561 $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // 00-0f
562 $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // 10-1f
563 $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // 20-2f
564 $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // 30-3f
565 $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // 40-4f
566 $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // 50-5f
567 $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // 60-6f
568 $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // 70-7f
569 $01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01, // 80-8f
570 $09,$09,$09,$09,$09,$09,$09,$09,$09,$09,$09,$09,$09,$09,$09,$09, // 90-9f
571 $07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07, // a0-af
572 $07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07,$07, // b0-bf
573 $08,$08,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02, // c0-cf
574 $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02, // d0-df
575 $0a,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$03,$04,$03,$03, // e0-ef
576 $0b,$06,$06,$06,$05,$08,$08,$08,$08,$08,$08,$08,$08,$08,$08,$08, // f0-ff
577 // maps a combination of a state of the automaton and a character class to a state
578 $00,$0c,$18,$24,$3c,$60,$54,$0c,$0c,$0c,$30,$48,$0c,$0c,$0c,$0c, // 100-10f
579 $0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c,$00,$0c,$0c,$0c,$0c,$0c,$00, // 110-11f
580 $0c,$00,$0c,$0c,$0c,$18,$0c,$0c,$0c,$0c,$0c,$18,$0c,$18,$0c,$0c, // 120-12f
581 $0c,$0c,$0c,$0c,$0c,$0c,$0c,$18,$0c,$0c,$0c,$0c,$0c,$18,$0c,$0c, // 130-13f
582 $0c,$0c,$0c,$0c,$0c,$18,$0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c,$24, // 140-14f
583 $0c,$24,$0c,$0c,$0c,$24,$0c,$0c,$0c,$0c,$0c,$24,$0c,$24,$0c,$0c, // 150-15f
584 $0c,$24,$0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c);
587 // ////////////////////////////////////////////////////////////////////////// //
588 constructor TUtf8DecoderFast.Create (v: Boolean{fuck you, fpc}); begin state := Accept; codepoint := 0; end;
590 procedure TUtf8DecoderFast.reset (); inline; begin state := Accept; codepoint := 0; end;
592 function TUtf8DecoderFast.complete (): Boolean; inline; begin result := (state = Accept); end;
593 function TUtf8DecoderFast.invalid (): Boolean; inline; begin result := (state = Reject); end;
594 function TUtf8DecoderFast.completeOrInvalid (): Boolean; inline; begin result := (state = Accept) or (state = Reject); end;
596 function TUtf8DecoderFast.decode (c: AnsiChar): Boolean; inline; overload; begin result := decode(Byte(c)); end;
598 function TUtf8DecoderFast.decode (b: Byte): Boolean; inline; overload;
599 var
600 tp: LongWord;
601 begin
602 if (state = Reject) then begin state := Accept; codepoint := 0; end;
603 tp := utf8dfa[b];
604 if (state <> Accept) then codepoint := (b and $3f) or (codepoint shl 6) else codepoint := ($ff shr tp) and b;
605 state := utf8dfa[256+state+tp];
606 if (state = Reject) then begin codepoint := Replacement; state := Accept; end;
607 result := (state = Accept);
608 end;
611 // ////////////////////////////////////////////////////////////////////////// //
612 function wchar2win (wc: WideChar): AnsiChar; inline;
613 begin
614 if not wc2shitmapInited then initShitMap();
615 if (LongWord(wc) > 65535) then result := '?' else result := wc2shitmap[LongWord(wc)];
616 end;
619 // ////////////////////////////////////////////////////////////////////////// //
620 function utf2win (const s: AnsiString): AnsiString;
621 var
622 f, c: Integer;
623 ud: TUtf8DecoderFast;
624 begin
625 for f := 1 to Length(s) do
626 begin
627 if (Byte(s[f]) > 127) then
628 begin
629 ud := TUtf8DecoderFast.Create(true);
630 result := '';
631 for c := 1 to Length(s) do
632 begin
633 if ud.decode(s[c]) then result += wchar2win(WideChar(ud.codepoint));
634 end;
635 exit;
636 end;
637 end;
638 result := s;
639 end;
642 function win2utf (const s: AnsiString): AnsiString;
643 var
644 f, c: Integer;
646 function utf8Encode (code: Integer): AnsiString;
647 begin
648 if (code < 0) or (code > $10FFFF) then begin result := '?'; exit; end;
649 if (code <= $7f) then
650 begin
651 result := AnsiChar(code and $ff);
652 end
653 else if (code <= $7FF) then
654 begin
655 result := AnsiChar($C0 or (code shr 6));
656 result += AnsiChar($80 or (code and $3F));
657 end
658 else if (code <= $FFFF) then
659 begin
660 result := AnsiChar($E0 or (code shr 12));
661 result += AnsiChar($80 or ((code shr 6) and $3F));
662 result += AnsiChar($80 or (code and $3F));
663 end
664 else if (code <= $10FFFF) then
665 begin
666 result := AnsiChar($F0 or (code shr 18));
667 result += AnsiChar($80 or ((code shr 12) and $3F));
668 result += AnsiChar($80 or ((code shr 6) and $3F));
669 result += AnsiChar($80 or (code and $3F));
670 end
671 else
672 begin
673 result := '?';
674 end;
675 end;
677 begin
678 for f := 1 to Length(s) do
679 begin
680 if (Byte(s[f]) > 127) then
681 begin
682 result := '';
683 for c := 1 to Length(s) do
684 begin
685 if (Byte(s[c]) < 128) then
686 begin
687 result += s[c];
688 end
689 else
690 begin
691 result += utf8Encode(cp1251[Byte(s[c])-128])
692 end;
693 end;
694 exit;
695 end;
696 end;
697 result := s;
698 end;
701 // ////////////////////////////////////////////////////////////////////////// //
702 function digitInBase (ch: AnsiChar; base: Integer): Integer;
703 begin
704 result := -1;
705 if (base < 1) or (base > 36) then exit;
706 if (ch < '0') then exit;
707 if (base <= 10) then
708 begin
709 if (Integer(ch) >= 48+base) then exit;
710 result := Integer(ch)-48;
711 end
712 else
713 begin
714 if (ch >= '0') and (ch <= '9') then begin result := Integer(ch)-48; exit; end;
715 if (ch >= 'a') and (ch <= 'z') then Dec(ch, 32); // poor man's tolower()
716 if (ch < 'A') or (Integer(ch) >= 65+(base-10)) then exit;
717 result := Integer(ch)-65+10;
718 end;
719 end;
722 // ////////////////////////////////////////////////////////////////////////// //
723 function quoteStr (const s: AnsiString): AnsiString;
725 function squote (const s: AnsiString): AnsiString;
726 var
727 f: Integer;
728 begin
729 result := '''';
730 for f := 1 to Length(s) do
731 begin
732 if (s[f] = '''') then result += '''';
733 result += s[f];
734 end;
735 result += '''';
736 end;
738 function dquote (const s: AnsiString): AnsiString;
739 var
740 f: Integer;
741 ch: AnsiChar;
742 begin
743 result := '"';
744 for f := 1 to Length(s) do
745 begin
746 ch := s[f];
747 if (ch = #0) then result += '\z'
748 else if (ch = #9) then result += '\t'
749 else if (ch = #10) then result += '\n'
750 else if (ch = #13) then result += '\r'
751 else if (ch = #27) then result += '\e'
752 else if (ch < ' ') or (ch = #127) then
753 begin
754 result += '\x';
755 result += LowerCase(IntToHex(Integer(ch), 2));
756 end
757 else if (ch = '"') or (ch = '\') then
758 begin
759 result += '\';
760 result += ch;
761 end
762 else
763 begin
764 result += ch;
765 end;
766 end;
767 result += '"';
768 end;
770 var
771 needSingle: Boolean = false;
772 f: Integer;
773 begin
774 for f := 1 to Length(s) do
775 begin
776 if (s[f] = '''') then begin needSingle := true; continue; end;
777 if (s[f] < ' ') or (s[f] = #127) then begin result := dquote(s); exit; end;
778 end;
779 if needSingle then result := squote(s) else result := ''''+s+'''';
780 end;
783 // ////////////////////////////////////////////////////////////////////////// //
784 function getFilenameExt (const fn: AnsiString): AnsiString;
785 var
786 pos: Integer;
787 ch: AnsiChar;
788 begin
789 pos := Length(fn);
790 while (pos > 0) do
791 begin
792 ch := fn[pos];
793 if (ch = '.') then
794 begin
795 if (pos = Length(fn)) then result := '' else result := Copy(fn, pos, Length(fn)-pos+1);
796 exit;
797 end;
798 if (ch = '/') or (ch = '\') then break;
799 Dec(pos);
800 end;
801 result := ''; // no extension
802 end;
805 function setFilenameExt (const fn, ext: AnsiString): AnsiString;
806 var
807 pos: Integer;
808 ch: AnsiChar;
809 begin
810 result := fn;
811 if (Length(ext) = 0) or (ext = '.') then exit;
812 pos := Length(fn);
813 while (pos > 0) do
814 begin
815 ch := fn[pos];
816 if (ch = '.') then exit;
817 if (ch = '/') or (ch = '\') then break;
818 Dec(pos);
819 end;
820 if (ext[1] <> '.') then result += '.';
821 result += ext;
822 end;
825 function forceFilenameExt (const fn, ext: AnsiString): AnsiString;
826 var
827 pos: Integer;
828 ch: AnsiChar;
829 begin
830 result := fn;
831 pos := Length(fn);
832 while (pos > 0) do
833 begin
834 ch := fn[pos];
835 if (ch = '.') then
836 begin
837 if (Length(ext) = 0) or (ext = '.') then
838 begin
839 result := Copy(fn, 1, pos-1);
840 end
841 else
842 begin
843 if (ext[1] = '.') then result := Copy(fn, 1, pos-1) else result := Copy(fn, 1, pos);
844 result += ext;
845 exit;
846 end;
847 end;
848 if (ch = '/') or (ch = '\') then break;
849 Dec(pos);
850 end;
851 if (Length(ext) > 0) then
852 begin
853 if (ext[1] <> '.') then result += '.';
854 result += ext;
855 end;
856 end;
859 // strips out name from `fn`, leaving trailing slash
860 function getFilenamePath (const fn: AnsiString): AnsiString;
861 var
862 pos: Integer;
863 ch: AnsiChar;
864 begin
865 if (Length(fn) = 0) then begin result := './'; exit; end;
866 if (fn[Length(fn)] = '/') or (fn[Length(fn)] = '\') then begin result := fn; exit; end;
867 pos := Length(fn);
868 while (pos > 0) do
869 begin
870 ch := fn[pos];
871 if (ch = '/') or (ch = '\') then begin result := Copy(fn, 1, pos); exit; end;
872 Dec(pos);
873 end;
874 result := './'; // no path -> current dir
875 end;
878 // ends with '/' or '\'?
879 function isFilenamePath (const fn: AnsiString): Boolean;
880 begin
881 if (Length(fn) = 0) then
882 begin
883 result := false;
884 end
885 else
886 begin
887 result := (fn[Length(fn)] = '/') or (fn[Length(fn)] = '\');
888 end;
889 end;
892 // strips extra trailing slashes in `path, and extra leading slashes in `fn`
893 // will add slash to `path`, even if `fn` is empty!
894 function filenameConcat (const path, fn: AnsiString): AnsiString;
895 var
896 pos: Integer;
897 begin
898 pos := 1;
899 while (pos <= Length(fn)) and ((fn[pos] = '/') or (fn[pos] = '\')) do Inc(pos);
900 result := path;
901 if (Length(result) > 0) and ((result[Length(result)] <> '/') and (result[Length(result)] <> '\')) then result += '/';
902 if (pos <= Length(fn)) then
903 begin
904 result += Copy(fn, pos, Length(fn)-pos+1);
905 //FIXME: make this faster!
906 while (Length(result) > 0) and ((result[Length(result)] = '/') or (result[Length(result)] = '\')) do
907 begin
908 Delete(result, Length(result), 1);
909 end;
910 if (fn[Length(fn)] = '/') or (fn[Length(fn)] = '\') then result += '/';
911 end;
912 end;
915 function hasWadExtension (const fn: AnsiString): Boolean;
916 var
917 ext, newExt: AnsiString;
918 begin
919 ext := getFilenameExt(fn);
920 result := true;
921 for newExt in wadExtensions do if (StrEquCI1251(ext, newExt)) then exit;
922 result := false;
923 //result := StrEquCI1251(ext, '.wad') or StrEquCI1251(ext, '.pk3') or StrEquCI1251(ext, '.zip') or StrEquCI1251(ext, '.dfz');
924 end;
927 function addWadExtension (const fn: AnsiString): AnsiString;
928 begin
929 result := fn;
930 if not hasWadExtension(result) then result := result+'.wad';
931 end;
934 function isWadData (data: Pointer; len: LongWord): Boolean;
935 var p: PChar;
936 begin
937 p := PChar(data);
938 Result :=
939 (* ZIP *)
940 ((len > 3) and (p[0] = 'P') and (p[1] = 'K') and (p[2] = #03) and (p[3] = #04)) or
941 ((len > 3) and (p[0] = 'P') and (p[1] = 'K') and (p[2] = #05) and (p[3] = #06)) or
942 (* PACK *)
943 ((len > 3) and (p[0] = 'P') and (p[1] = 'A') and (p[2] = 'C') and (p[3] = 'K')) or
944 ((len > 3) and (p[0] = 'S') and (p[1] = 'P') and (p[2] = 'A') and (p[3] = 'K')) or
945 (* DFWAD *)
946 ((len > 5) and (p[0] = 'D') and (p[1] = 'F') and (p[2] = 'W') and (p[3] = 'A') and (p[4] = 'D') and (p[5] = #01))
947 end;
950 function isWadPath (const fn: AnsiString): Boolean;
951 var
952 pos: Integer;
953 s, wext: AnsiString;
954 begin
955 result := false;
956 pos := 1;
957 while (pos <= Length(fn)) do
958 begin
959 if (fn[pos] = ':') then
960 begin
961 if (Length(fn)-pos < 1) then break;
962 if (pos-4 > 1) and (fn[pos-4] = '.') and ((fn[pos+1] = '\') or (fn[pos+1] = '/')) then
963 begin
964 s := Copy(fn, pos-4, 4);
965 for wext in wadExtensions do
966 begin
967 if strEquCI1251(s, wext) then
968 begin
969 result := true;
970 exit;
971 end;
972 end;
973 end;
974 end;
975 Inc(pos);
976 end;
977 end;
980 function int64ToStrComma (i: Int64): AnsiString;
981 var
982 f: Integer;
983 begin
984 Str(i, result);
985 f := Length(result)+1;
986 while f > 4 do
987 begin
988 Dec(f, 3); Insert(',', result, f);
989 end;
990 end;
993 function upcase1251 (ch: AnsiChar): AnsiChar; inline;
994 begin
995 if ch < #128 then
996 begin
997 if (ch >= 'a') and (ch <= 'z') then Dec(ch, 32);
998 end
999 else
1000 begin
1001 if (ch >= #224) and (ch <= #255) then
1002 begin
1003 Dec(ch, 32);
1004 end
1005 else
1006 begin
1007 case ch of
1008 #184, #186, #191: Dec(ch, 16);
1009 #162, #179: Dec(ch);
1010 end;
1011 end;
1012 end;
1013 result := ch;
1014 end;
1017 function locase1251 (ch: AnsiChar): AnsiChar; inline;
1018 begin
1019 if ch < #128 then
1020 begin
1021 if (ch >= 'A') and (ch <= 'Z') then Inc(ch, 32);
1022 end
1023 else
1024 begin
1025 if (ch >= #192) and (ch <= #223) then
1026 begin
1027 Inc(ch, 32);
1028 end
1029 else
1030 begin
1031 case ch of
1032 #168, #170, #175: Inc(ch, 16);
1033 #161, #178: Inc(ch);
1034 end;
1035 end;
1036 end;
1037 result := ch;
1038 end;
1040 function IsValid1251 (ch: Word): Boolean;
1041 begin
1042 result := ((ch = Ord('?')) or (wc2shitmap[ch] <> '?')) and (wc2shitmap[ch] <> #$98)
1043 end;
1045 function IsPrintable1251 (ch: AnsiChar): Boolean;
1046 begin
1047 result := (ch >= #32) and (ch <> #127) and (ch <> #$98)
1048 end;
1051 function strEquCI1251 (const s0, s1: AnsiString): Boolean;
1052 var
1053 i: Integer;
1054 begin
1055 result := false;
1056 if length(s0) <> length(s1) then exit;
1057 for i := 1 to length(s0) do if UpCase1251(s0[i]) <> UpCase1251(s1[i]) then exit;
1058 result := true;
1059 end;
1062 function toLowerCase1251 (const s: AnsiString): AnsiString;
1063 var
1064 f: Integer;
1065 ch: AnsiChar;
1066 begin
1067 for ch in s do
1068 begin
1069 if (ch <> LoCase1251(ch)) then
1070 begin
1071 result := '';
1072 SetLength(result, Length(s));
1073 for f := 1 to Length(s) do result[f] := LoCase1251(s[f]);
1074 exit;
1075 end;
1076 end;
1077 // nothing to do
1078 result := s;
1079 end;
1082 // ////////////////////////////////////////////////////////////////////////// //
1083 // utils
1084 // `ch`: utf8 start
1085 // -1: invalid utf8
1086 function utf8CodeLen (ch: Word): Integer;
1087 begin
1088 if ch < $80 then begin result := 1; exit; end;
1089 if (ch and $FE) = $FC then begin result := 6; exit; end;
1090 if (ch and $FC) = $F8 then begin result := 5; exit; end;
1091 if (ch and $F8) = $F0 then begin result := 4; exit; end;
1092 if (ch and $F0) = $E0 then begin result := 3; exit; end;
1093 if (ch and $E0) = $C0 then begin result := 2; exit; end;
1094 result := -1; // invalid
1095 end;
1098 function utf8Valid (const s: AnsiString): Boolean;
1099 var
1100 pos, len: Integer;
1101 begin
1102 result := false;
1103 pos := 1;
1104 while pos <= length(s) do
1105 begin
1106 len := utf8CodeLen(Byte(s[pos]));
1107 if len < 1 then exit; // invalid sequence start
1108 if pos+len-1 > length(s) then exit; // out of chars in string
1109 Dec(len);
1110 Inc(pos);
1111 // check other sequence bytes
1112 while len > 0 do
1113 begin
1114 if (Byte(s[pos]) and $C0) <> $80 then exit;
1115 Dec(len);
1116 Inc(pos);
1117 end;
1118 end;
1119 result := true;
1120 end;
1123 // ////////////////////////////////////////////////////////////////////////// //
1124 const
1125 uni2wint: array [128..255] of Word = (
1126 $0402,$0403,$201A,$0453,$201E,$2026,$2020,$2021,$20AC,$2030,$0409,$2039,$040A,$040C,$040B,$040F,
1127 $0452,$2018,$2019,$201C,$201D,$2022,$2013,$2014,$003F,$2122,$0459,$203A,$045A,$045C,$045B,$045F,
1128 $00A0,$040E,$045E,$0408,$00A4,$0490,$00A6,$00A7,$0401,$00A9,$0404,$00AB,$00AC,$00AD,$00AE,$0407,
1129 $00B0,$00B1,$0406,$0456,$0491,$00B5,$00B6,$00B7,$0451,$2116,$0454,$00BB,$0458,$0405,$0455,$0457,
1130 $0410,$0411,$0412,$0413,$0414,$0415,$0416,$0417,$0418,$0419,$041A,$041B,$041C,$041D,$041E,$041F,
1131 $0420,$0421,$0422,$0423,$0424,$0425,$0426,$0427,$0428,$0429,$042A,$042B,$042C,$042D,$042E,$042F,
1132 $0430,$0431,$0432,$0433,$0434,$0435,$0436,$0437,$0438,$0439,$043A,$043B,$043C,$043D,$043E,$043F,
1133 $0440,$0441,$0442,$0443,$0444,$0445,$0446,$0447,$0448,$0449,$044A,$044B,$044C,$044D,$044E,$044F
1134 );
1137 function decodeUtf8Char (s: AnsiString; var pos: Integer): AnsiChar;
1138 var
1139 b, c: Integer;
1140 begin
1141 (* The following encodings are valid, except for the 5 and 6 byte
1142 * combinations:
1143 * 0xxxxxxx
1144 * 110xxxxx 10xxxxxx
1145 * 1110xxxx 10xxxxxx 10xxxxxx
1146 * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1147 * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
1148 * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
1149 *)
1150 result := '?';
1151 if pos > length(s) then exit;
1153 b := Byte(s[pos]);
1154 Inc(pos);
1155 if b < $80 then begin result := AnsiChar(b); exit; end;
1157 // mask out unused bits
1158 if (b and $FE) = $FC then b := b and $01
1159 else if (b and $FC) = $F8 then b := b and $03
1160 else if (b and $F8) = $F0 then b := b and $07
1161 else if (b and $F0) = $E0 then b := b and $0F
1162 else if (b and $E0) = $C0 then b := b and $1F
1163 else exit; // invalid utf8
1165 // now continue
1166 while pos <= length(s) do
1167 begin
1168 c := Byte(s[pos]);
1169 if (c and $C0) <> $80 then break; // no more
1170 b := b shl 6;
1171 b := b or (c and $3F);
1172 Inc(pos);
1173 end;
1175 // done, try 1251
1176 for c := 128 to 255 do if uni2wint[c] = b then begin result := AnsiChar(c and $FF); exit; end;
1177 // alas
1178 end;
1181 function utf8to1251 (s: AnsiString): AnsiString;
1182 var
1183 pos: Integer;
1184 begin
1185 if not utf8Valid(s) then begin result := s; exit; end;
1186 pos := 1;
1187 while pos <= length(s) do
1188 begin
1189 if Byte(s[pos]) >= $80 then break;
1190 Inc(pos);
1191 end;
1192 if pos > length(s) then begin result := s; exit; end; // nothing to do here
1193 result := '';
1194 pos := 1;
1195 while pos <= length(s) do result := result+decodeUtf8Char(s, pos);
1196 end;
1199 // ////////////////////////////////////////////////////////////////////////// //
1200 // findFileCI eats case-insensitive path, traverses it and rewrites it to a
1201 // case-sensetive. result value means success.
1202 // if file/dir not founded than pathname is in undefined state!
1203 function findFileCI (var pathname: AnsiString; lastIsDir: Boolean=false): Boolean;
1204 var
1205 sr: TSearchRec;
1206 npt: AnsiString;
1207 newname: AnsiString = '';
1208 curname: AnsiString;
1209 wantdir: Boolean;
1210 attr: LongInt;
1211 foundher: Boolean;
1212 begin
1213 npt := pathname;
1214 result := (length(npt) > 0);
1215 if (length(npt) > 0) and ((npt[1] = '/') or (npt[1] = '\')) then newname := '/';
1216 while length(npt) > 0 do
1217 begin
1218 // remove trailing slashes
1219 while (length(npt) > 0) and ((npt[1] = '/') or (npt[1] = '\')) do Delete(npt, 1, 1);
1220 if length(npt) = 0 then break;
1221 // extract name
1222 curname := '';
1223 while (length(npt) > 0) and (npt[1] <> '/') and (npt[1] <> '\') do
1224 begin
1225 curname := curname+npt[1];
1226 Delete(npt, 1, 1);
1227 end;
1228 // remove trailing slashes again
1229 while (length(npt) > 0) and ((npt[1] = '/') or (npt[1] = '\')) do Delete(npt, 1, 1);
1230 wantdir := lastIsDir or (length(npt) > 0); // do we want directory here?
1231 //writeln(Format('npt=[%s]; newname=[%s]; curname=[%s]; wantdir=%d', [npt, newname, curname, Integer(wantdir)]));
1232 // try the easiest case first
1233 attr := FileGetAttr(newname+curname);
1234 if attr <> -1 then
1235 begin
1236 if wantdir = ((attr and faDirectory) <> 0) then
1237 begin
1238 // i found her!
1239 newname := newname+curname;
1240 if wantdir then newname := newname+'/';
1241 continue;
1242 end;
1243 end;
1244 //writeln(Format('npt=[%s]; newname=[%s]; curname=[%s]; wantdir=%d', [npt, newname, curname, Integer(wantdir)]));
1245 // alas, either not found, or invalid attributes
1246 foundher := false;
1247 try
1248 if FindFirst(newname+'*', faAnyFile, sr) = 0 then
1249 repeat
1250 if (wantdir = ((sr.attr and faDirectory) <> 0)) and StrEquCI1251(sr.name, curname) then
1251 begin
1252 // i found her!
1253 newname := newname+sr.name;
1254 if wantdir then newname := newname+'/';
1255 foundher := true;
1256 break;
1257 end;
1258 until FindNext(sr) <> 0;
1259 finally
1260 FindClose(sr);
1261 end;
1262 if not foundher then begin newname := ''; result := false; break; end;
1263 end;
1264 if result then pathname := newname;
1265 end;
1268 function isWadNamesEqu (wna, wnb: AnsiString): Boolean;
1269 var
1270 ext, newExt: AnsiString;
1271 found: Boolean;
1272 begin
1273 result := StrEquCI1251(wna, wnb);
1274 if result then exit;
1275 // check first ext
1276 ext := getFilenameExt(wna);
1277 found := false;
1278 for newExt in wadExtensions do if (StrEquCI1251(ext, newExt)) then begin found := true; break; end;
1279 if not found then exit;
1280 // check second ext
1281 ext := getFilenameExt(wnb);
1282 found := false;
1283 for newExt in wadExtensions do if (StrEquCI1251(ext, newExt)) then begin found := true; break; end;
1284 if not found then exit;
1285 wna := forceFilenameExt(wna, '');
1286 wnb := forceFilenameExt(wnb, '');
1287 result := StrEquCI1251(wna, wnb);
1288 end;
1290 function findDiskWad (fname: AnsiString): AnsiString;
1291 var
1292 origExt: AnsiString = '';
1293 newExt: AnsiString = '';
1294 begin
1295 result := '';
1296 //writeln('findDiskWad00: fname=<', fname, '>');
1297 if (findFileCI(fname)) then begin result := fname; exit; end;
1298 origExt := getFilenameExt(fname);
1299 fname := forceFilenameExt(fname, '');
1300 //writeln(' findDiskWad01: fname=<', fname, '>; origExt=<', origExt, '>');
1301 for newExt in wadExtensions do
1302 begin
1303 //writeln(' findDiskWad02: fname=<', fname, '>; origExt=<', origExt, '>; newExt=<', newExt, '>');
1304 if (StrEquCI1251(newExt, origExt)) then
1305 begin
1306 //writeln(' SKIP');
1307 continue;
1308 end;
1309 result := fname+newExt;
1310 if (findFileCI(result)) then exit;
1311 end;
1312 result := '';
1313 end;
1316 function openDiskFileRO (pathname: AnsiString): TStream;
1317 begin
1318 if not findFileCI(pathname) then raise EFileNotFoundException.Create('can''t open file "'+pathname+'"');
1319 result := TFileStream.Create(pathname, fmOpenRead or {fmShareDenyWrite}fmShareDenyNone);
1320 end;
1322 function createDiskFile (pathname: AnsiString): TStream;
1323 var
1324 path: AnsiString;
1325 begin
1326 path := ExtractFilePath(pathname);
1327 if length(path) > 0 then
1328 begin
1329 if not findFileCI(path, true) then raise Exception.Create('can''t create file "'+pathname+'"');
1330 end;
1331 result := TFileStream.Create(path+ExtractFileName(pathname), fmCreate);
1332 end;
1335 function openDiskFileRW (pathname: AnsiString): TStream;
1336 var
1337 path: AnsiString;
1338 oldname: AnsiString;
1339 begin
1340 //writeln('*** TRYING R/W FILE "', pathname, '"');
1341 path := ExtractFilePath(pathname);
1342 if length(path) > 0 then
1343 begin
1344 if not findFileCI(path, true) then raise Exception.Create('can''t create file "'+pathname+'"');
1345 end;
1346 oldname := pathname;
1347 if findFileCI(oldname) then
1348 begin
1349 //writeln('*** found old file "', oldname, '"');
1350 result := TFileStream.Create(oldname, fmOpenReadWrite or fmShareDenyWrite);
1351 end
1352 else
1353 begin
1354 result := TFileStream.Create(path+ExtractFileName(pathname), fmCreate);
1355 end;
1356 end;
1359 procedure writeIntegerLE (st: TStream; vp: Pointer; size: Integer);
1360 {$IFDEF ENDIAN_LITTLE}
1361 begin
1362 st.writeBuffer(vp^, size);
1363 end;
1364 {$ELSE}
1365 var
1366 p: PByte;
1367 begin
1368 p := PByte(vp)+size-1;
1369 while size > 0 do
1370 begin
1371 st.writeBuffer(p^, 1);
1372 Dec(size);
1373 Dec(p);
1374 end;
1375 end;
1376 {$ENDIF}
1378 procedure writeIntegerBE (st: TStream; vp: Pointer; size: Integer);
1379 {$IFDEF ENDIAN_LITTLE}
1380 var
1381 p: PByte;
1382 begin
1383 p := PByte(vp)+size-1;
1384 while size > 0 do
1385 begin
1386 st.writeBuffer(p^, 1);
1387 Dec(size);
1388 Dec(p);
1389 end;
1390 end;
1391 {$ELSE}
1392 begin
1393 st.writeBuffer(vp^, size);
1394 end;
1395 {$ENDIF}
1397 procedure writeSign (st: TStream; const sign: AnsiString);
1398 begin
1399 if (Length(sign) > 0) then st.WriteBuffer(sign[1], Length(sign));
1400 end;
1402 function checkSign (st: TStream; const sign: AnsiString): Boolean;
1403 var
1404 buf: packed array[0..7] of AnsiChar;
1405 f: Integer;
1406 begin
1407 result := false;
1408 if (Length(sign) > 0) then
1409 begin
1410 if (Length(sign) <= 8) then
1411 begin
1412 st.ReadBuffer(buf[0], Length(sign));
1413 for f := 1 to Length(sign) do if (buf[f-1] <> sign[f]) then exit;
1414 end
1415 else
1416 begin
1417 for f := 1 to Length(sign) do
1418 begin
1419 st.ReadBuffer(buf[0], 1);
1420 if (buf[0] <> sign[f]) then exit;
1421 end;
1422 end;
1423 end;
1424 result := true;
1425 end;
1427 procedure writeInt (st: TStream; v: Byte); overload; begin writeIntegerLE(st, @v, 1); end;
1428 procedure writeInt (st: TStream; v: ShortInt); overload; begin writeIntegerLE(st, @v, 1); end;
1429 procedure writeInt (st: TStream; v: Word); overload; begin writeIntegerLE(st, @v, 2); end;
1430 procedure writeInt (st: TStream; v: SmallInt); overload; begin writeIntegerLE(st, @v, 2); end;
1431 procedure writeInt (st: TStream; v: LongWord); overload; begin writeIntegerLE(st, @v, 4); end;
1432 procedure writeInt (st: TStream; v: LongInt); overload; begin writeIntegerLE(st, @v, 4); end;
1433 procedure writeInt (st: TStream; v: Int64); overload; begin writeIntegerLE(st, @v, 8); end;
1434 procedure writeInt (st: TStream; v: UInt64); overload; begin writeIntegerLE(st, @v, 8); end;
1436 procedure writeIntBE (st: TStream; v: Byte); overload; begin writeIntegerBE(st, @v, 1); end;
1437 procedure writeIntBE (st: TStream; v: ShortInt); overload; begin writeIntegerBE(st, @v, 1); end;
1438 procedure writeIntBE (st: TStream; v: Word); overload; begin writeIntegerBE(st, @v, 2); end;
1439 procedure writeIntBE (st: TStream; v: SmallInt); overload; begin writeIntegerBE(st, @v, 2); end;
1440 procedure writeIntBE (st: TStream; v: LongWord); overload; begin writeIntegerBE(st, @v, 4); end;
1441 procedure writeIntBE (st: TStream; v: LongInt); overload; begin writeIntegerBE(st, @v, 4); end;
1442 procedure writeIntBE (st: TStream; v: Int64); overload; begin writeIntegerBE(st, @v, 8); end;
1443 procedure writeIntBE (st: TStream; v: UInt64); overload; begin writeIntegerBE(st, @v, 8); end;
1445 procedure writeBool (st: TStream; b: Boolean); begin writeInt(st, Byte(b)); end;
1446 function readBool (st: TStream): Boolean; begin result := (readByte(st) <> 0); end;
1449 procedure writeStr (st: TStream; const str: AnsiString; maxlen: LongWord=65535);
1450 begin
1451 if (Length(str) > maxlen) then raise XStreamError.Create('string too long');
1452 if (maxlen <= 65535) then writeInt(st, Word(Length(str))) else writeInt(st, LongWord(Length(str)));
1453 if (Length(str) > 0) then st.WriteBuffer(str[1], Length(str));
1454 end;
1456 function readStr (st: TStream; maxlen: LongWord=65535): AnsiString;
1457 var
1458 len: Integer;
1459 begin
1460 result := '';
1461 if (maxlen <= 65535) then len := readWord(st) else len := Integer(readLongWord(st));
1462 if (len < 0) or (len > maxlen) then raise XStreamError.Create('string too long');
1463 if (len > 0) then
1464 begin
1465 SetLength(result, len);
1466 st.ReadBuffer(result[1], len);
1467 end;
1468 end;
1471 procedure readIntegerLE (st: TStream; vp: Pointer; size: Integer);
1472 {$IFDEF ENDIAN_LITTLE}
1473 begin
1474 st.readBuffer(vp^, size);
1475 end;
1476 {$ELSE}
1477 var
1478 p: PByte;
1479 begin
1480 p := PByte(vp)+size-1;
1481 while size > 0 do
1482 begin
1483 st.readBuffer(p^, 1);
1484 Dec(size);
1485 Dec(p);
1486 end;
1487 end;
1488 {$ENDIF}
1490 procedure readIntegerBE (st: TStream; vp: Pointer; size: Integer);
1491 {$IFDEF ENDIAN_LITTLE}
1492 var
1493 p: PByte;
1494 begin
1495 p := PByte(vp)+size-1;
1496 while size > 0 do
1497 begin
1498 st.readBuffer(p^, 1);
1499 Dec(size);
1500 Dec(p);
1501 end;
1502 end;
1503 {$ELSE}
1504 begin
1505 st.readBuffer(vp^, size);
1506 end;
1507 {$ENDIF}
1509 function readByte (st: TStream): Byte; begin readIntegerLE(st, @result, 1); end;
1510 function readShortInt (st: TStream): ShortInt; begin readIntegerLE(st, @result, 1); end;
1511 function readWord (st: TStream): Word; begin readIntegerLE(st, @result, 2); end;
1512 function readSmallInt (st: TStream): SmallInt; begin readIntegerLE(st, @result, 2); end;
1513 function readLongWord (st: TStream): LongWord; begin readIntegerLE(st, @result, 4); end;
1514 function readLongInt (st: TStream): LongInt; begin readIntegerLE(st, @result, 4); end;
1515 function readInt64 (st: TStream): Int64; begin readIntegerLE(st, @result, 8); end;
1516 function readUInt64 (st: TStream): UInt64; begin readIntegerLE(st, @result, 8); end;
1518 function readByteBE (st: TStream): Byte; begin readIntegerBE(st, @result, 1); end;
1519 function readShortIntBE (st: TStream): ShortInt; begin readIntegerBE(st, @result, 1); end;
1520 function readWordBE (st: TStream): Word; begin readIntegerBE(st, @result, 2); end;
1521 function readSmallIntBE (st: TStream): SmallInt; begin readIntegerBE(st, @result, 2); end;
1522 function readLongWordBE (st: TStream): LongWord; begin readIntegerBE(st, @result, 4); end;
1523 function readLongIntBE (st: TStream): LongInt; begin readIntegerBE(st, @result, 4); end;
1524 function readInt64BE (st: TStream): Int64; begin readIntegerBE(st, @result, 8); end;
1525 function readUInt64BE (st: TStream): UInt64; begin readIntegerBE(st, @result, 8); end;
1528 // ////////////////////////////////////////////////////////////////////////// //
1529 function nmin (a, b: Byte): Byte; inline; overload; begin if (a < b) then result := a else result := b; end;
1530 function nmin (a, b: ShortInt): ShortInt; inline; overload; begin if (a < b) then result := a else result := b; end;
1531 function nmin (a, b: Word): Word; inline; overload; begin if (a < b) then result := a else result := b; end;
1532 function nmin (a, b: SmallInt): SmallInt; inline; overload; begin if (a < b) then result := a else result := b; end;
1533 function nmin (a, b: LongWord): LongWord; inline; overload; begin if (a < b) then result := a else result := b; end;
1534 function nmin (a, b: LongInt): LongInt; inline; overload; begin if (a < b) then result := a else result := b; end;
1535 function nmin (a, b: Int64): Int64; inline; overload; begin if (a < b) then result := a else result := b; end;
1536 function nmin (a, b: UInt64): UInt64; inline; overload; begin if (a < b) then result := a else result := b; end;
1537 function nmin (a, b: Single): Single; inline; overload; begin if (a < b) then result := a else result := b; end;
1538 function nmin (a, b: Double): Double; inline; overload; begin if (a < b) then result := a else result := b; end;
1539 {$IF DEFINED(CPU386) OR DEFINED(CPUAMD64)}
1540 function nmin (a, b: Extended): Extended; inline; overload; begin if (a < b) then result := a else result := b; end;
1541 {$ENDIF}
1543 function nmax (a, b: Byte): Byte; inline; overload; begin if (a > b) then result := a else result := b; end;
1544 function nmax (a, b: ShortInt): ShortInt; inline; overload; begin if (a > b) then result := a else result := b; end;
1545 function nmax (a, b: Word): Word; inline; overload; begin if (a > b) then result := a else result := b; end;
1546 function nmax (a, b: SmallInt): SmallInt; inline; overload; begin if (a > b) then result := a else result := b; end;
1547 function nmax (a, b: LongWord): LongWord; inline; overload; begin if (a > b) then result := a else result := b; end;
1548 function nmax (a, b: LongInt): LongInt; inline; overload; begin if (a > b) then result := a else result := b; end;
1549 function nmax (a, b: Int64): Int64; inline; overload; begin if (a > b) then result := a else result := b; end;
1550 function nmax (a, b: UInt64): UInt64; inline; overload; begin if (a > b) then result := a else result := b; end;
1551 function nmax (a, b: Single): Single; inline; overload; begin if (a > b) then result := a else result := b; end;
1552 function nmax (a, b: Double): Double; inline; overload; begin if (a > b) then result := a else result := b; end;
1553 {$IF DEFINED(CPU386) OR DEFINED(CPUAMD64)}
1554 function nmax (a, b: Extended): Extended; inline; overload; begin if (a > b) then result := a else result := b; end;
1555 {$ENDIF}
1557 function nclamp (v, a, b: Byte): Byte; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1558 function nclamp (v, a, b: ShortInt): ShortInt; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1559 function nclamp (v, a, b: Word): Word; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1560 function nclamp (v, a, b: SmallInt): SmallInt; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1561 function nclamp (v, a, b: LongWord): LongWord; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1562 function nclamp (v, a, b: LongInt): LongInt; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1563 function nclamp (v, a, b: Int64): Int64; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1564 function nclamp (v, a, b: UInt64): UInt64; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1565 function nclamp (v, a, b: Single): Single; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1566 function nclamp (v, a, b: Double): Double; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1567 {$IF DEFINED(CPU386) OR DEFINED(CPUAMD64)}
1568 function nclamp (v, a, b: Extended): Extended; inline; overload; begin if (v < a) then result := a else if (v > b) then result := b else result := v; end;
1569 {$ENDIF}
1571 // ////////////////////////////////////////////////////////////////////////// //
1572 {$IFDEF WINDOWS}
1573 function snprintf (buf: PAnsiChar; bufsize: SizeUInt; const fmt: PAnsiChar): SizeUInt; cdecl; varargs; external 'msvcrt.dll' name '_snprintf';
1574 {$ELSE}
1575 function snprintf (buf: PAnsiChar; bufsize: SizeUInt; const fmt: PAnsiChar): SizeUInt; cdecl; varargs; external 'libc' name 'snprintf';
1576 {$ENDIF}
1579 (*
1580 procedure conwriter (constref buf; len: SizeUInt);
1581 var
1582 ss: ShortString;
1583 slen: Integer;
1584 b: PByte;
1585 begin
1586 if (len < 1) then exit;
1587 b := PByte(@buf);
1588 while (len > 0) do
1589 begin
1590 if (len > 255) then slen := 255 else slen := Integer(len);
1591 Move(b^, ss[1], len);
1592 ss[0] := AnsiChar(slen);
1593 write(ss);
1594 b += slen;
1595 len -= slen;
1596 end;
1597 end;
1598 *)
1601 function formatstrf (const fmt: AnsiString; const args: array of const; writerCB: TFormatStrFCallback=nil): AnsiString;
1602 const
1603 PadSpaces: AnsiString = ' ';
1604 PadZeroes: AnsiString = '00000000000000000000000000000000000000000000000000000000000000000000000';
1605 var
1606 curarg: Integer = 0; // current arg in `args`
1607 sign, fmtch: AnsiChar;
1608 zeropad: Boolean;
1609 width, prec: Integer; // width and precision
1610 spos, epos: Integer;
1611 ch: AnsiChar;
1612 strbuf: array[0..256] of AnsiChar;
1613 strblen: SizeUInt;
1614 fmtbuf: array[0..256] of AnsiChar;
1615 fmtblen: Integer;
1616 pclen: Integer;
1617 pc: PAnsiChar;
1618 ccname: ShortString;
1620 procedure writer (constref buf; len: SizeUInt);
1621 var
1622 ss: ShortString;
1623 slen: Integer;
1624 b: PByte;
1625 begin
1626 if (len < 1) then exit;
1627 b := PByte(@buf);
1628 if assigned(writerCB) then
1629 begin
1630 writerCB(b^, len);
1631 end
1632 else
1633 begin
1634 while (len > 0) do
1635 begin
1636 if (len > 255) then slen := 255 else slen := Integer(len);
1637 Move(b^, ss[1], slen);
1638 ss[0] := AnsiChar(slen);
1639 result += ss;
1640 b += slen;
1641 len -= slen;
1642 end;
1643 end;
1644 end;
1646 procedure xwrite (const s: AnsiString);
1647 begin
1648 if (Length(s) > 0) then writer(PAnsiChar(s)^, Length(s));
1649 end;
1651 procedure putFmtChar (ch: AnsiChar);
1652 begin
1653 fmtbuf[fmtblen] := ch;
1654 Inc(fmtblen);
1655 end;
1657 procedure putFmtInt (n: Integer);
1658 var
1659 len: SizeUInt;
1660 begin
1661 len := snprintf(@fmtbuf[fmtblen], Length(fmtbuf)-fmtblen, '%d', n);
1662 if (len > 0) then Inc(fmtblen, len);
1663 end;
1665 procedure buildCFormat (const pfx: AnsiString='');
1666 var
1667 f: Integer;
1668 begin
1669 fmtblen := 0;
1670 for f := 1 to Length(pfx) do putFmtChar(pfx[f]);
1671 putFmtChar('%');
1672 if (sign <> ' ') then putFmtChar(sign);
1673 if (width >= 0) then
1674 begin
1675 if (zeropad) then putFmtChar('0');
1676 putFmtInt(width);
1677 if (prec >= 0) then
1678 begin
1679 putFmtChar('.');
1680 putFmtInt(prec);
1681 end;
1682 end;
1683 putFmtChar(fmtch);
1684 fmtbuf[fmtblen] := #0;
1685 end;
1687 procedure writeStrBuf ();
1688 begin
1689 if (strblen > 0) then writer(strbuf, strblen);
1690 end;
1692 function i642str (n: Int64; hex: Boolean; hexup: Boolean): PAnsiChar;
1693 var
1694 neg: Boolean;
1695 xpos: Integer;
1696 begin
1697 if (n = $8000000000000000) then
1698 begin
1699 if hex then snprintf(@strbuf[0], Length(strbuf), '-8000000000000000')
1700 else snprintf(@strbuf[0], Length(strbuf), '-9223372036854775808');
1701 result := @strbuf[0];
1702 end
1703 else
1704 begin
1705 neg := (n < 0);
1706 if neg then n := -n;
1707 xpos := High(strbuf);
1708 strbuf[xpos] := #0; Dec(xpos);
1709 repeat
1710 if not hex then
1711 begin
1712 strbuf[xpos] := AnsiChar((n mod 10)+48);
1713 Dec(xpos);
1714 n := n div 10;
1715 end
1716 else
1717 begin
1718 if (n mod 16 > 9) then
1719 begin
1720 strbuf[xpos] := AnsiChar((n mod 16)+48+7);
1721 if not hexup then Inc(strbuf[xpos], 32);
1722 end
1723 else strbuf[xpos] := AnsiChar((n mod 16)+48);
1724 Dec(xpos);
1725 n := n div 16;
1726 end;
1727 until (n = 0);
1728 if neg then begin strbuf[xpos] := '-'; Dec(xpos); end;
1729 result := @strbuf[xpos+1];
1730 end;
1731 end;
1733 function ui642str (n: UInt64; hex: Boolean; hexup: Boolean): PAnsiChar;
1734 var
1735 xpos: Integer;
1736 begin
1737 xpos := High(strbuf);
1738 strbuf[xpos] := #0; Dec(xpos);
1739 repeat
1740 if not hex then
1741 begin
1742 strbuf[xpos] := AnsiChar((n mod 10)+48);
1743 Dec(xpos);
1744 n := n div 10;
1745 end
1746 else
1747 begin
1748 if (n mod 16 > 9) then
1749 begin
1750 strbuf[xpos] := AnsiChar((n mod 16)+48+7);
1751 if not hexup then Inc(strbuf[xpos], 32);
1752 end
1753 else strbuf[xpos] := AnsiChar((n mod 16)+48);
1754 Dec(xpos);
1755 n := n div 16;
1756 end;
1757 until (n = 0);
1758 result := @strbuf[xpos+1];
1759 end;
1761 procedure indent (len: Integer);
1762 var
1763 ilen: Integer;
1764 begin
1765 while (len > 0) do
1766 begin
1767 if (len > Length(PadSpaces)) then ilen := Length(PadSpaces) else ilen := len;
1768 writer(PAnsiChar(PadSpaces)^, ilen);
1769 Dec(len, ilen);
1770 end;
1771 end;
1773 procedure indent0 (len: Integer);
1774 var
1775 ilen: Integer;
1776 begin
1777 while (len > 0) do
1778 begin
1779 if (len > Length(PadZeroes)) then ilen := Length(PadZeroes) else ilen := len;
1780 writer(PAnsiChar(PadZeroes)^, ilen);
1781 Dec(len, ilen);
1782 end;
1783 end;
1785 begin
1786 result := '';
1787 spos := 1;
1788 while (spos <= Length(fmt)) do
1789 begin
1790 // print literal part
1791 epos := spos;
1792 while (epos <= Length(fmt)) and (fmt[epos] <> '%') do Inc(epos);
1793 // output literal part
1794 if (epos > spos) then
1795 begin
1796 if (epos > Length(fmt)) then
1797 begin
1798 writer((PAnsiChar(fmt)+spos-1)^, epos-spos);
1799 break;
1800 end;
1801 if (epos+1 > Length(fmt)) then Inc(epos) // last percent, output literally
1802 else if (fmt[epos+1] = '%') then // special case
1803 begin
1804 Inc(epos);
1805 writer((PAnsiChar(fmt)+spos-1)^, epos-spos);
1806 spos := epos+1;
1807 end
1808 else
1809 begin
1810 writer((PAnsiChar(fmt)+spos-1)^, epos-spos);
1811 spos := epos;
1812 end;
1813 continue;
1814 end;
1815 // check if we have argument for this format string
1816 if (curarg > High(args)) then
1817 begin
1818 xwrite('<OUT OF ARGS>');
1819 writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1);
1820 break;
1821 end;
1822 // skip percent
1823 if (spos+1 > Length(fmt)) then break; // oops
1824 assert(fmt[spos] = '%');
1825 Inc(spos);
1826 // parse format; check for sign
1827 if (fmt[spos] = '-') then begin sign := '-'; Inc(spos); end
1828 else if (fmt[spos] = '+') then begin sign := '+'; Inc(spos); end
1829 else sign := ' ';
1830 // parse width
1831 if (spos > Length(fmt)) then begin xwrite('<INVALID FORMAT>'); break; end;
1832 if (sign <> ' ') or ((fmt[spos] >= '0') and (fmt[spos] <= '9')) then
1833 begin
1834 if (fmt[spos] < '0') or (fmt[spos] > '9') then begin xwrite('<INVALID FORMAT>'); writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1); break; end;
1835 zeropad := (fmt[spos] = '0');
1836 width := 0;
1837 while (spos <= Length(fmt)) do
1838 begin
1839 ch := fmt[spos];
1840 if (ch < '0') or (ch > '9') then break;
1841 width := width*10+Integer(ch)-48;
1842 Inc(spos);
1843 end;
1844 end
1845 else
1846 begin
1847 width := -1;
1848 zeropad := false;
1849 end;
1850 // parse precision
1851 prec := -1;
1852 if (spos <= Length(fmt)) and (fmt[spos] = '.') then
1853 begin
1854 Inc(spos);
1855 if (spos > Length(fmt)) then begin xwrite('<INVALID FORMAT>'); break; end;
1856 if (fmt[spos] < '0') or (fmt[spos] > '9') then begin xwrite('<INVALID FORMAT>'); writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1); break; end;
1857 prec := 0;
1858 while (spos <= Length(fmt)) do
1859 begin
1860 ch := fmt[spos];
1861 if (ch < '0') or (ch > '9') then break;
1862 prec := prec*10+Integer(ch)-48;
1863 Inc(spos);
1864 end;
1865 end;
1866 // get format char
1867 if (spos > Length(fmt)) then begin xwrite('<INVALID FORMAT>'); break; end;
1868 fmtch := fmt[spos];
1869 Inc(spos);
1870 // done parsing format, check for valid format chars
1871 if not (fmtch in ['s','u','d','x','X','p','f','g','c']) then begin xwrite('<INVALID FORMAT CHAR>'); writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1); break; end;
1872 // now write formatted string
1873 case args[curarg].VType of
1874 vtInteger: // args[curarg].VInteger
1875 begin
1876 if not (fmtch in ['s','u','d','x','X']) then begin xwrite('<INVALID FORMAT CHAR>'); writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1); break; end;
1877 if (fmtch = 's') then fmtch := 'd';
1878 buildCFormat();
1879 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], args[curarg].VInteger);
1880 writeStrBuf();
1881 end;
1882 vtBoolean: // args[curarg].VBoolean
1883 case fmtch of
1884 's':
1885 begin
1886 buildCFormat();
1887 if args[curarg].VBoolean then strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], 'true')
1888 else strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], 'false');
1889 writeStrBuf();
1890 end;
1891 'c':
1892 begin
1893 buildCFormat();
1894 if args[curarg].VBoolean then strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], AnsiChar('t'))
1895 else strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], AnsiChar('f'));
1896 writeStrBuf();
1897 end;
1898 'u', 'd', 'x', 'X':
1899 begin
1900 buildCFormat();
1901 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], Integer(args[curarg].VBoolean));
1902 writeStrBuf();
1903 end;
1904 else
1905 begin
1906 xwrite('<INVALID FORMAT CHAR>');
1907 writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1);
1908 break;
1909 end;
1910 end;
1911 vtChar: // args[curarg].VChar
1912 case fmtch of
1913 's', 'c':
1914 begin
1915 fmtch := 'c';
1916 buildCFormat();
1917 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], args[curarg].VChar);
1918 writeStrBuf();
1919 end;
1920 'u', 'd', 'x', 'X':
1921 begin
1922 buildCFormat();
1923 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], Integer(args[curarg].VChar));
1924 writeStrBuf();
1925 end;
1926 else
1927 begin
1928 xwrite('<INVALID FORMAT CHAR>');
1929 writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1);
1930 break;
1931 end;
1932 end;
1933 //vtWideChar: begin end; // args[curarg].VWideChar (WideChar)
1934 vtExtended: // args[curarg].VExtended^
1935 case fmtch of
1936 's', 'g':
1937 begin
1938 fmtch := 'g';
1939 buildCFormat();
1940 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], Double(args[curarg].VExtended^));
1941 writeStrBuf();
1942 end;
1943 'f':
1944 begin
1945 buildCFormat();
1946 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], Double(args[curarg].VExtended^));
1947 writeStrBuf();
1948 end;
1949 'd':
1950 begin
1951 buildCFormat();
1952 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], Integer(trunc(args[curarg].VExtended^)));
1953 writeStrBuf();
1954 end;
1955 'u', 'x', 'X':
1956 begin
1957 buildCFormat();
1958 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], LongWord(trunc(args[curarg].VExtended^)));
1959 writeStrBuf();
1960 end;
1961 else
1962 begin
1963 xwrite('<INVALID FORMAT CHAR>');
1964 writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1);
1965 break;
1966 end;
1967 end;
1968 vtString: // args[curarg].VString^ (PShortString)
1969 begin
1970 if (sign <> '-') then indent(width-Length(args[curarg].VString^));
1971 writer(args[curarg].VString^[1], Length(args[curarg].VString^));
1972 if (sign = '-') then indent(width-Length(args[curarg].VString^));
1973 end;
1974 vtPointer: // args[curarg].VPointer
1975 case fmtch of
1976 's':
1977 begin
1978 fmtch := 'x';
1979 if (width < 8) then width := 8;
1980 zeropad := true;
1981 buildCFormat('0x');
1982 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], PtrUInt(args[curarg].VPointer));
1983 writeStrBuf();
1984 end;
1985 'u', 'd', 'x', 'p', 'X':
1986 begin
1987 if (fmtch = 'p') then fmtch := 'x';
1988 if (width < 8) then width := 8;
1989 zeropad := true;
1990 buildCFormat('0x');
1991 strblen := snprintf(@strbuf[0], Length(strbuf), @fmtbuf[0], PtrUInt(args[curarg].VPointer));
1992 writeStrBuf();
1993 end;
1994 else
1995 begin
1996 xwrite('<INVALID FORMAT CHAR>');
1997 writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1);
1998 break;
1999 end;
2000 end;
2001 vtPChar: // args[curarg].VPChar
2002 if (args[curarg].VPChar = nil) then
2003 begin
2004 if (sign <> '-') then indent(width-3);
2005 xwrite('nil');
2006 if (sign = '-') then indent(width-3);
2007 end
2008 else
2009 begin
2010 pclen := 0;
2011 while (args[curarg].VPChar[pclen] <> #0) do Inc(pclen);
2012 if (sign <> '-') then indent(width-pclen);
2013 writer(args[curarg].VPChar^, pclen);
2014 if (sign = '-') then indent(width-pclen);
2015 end;
2016 vtObject: // args[curarg].VObject.Classname (TObject)
2017 begin
2018 if (args[curarg].VObject <> nil) then ccname := args[curarg].VObject.Classname else ccname := '<nil>';
2019 if (sign <> '-') then indent(width-Length(ccname));
2020 xwrite(ccname);
2021 if (sign = '-') then indent(width-Length(ccname));
2022 end;
2023 vtClass: // args[curarg].VClass.Classname (TClass)
2024 begin
2025 if (args[curarg].VClass <> nil) then ccname := args[curarg].VClass.Classname else ccname := '<nil>';
2026 if (sign <> '-') then indent(width-Length(ccname));
2027 xwrite(ccname);
2028 if (sign = '-') then indent(width-Length(ccname));
2029 end;
2030 //vtPWideChar: begin end; // args[curarg].VPWideChar (PWideChar)
2031 vtAnsiString: // AnsiString(args[curarg].VAnsiString) (Pointer)
2032 begin
2033 if (sign <> '-') then indent(width-Length(AnsiString(args[curarg].VAnsiString)));
2034 xwrite(AnsiString(args[curarg].VAnsiString));
2035 if (sign = '-') then indent(width-Length(AnsiString(args[curarg].VAnsiString)));
2036 end;
2037 //vtCurrency: begin end; // args[curarg].VCurrency (PCurrency)
2038 //vtVariant: begin end; // args[curarg].VVariant^ (PVariant)
2039 //vtInterface: begin end; // args[curarg].VInterface (Pointer);
2040 //vtWideString: begin end; // args[curarg].VWideString (Pointer);
2041 vtInt64: // args[curarg].VInt64^ (PInt64)
2042 begin
2043 case fmtch of
2044 's','d','u': pc := i642str(args[curarg].VInt64^, false, false);
2045 'x': pc := i642str(args[curarg].VInt64^, true, false);
2046 'X': pc := i642str(args[curarg].VInt64^, true, true);
2047 else begin xwrite('<INVALID FORMAT CHAR>'); writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1); break; end;
2048 end;
2049 pclen := 0;
2050 while (pc[pclen] <> #0) do Inc(pclen);
2051 if (sign <> '-') and (width > pclen) then
2052 begin
2053 if zeropad then
2054 begin
2055 if (pc[0] = '-') or (pc[0] = '+') then
2056 begin
2057 writer(pc^, 1);
2058 indent0(width-pclen-1);
2059 Inc(pc);
2060 Dec(pclen);
2061 end
2062 else
2063 begin
2064 indent0(width-pclen);
2065 end;
2066 end
2067 else
2068 begin
2069 indent(width-pclen);
2070 end;
2071 end;
2072 writer(pc^, pclen);
2073 if (sign = '-') then indent(width-pclen);
2074 end;
2075 vtQWord: // args[curarg].VQWord^ (PQWord)
2076 begin
2077 case fmtch of
2078 's','d','u': pc := ui642str(args[curarg].VInt64^, false, false);
2079 'x': pc := ui642str(args[curarg].VInt64^, true, false);
2080 'X': pc := ui642str(args[curarg].VInt64^, true, true);
2081 else begin xwrite('<INVALID FORMAT CHAR>'); writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1); break; end;
2082 end;
2083 pclen := 0;
2084 while (pc[pclen] <> #0) do Inc(pclen);
2085 if (sign <> '-') then begin if zeropad then indent0(width-pclen) else indent(width-pclen); end;
2086 writer(pc^, pclen);
2087 if (sign = '-') then indent(width-pclen);
2088 end;
2089 else
2090 begin
2091 xwrite('<INVALID TYPE>');
2092 writer((PAnsiChar(fmt)+spos-1)^, Length(fmt)-spos+1);
2093 break;
2094 end;
2095 end;
2096 Inc(curarg);
2097 end;
2098 end;
2101 function GetDiskFileInfo (fname: AnsiString; var info: TDiskFileInfo): Boolean;
2102 var
2103 age: LongInt;
2104 size: LongInt;
2105 handle: THandle;
2106 begin
2107 result := false;
2108 if (length(fname) = 0) then exit;
2109 if not findFileCI(fname) then exit;
2110 // get age
2111 age := FileAge(fname);
2112 if (age = -1) then exit;
2113 // get size
2114 handle := FileOpen(fname, fmOpenRead or fmShareDenyNone);
2115 if (handle = THandle(-1)) then exit;
2116 size := FileSeek(handle, 0, fsFromEnd);
2117 FileClose(handle);
2118 if (size = -1) then exit;
2119 // fill info
2120 info.diskName := fname;
2121 info.size := size;
2122 info.age := age;
2123 result := true;
2124 end;
2127 (*
2128 var
2129 ss: ShortString;
2130 ls: AnsiString;
2131 i64: Int64 = -$A000000000;
2132 ui64: UInt64 = $A000000000;
2133 begin
2134 writef(conwriter, 'test int:<%s> bool:<%s:%02d:%c> bool:<%s:%02d:%c>; char:<%2s;%c;%d>!'#10, [42, true, true, true, false, false, false, 'A', 'A', 'A']);
2135 writef(conwriter, 'test float:<%s;%u;%f;%g>'#10, [666.6942, 666.6942, 666.6942, 666.6942]);
2136 ss := 'fuckit';
2137 ls := 'FUCKIT';
2138 writef(conwriter, 'test ss:<%5s;%040s>'#10, [ss, ss]);
2139 writef(conwriter, 'test ls:<%5s;%040s>'#10, [ls, ls]);
2140 writef(conwriter, 'test pointer:<%s;%x;%p>'#10, [@ss, @ss, @ss]);
2141 writef(conwriter, 'test i64:<%s;%x;%015d;%u;%X>'#10, [i64, i64, i64, i64, i64]);
2142 writef(conwriter, 'test ui64:<%s;%x;%15d;%015u;%X>'#10, [ui64, ui64, ui64, ui64, ui64]);
2143 *)
2144 end.