DEADSOFTWARE

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