-
Notifications
You must be signed in to change notification settings - Fork 58
/
StdFuncs.pas
1682 lines (1481 loc) · 38.9 KB
/
StdFuncs.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{***************************************************************}
{ FIBPlus - component library for direct access to Firebird and }
{ InterBase databases }
{ }
{ FIBPlus is based in part on the product }
{ Free IB Components, written by Gregory H. Deatz for }
{ Hoagland, Longo, Moran, Dunst & Doukas Company. }
{ mailto:[email protected] }
{ }
{ Copyright (c) 1998-2007 Devrace Ltd. }
{ Written by Serge Buzadzhy ([email protected]) }
{ }
{ ------------------------------------------------------------- }
{ FIBPlus home page: http://www.fibplus.com/ }
{ FIBPlus support : http://www.devrace.com/support/ }
{ ------------------------------------------------------------- }
{ }
{ Please see the file License.txt for full license information }
{***************************************************************}
(*
* StdFuncs -
* A file chock full of functions that should exist in Delphi, but
* dont, like "Max", "GetTempFile", "Soundex", etc...
*)
unit StdFuncs;
{$I FIBPlus.inc}
interface
uses
Classes, SysUtils,DB,FIBSafeTimer
{$IFDEF WINDOWS},Windows {$ENDIF}
{$IFDEF D6+},FMTBcd, Variants{$ENDIF};
type
EParserError = class(Exception);
TCharSet = set of AnsiChar;
TDynArray = array of variant;
PDynArray=^TDynArray;
TFIBTimer = TFIBCustomTimer;
function ConvertFromBase(sNum: String; iBase: Integer; cDigits: String): Integer;
function ConvertToBase(iNum, iBase: Integer; cDigits: String): String;
function Max(n1, n2: Integer): Integer;
function MaxD(n1, n2: Double): Double;
function Min(n1, n2: Integer): Integer;{$IFDEF D2005+} inline;{$ENDIF}
function MinD(n1, n2: Double): Double;
function Signum(Arg:Integer) :Integer; {$IFDEF D2005+} inline;{$ENDIF}
function RandomString(iLength: Integer): String;
//function RandomInteger(iLow, iHigh: Integer): Integer;
function Soundex(st: String): String;
function StripString(const st: String; const CharsToStrip: String): String;
function ClosestWeekday(const d: TDateTime): TDateTime;
function Year(d: TDateTime): Integer;
function Month(d: TDateTime): Integer;
function DayOfYear(d: TDateTime): Integer;
function DayOfMonth(d: TDateTime): Integer;
procedure WeekOfYear(d: TDateTime; var Year, Week: Integer);
function Degree10(Degree:integer):Extended;{$IFDEF D2005+} inline;{$ENDIF}
function ExtPrecision(Value:Extended) :integer;{$IFDEF D2005+} inline;{$ENDIF}
function RoundExtend(Value: Extended;Decimals:integer): Extended;
// Comp type stuff
function Int64WithScaleToStr(Value: Int64;Scale:integer;DSep:Char): string; overload;
function ExtendedToBCD(const Value:Extended;NeedScale:integer):TBCD;
//end Comp type stuff
function Int64ToBCD(Value: Int64;Scale:integer; var BCD: TBcd ): Boolean; // {$IFDEF D2005+} inline;{$ENDIF}
function BCDToExtended(BCD: TBcd; var Value: Extended): Boolean;
function BCDToCompWithScale(BCD: TBcd; var Value: Int64;var Scale:byte): Boolean;
function BCDToInt64WithScale(BCD: TBcd; var Value: Int64;var Scale:byte): Boolean;
{$IFNDEF D6+}
function BCDToStr(BCD: TBcd): String;
{$ENDIF}
function BCDToSQLStr(BCD: TBcd): String;
function CompareBCD(const BCD1,BCD2: TBcd): integer;{$IFDEF D2005+} inline;{$ENDIF}
{$IFDEF D6+}
function fFormatBcd(const Format: string; Bcd: TBcd): string;
function FormatNumericString(const Format,Source: string; OneSectionFormat:boolean=False ): string;
{$ENDIF}
function TimeStamp(const aDate,aTime:integer):TTimeStamp;
function CmpFullName(cmp:TComponent):string;
function CmpInLoadedState(Cmp:TComponent):boolean; {$IFDEF D2005+} inline;{$ENDIF}
procedure FullClearStrings(aStrings:TStrings);
function HookTimeStampToMSecs(const TimeStamp:TTimeStamp): Int64;
function HookTimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
function IBStrToTime(const Str:string):TDateTime;
function IntDateToDateTime(aDate:integer):TDateTime;
//DB rtns
function FieldOldValAsString(Field:TField;SQLFormat:boolean):string;
function BCDFieldAsSQLString(Field:TField;OldVal:boolean):variant;
function BCDFieldAsString(Field:TField;OldVal:boolean):variant;
function GetBCDFieldData(Field:TField;OldVal:boolean; var BCD:TBcd):boolean;
function GetBit(InByte:Byte; Index:byte):Boolean;{$IFDEF D2005+} inline;{$ENDIF}
function SetBit(InByte:Byte; Index:byte; value :Boolean):Byte;
function HexStr2Int(const S: String): Integer;
function HexStr2IntStr(const S: String): string;
{$IFNDEF D6+}
type
PBoolean = ^Boolean;
function CreateGUID(out Guid: TGUID): HResult;
//function IsEqualGUID(const guid1, guid2: TGUID): Boolean; stdcall; {$EXTERNALSYM IsEqualGUID}
function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PChar; SourceBytes: Cardinal): Cardinal;
function DirectoryExists(const Name: string): Boolean;
function ForceDirectories(Dir: string): Boolean;
{$ENDIF}
procedure InitFPU;
procedure StreamToVariant(Stream:TMemoryStream; var Value : Variant);
procedure StreamToVariantArray(Stream:TMemoryStream; var Value : Variant);
function VariantToStream(Value : Variant;Stream:TStream): integer; {Length of Blob}
function StringIsDateTimeDefValue(const s:string):boolean; {$IFDEF D2005+} inline;{$ENDIF}
{$IFNDEF D6+}
// Cut from system.pas Delphi 6
function Utf8Encode(const WS: WideString): String;
function Utf8Decode(const S: String): WideString;
{$ENDIF}
{$IFDEF WINDOWS}
function ConvertFromCodePage( const Source : string; FromCodePage:LongWord) : WideString;
function ConvertToCodePage(const Source : WideString; ToCodePage : LongWord) : string;
{$ENDIF}
var
TempPath: PAnsiChar;
TempPathLength: Integer;
const
E10:array [-18..18] of Double =
( 1E-18,1E-17, 1E-16, 1E-15, 1E-14, 1E-13, 1E-12, 1E-11,
1E-10, 1E-9, 1E-8, 1E-7, 1E-6, 1E-5, 1E-4, 1E-3,1E-2, 1E-1,
1,
1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,1E9, 1E10,
1E11, 1E12, 1E13, 1E14, 1E15, 1E16, 1E17, 1E18
);
IE10:array [0..18] of int64 =
(
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,1000000000,
10000000000,100000000000,1000000000000,10000000000000,100000000000000,
1000000000000000,10000000000000000,100000000000000000,1000000000000000000
);
const
AppPathTemplate='{APP_PATH}';
implementation
uses FIBConsts,StrUtil;
{$IFDEF WINDOWS}
function ConvertToCodePage(const Source : WideString;
ToCodePage : LongWord) : string;
var
L :integer;
begin
L := Length(Source);
SetLength(Result,L);
if
{$IFDEF D2007+}
WideCharToMultiByte(ToCodePage, 0, PWideChar(Source), L, PAnsiChar(AnsiString(Result)), L, nil, nil)=0
{$ELSE}
WideCharToMultiByte(ToCodePage, 0, PWideChar(Source), L, PChar(Result), L, nil, nil)=0
{$ENDIF}
then
Result:=Source
end;
function ConvertFromCodePage(const Source : string; FromCodePage:LongWord) : WideString;
var
L :integer;
begin
L := Length(Source);
SetLength(Result,L);
if
{$IFDEF D2007+}
MultiByteToWideChar(FromCodePage, 0, PAnsiChar(AnsiString(Source)), L, PWideChar(Result), L)=0
{$ELSE}
MultiByteToWideChar(FromCodePage, 0, PChar(Source), L, PWideChar(Result), L)=0
{$ENDIF}
then
Result :=Source
end;
{$ENDIF}
{$IFNDEF D6+}
// Cut from system.pas Delphi 6
function UnicodeToUtf8(Dest: PChar; MaxDestBytes: Cardinal; Source: PWideChar; SourceChars: Cardinal): Cardinal;
var
i, count: Cardinal;
c: Cardinal;
begin
Result := 0;
if Source = nil then Exit;
count := 0;
i := 0;
if Dest <> nil then
begin
while (i < SourceChars) and (count < MaxDestBytes) do
begin
c := Cardinal(Source[i]);
Inc(i);
if c <= $7F then
begin
Dest[count] := Char(c);
Inc(count);
end
else if c > $7FF then
begin
if count + 3 > MaxDestBytes then
break;
Dest[count] := Char($E0 or (c shr 12));
Dest[count+1] := Char($80 or ((c shr 6) and $3F));
Dest[count+2] := Char($80 or (c and $3F));
Inc(count,3);
end
else // $7F < Source[i] <= $7FF
begin
if count + 2 > MaxDestBytes then
break;
Dest[count] := Char($C0 or (c shr 6));
Dest[count+1] := Char($80 or (c and $3F));
Inc(count,2);
end;
end;
if count >= MaxDestBytes then count := MaxDestBytes-1;
Dest[count] := #0;
end
else
begin
while i < SourceChars do
begin
c := Integer(Source[i]);
Inc(i);
if c > $7F then
begin
if c > $7FF then
Inc(count);
Inc(count);
end;
Inc(count);
end;
end;
Result := count+1; // convert zero based index to byte count
end;
function Utf8Encode(const WS: WideString): String;
var
L: Integer;
Temp: String;
begin
Result := '';
if WS = '' then Exit;
SetLength(Temp, Length(WS) * 3); // SetLength includes space for null terminator
L := UnicodeToUtf8(PChar(Temp), Length(Temp)+1, PWideChar(WS), Length(WS));
if L > 0 then
SetLength(Temp, L-1)
else
Temp := '';
Result := Temp;
end;
function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PChar; SourceBytes: Cardinal): Cardinal;
var
i, count: Cardinal;
c: Byte;
wc: Cardinal;
begin
if Source = nil then
begin
Result := 0;
Exit;
end;
Result := Cardinal(-1);
count := 0;
i := 0;
if Dest <> nil then
begin
while (i < SourceBytes) and (count < MaxDestChars) do
begin
wc := Cardinal(Source[i]);
Inc(i);
if (wc and $80) <> 0 then
begin
wc := wc and $3F;
if i > SourceBytes then Exit; // incomplete multibyte char
if (wc and $20) <> 0 then
begin
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte or out of range char
if i > SourceBytes then Exit; // incomplete multibyte char
wc := (wc shl 6) or (c and $3F);
end;
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte
Dest[count] := WideChar((wc shl 6) or (c and $3F));
end
else
Dest[count] := WideChar(wc);
Inc(count);
end;
if count >= MaxDestChars then count := MaxDestChars-1;
Dest[count] := #0;
end
else
begin
while (i <= SourceBytes) do
begin
c := Byte(Source[i]);
Inc(i);
if (c and $80) <> 0 then
begin
if (c and $F0) = $F0 then Exit; // too many bytes for UCS2
if (c and $40) = 0 then Exit; // malformed lead byte
if i > SourceBytes then Exit; // incomplete multibyte char
if (Byte(Source[i]) and $C0) <> $80 then Exit; // malformed trail byte
Inc(i);
if i > SourceBytes then Exit; // incomplete multibyte char
if ((c and $20) <> 0) and ((Byte(Source[i]) and $C0) <> $80) then Exit; // malformed trail byte
Inc(i);
end;
Inc(count);
end;
end;
Result := count+1;
end;
function Utf8Decode(const S: String): WideString;
var
L: Integer;
Temp: WideString;
begin
Result := '';
if S = '' then Exit;
SetLength(Temp, Length(S));
L := Utf8ToUnicode(PWideChar(Temp), Length(Temp)+1, PChar(S), Length(S));
if L > 0 then
SetLength(Temp, L-1)
else
Temp := '';
Result := Temp;
end;
{$ENDIF}
procedure StreamToVariantArray(Stream:TMemoryStream; var Value : Variant);
var
i : integer;
begin
for i := 0 to Stream.Size - 1 do
PByte(LongInt(TVarData(Value).VArray^.Data)+i)^ := PByte(LongInt(Stream.Memory)+i)^ ;
end;
procedure StreamToVariant(Stream:TMemoryStream; var Value : Variant);
var
i : integer;
{$IFDEF D6+}
vt :TVarType;
{$ELSE}
vt :Integer;
{$ENDIF}
begin
VarClear(Value);
if Stream.Size > 0 then
begin
Stream.Position:=0;
vt:=varByte;
Value := VarArrayCreate([0, Stream.Size-1],vt);
for i := 0 to Stream.Size - 1 do
PByte(LongInt(TVarData(Value).VArray^.Data)+i)^ := PByte(LongInt(Stream.Memory)+i)^ ;
end;
end;
function VariantToStream(Value : Variant;Stream:TStream): integer; {Length of Stream}
var
B : TVarArrayBound;
BufSize: Integer;
begin
Result := 0;
if not VarIsArray(Value) then
Exit;
if not Assigned(Stream) then
Exit;
if TVarData(Value).VArray <> nil then
begin
B := TVarData(Value).VArray^.Bounds[0];
if B.ElementCount > 0 then
begin
BufSize:=B.ElementCount*TVarData(Value).VArray^.ElementSize;
Stream.Size:=BufSize;
Stream.Position:=0;
Stream.Write(TVarData(Value).VArray^.Data^, BufSize );
Result := Stream.Size;
end;
end;
end;
function StringIsDateTimeDefValue(const s:string):boolean;
begin
Result := False;
if Length(s) > 0 then
case s[1] of
'C': Result:=(s='CURRENT_TIME') or (s='CURRENT_TIMESTAMP') or (s='CURRENT_DATE');
'N': Result:=(s='NULL') or (s='NOW');
'T': Result:=(s='TODAY') or (s='TOMORROW');
'Y': Result:=(s='YESTERDAY');
end;
end;
{$IFNDEF D6+}
resourcestring
SCannotCreateDir = 'Unable to create directory';
{$EXTERNALSYM CoCreateGuid}
function CoCreateGuid(out guid: TGUID): HResult; stdcall; external 'ole32.dll' name 'CoCreateGuid';
function CreateGUID(out Guid: TGUID): HResult;
begin
Result := CoCreateGuid(Guid);
end;
{$ENDIF}
type THackDS=class(TDataSet);
function FieldOldValAsString(Field:TField;SQLFormat:boolean):string;
var
OldState:TDataSetState;
begin
OldState:=Field.DataSet.State;
try
THackDS(Field.DataSet).SetTempState(dsOldValue);
Result:=Field.AsString;
finally
THackDS(Field.DataSet).RestoreState(OldState);
end;
{$IFDEF D_XE3}with FormatSettings do{$ENDIF}
if SQLFormat and (DecimalSeparator<>'.') then
ReplaceStr(Result,DecimalSeparator,'.')
end;
function GetBCDFieldData(Field:TField;OldVal:boolean; var BCD:TBcd):boolean;
var
OldState:TDataSetState;
begin
OldState:=Field.DataSet.State;
with THackDS(Field.DataSet) do
try
if OldVal and (OldState<>dsOldValue) then
SetTempState(dsOldValue);
Result:=GetFieldData(Field,@Bcd);
finally
if OldVal and (OldState<>dsOldValue) then
RestoreState(OldState);
end;
end;
function InternalBCDFieldAsString(Field:TField;OldVal,SQLFormat:boolean):variant;
var
Bcd :TBcd;
begin
if GetBCDFieldData(Field,OldVal,Bcd) then
begin
if SQLFormat then
Result:=BCDToSQLStr(BCD)
else
Result:=BCDToStr(BCD);
end
else
begin
Result:=UnAssigned;
end;
end;
function BCDFieldAsSQLString(Field:TField;OldVal:boolean):variant;
begin
Result:= InternalBCDFieldAsString(Field,OldVal,true)
end;
function BCDFieldAsString(Field:TField;OldVal:boolean):variant;
begin
Result:= InternalBCDFieldAsString(Field,OldVal,false)
end;
//
function RoundExtend(Value: Extended;Decimals:integer): Extended;
begin
Result:=
System.Int(Value)+Round(Frac(Value)*E10[Decimals])/E10[Decimals];
end;
function TimeStamp(const aDate,aTime:integer):TTimeStamp;
begin
with Result do
begin
Time:=aTime;
Date:=aDate;
end;
end;
function HookTimeStampToMSecs(const TimeStamp:TTimeStamp): Int64;
var t:TTimeStamp;
c:Comp;
begin
if TimeStamp.Date=0 then
begin
t.Date:=1;
t.Time:=TimeStamp.Time;
c:=TimeStampToMSecs(t)-86400000;
end
else
c:=TimeStampToMSecs(TimeStamp);
Result:=PInt64(@c)^
end;
function HookTimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
var
t:TTimeStamp;
begin
if TimeStamp.Date=0 then
begin
t.Date:=1;
t.Time:=TimeStamp.Time;
Result:=TimeStampToDateTime(t)-1;
end
else
Result:=TimeStampToDateTime(TimeStamp)
end;
function IBStrToTime(const Str:string):TDateTime;
var
t:TTimeStamp;
begin
Result:=StrToTime(Str);
t:=DateTimeToTimeStamp(Result);
t.Date:=0;
Result:=HookTimeStampToDateTime(t);
end;
function IntDateToDateTime(aDate:integer):TDateTime;
var
t:TTimeStamp;
begin
t.Date:=aDate;
t.Time:=0;
Result:=HookTimeStampToDateTime(t);
end;
function CmpFullName(cmp:TComponent):string;
begin
result:='';
while cmp<>nil do
with cmp do
begin
if Name<>'' then
if Result='' then
result:=Name
else
result:=Name+'.'+Result;
cmp:=Owner;
end;
end;
function CmpInLoadedState(Cmp:TComponent):boolean;
var tmpCmp :TComponent;
begin
tmpCmp :=Cmp;
while ((tmpCmp<>nil) and not (csLoading in tmpCmp.ComponentState)) do
begin
tmpCmp:=tmpCmp.Owner;
end;
Result:=tmpCmp<>nil;
end;
procedure FullClearStrings(aStrings:TStrings);
var
j: Integer;
begin
with aStrings do
for j := 0 to Pred(aStrings.Count) do
begin
if Objects[j]<>nil then Objects[j].Free;
end;
aStrings.Clear;
end;
function Degree10(Degree:integer):Extended;
begin
Result:=E10[Degree]
end;
function ExtPrecision(Value:Extended) :integer;
var
L, H, I: Integer;
c:comp;
a:comp;
begin
L := 0;
H := 18;
a := Abs(Int(Value));
while L <= H do
begin
I := (L + H) shr 1;
C := E10[I]-a;
if C < 0 then
L := I + 1
else
begin
H := I - 1;
if C = 0 then
begin
L := I+1;
Break
end;
end;
end;
Result:=L
end;
// Comp type stuff
function ExtendedToBCD(const Value:Extended;NeedScale:integer):TBCD;
var
// Pr:Integer;
c:Comp;
begin
// Pr:=ExtPrecision(Value);
c:=Value*E10[NeedScale];
Int64ToBCD(PInt64(@C)^,NeedScale,Result);
end;
procedure PutTwoBcdDigits(const Nibble1, Nibble2: Byte; var Bcd: TBcd; Digit: Integer);
var
b: Byte;
begin
b := Nibble1 SHL 4;
b := b OR (Nibble2 AND 15);
Bcd.Fraction[Digit div 2] := b;
end;
{$IFDEF D_XE2}
//CUT FROM Delphi XE
function CurrToBCD(const Curr: Currency; var BCD: TBcd; Precision: Integer = 32;
Decimals: Integer = 4): Boolean;
var
Temp: Currency;
BcdIndex, StrIndex, StartPos, Digits: Integer;
B1, B2, DotPos: Byte;
BcdStr: string;
Dot: Char;
function GetNextByte(): Byte;
begin
Result := 0;
if BcdIndex < StartPos then
Exit;
if (StrIndex <= Digits) and (BcdStr[StrIndex] = Dot) then
Inc(StrIndex);
if StrIndex <= Digits then
begin
Result := Byte(BcdStr[StrIndex]) - 48;
Inc(StrIndex);
end;
end;
begin
Dot := FormatSettings.DecimalSeparator;
Bcd.Precision := Precision;
Bcd.SignSpecialPlaces := Decimals;
for BcdIndex := 0 to 31 do
Bcd.Fraction[BcdIndex] := 0;
if Curr = 0 then
begin
Result := True;
Exit;
end;
if Curr < 0 then
Temp := -Curr
else
Temp := Curr;
BcdStr := CurrToStr(Temp);
Digits := Length(BcdStr);
DotPos := Pos(Dot, BcdStr);
if DotPos > 0 then
StartPos := Precision - ((DotPos - 1) + Decimals)
else
StartPos := Precision - (Digits + Decimals);
StrIndex := 1;
BcdIndex := 0;
while BcdIndex < Precision do
begin
B1 := GetNextByte();
Inc(BcdIndex);
B2 := GetNextByte();
PutTwoBcdDigits(B1, B2, Bcd, BcdIndex-1);
Inc(BcdIndex);
end;
if Curr < 0 then
Bcd.SignSpecialPlaces := (Bcd.SignSpecialPlaces and 63) or (1 shl 7);
Result := True;
end;
function GetBcdDigit(const Bcd: TBcd; Digit: Integer): Byte;
begin
if Digit mod 2 = 0 then
Result := Byte((Bcd.Fraction[Digit div 2]) SHR 4)
else
Result := Byte(Byte((Bcd.Fraction[Digit div 2]) AND 15));
end;
const
DValue: array[-10..20] of Currency = (0, 0, 0, 0, 0, 0, 0,
0.0001, 0.001, 0.01, 0.1, 1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
0, 0, 0, 0, 0);
{ Currency Value of a Byte for a specific digit column }
function PutCurrencyDigit(Value: Byte; Digit: Integer): Currency;
begin
Result := DValue[Digit] * Value;
end;
function BCDToCurr(const BCD: TBcd; var Curr: Currency): Boolean;
var
Scale, I: Integer;
Negative: Boolean;
b: Byte;
begin
Curr := 0;
Negative := (Bcd.SignSpecialPlaces and (1 shl 7)) <> 0;
Scale := (Bcd.SignSpecialPlaces and 63);
for I := 0 to Bcd.Precision -1 do
begin
b := GetBcdDigit(Bcd, I);
if b <> 0 then
Curr := Curr + PutCurrencyDigit(b, Bcd.Precision - (Scale + I));
end;
if Scale > 4 then
begin { 0.12345 = 0.1234, but 0.123450000001 is rounded up to 0.1235 }
b := GetBcdDigit(Bcd, 4 + (Bcd.Precision - Scale));
if b >= 5 then
if b > 5 then
Curr := Curr + 0.0001
else
for I := 5 + (Bcd.Precision - Scale) to Bcd.Precision -1 do
if GetBcdDigit(Bcd, I) <> 0 then
begin
Curr := Curr + 0.0001;
break;
end;
end;
if Negative then
Curr := -Curr;
Result := True;
end;
{$ENDIF}
function Int64ToBCD(Value: Int64;Scale:integer; var BCD: TBcd ): Boolean;
var
c:Currency;
begin
c:=Value/1E4;
Result:= CurrToBCD(c,BCD);
with BCD do
begin
if Value<0 then
SignSpecialPlaces:=128
else
SignSpecialPlaces:=0;
SignSpecialPlaces :=Scale+SignSpecialPlaces;
end;
end;
function BCDToCompWithScale(BCD: TBcd; var Value: Int64;var Scale:byte): Boolean;
begin
Result:=BCDToInt64WithScale(BCD, Value,Scale)
end;
function BCDToInt64WithScale(BCD: TBcd; var Value: Int64;var Scale:byte): Boolean;
var Sign:integer;
c:Currency;
begin
with BCD do
begin
if Precision=0 then
begin
Result:=true;
Value:=0;
Exit;
end;
if SignSpecialPlaces>=128 then
begin
Sign:=-1;
Scale:=SignSpecialPlaces-128;
end
else
begin
Sign :=1 ;
Scale:=SignSpecialPlaces;
end;
if Scale>=64 then
begin
// null
Result:=true;
Value:=0;
Exit;
end;
SignSpecialPlaces:=4;
end;
Result:=BCDToCurr(BCD,C);
if Result then
Value :=Sign*PInt64(@C)^;
end;
function BCDToSQLStr(BCD: TBcd): String;
var
pd:integer;
begin
Result:=BcdToStr(BCD);
{$IFDEF D_XE3}with FormatSettings do{$ENDIF}
if DecimalSeparator<>'.' then
begin
pd:=Pos(DecimalSeparator,Result);
if pd>0 then
Result[pd]:='.';
end;
end;
const
ZeroStr='000000000000000000';
{$IFDEF D6+}
{$IFNDEF D2005+}
function RoundAt(const Value: string; Position: SmallInt): string;
Procedure RoundChar(const PrevChar: SmallInt; var Carry: Boolean);
begin
if Result[PrevChar] in ['0' .. '9'] then
begin
if Result[PrevChar] = '9' then
begin
Result[PrevChar] := '0';
Carry := True;
end else
begin
Result[PrevChar] := Char(Byte(Result[PrevChar]) + 1);
Carry := False;
end;
end;
end;
var
C, Dot: Char;
PrevChar, I, DecPos, DecDigits: SmallInt;
Carry: Boolean;
Neg: string;
begin
Dot := DecimalSeparator;
if Value[1] = '-' then
begin
Result := FastCopy(Value, 2, MaxInt);
Neg := '-';
end else
begin
Result := Value;
Neg := '';
end;
DecPos := Pos(Dot, Result);
if DecPos > 0 then
DecDigits := Length(Result) - DecPos
else
DecDigits := 0;
if (DecPos = 0) or (DecDigits <= Position) then
{ nothing to round }
begin
Result := Value;
Exit;
end;
if Result[DecPos + Position + 1] < '5' then
begin
{ no possible rounding required }
if Position = 0 then
Result := Neg + Copy(Result, 1, DecPos + Position -1)
else
Result := Neg + Copy(Result, 1, DecPos + Position);
end else
begin
Carry := False;
PrevChar := 1;
for I := DecPos + DecDigits downto (DecPos + 1 + Position) do
begin
C := Result[I];
PrevChar := I-1;
if Result[PrevChar] = Dot then
begin
Dec(PrevChar);
Dec(Position);
end;
if (Byte(C) >= 53) or Carry then { if '5' or greater }
RoundChar(PrevChar, Carry);
end;
while Carry do
begin
if PrevChar >= DecPos then
Dec(Position);
Dec(PrevChar);
if PrevChar = 0 then
break;
if Result[PrevChar] <> Dot then
RoundChar(PrevChar, Carry);
end;
if Carry then
Result := Neg + '1' + Copy(Result, 1, DecPos + Position)
else
Result := Neg + Copy(Result, 1, DecPos + Position);
end;
end;
{$ENDIF}