DEADSOFTWARE

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