This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
decimal.cpp
2588 lines (2241 loc) · 72 KB
/
decimal.cpp
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: decimal.cpp
//
//
#include "common.h"
#include "object.h"
#include "excep.h"
#include "frames.h"
#include "vars.hpp"
#include "decimal.h"
#include "string.h"
LONG g_OLEAUT32_Loaded = 0;
unsigned int DecDivMod1E9(DECIMAL* value);
void DecMul10(DECIMAL* value);
void DecAddInt32(DECIMAL* value, unsigned int i);
#define COPYDEC(dest, src) {DECIMAL_SIGNSCALE(dest) = DECIMAL_SIGNSCALE(src); DECIMAL_HI32(dest) = DECIMAL_HI32(src); DECIMAL_LO64_SET(dest, DECIMAL_LO64_GET(src));}
FCIMPL2_IV(void, COMDecimal::InitSingle, DECIMAL *_this, float value)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
_ASSERTE(_this != NULL);
HRESULT hr = VarDecFromR4(value, _this);
if (FAILED(hr))
FCThrowResVoid(kOverflowException, W("Overflow_Decimal"));
_this->wReserved = 0;
}
FCIMPLEND
FCIMPL2_IV(void, COMDecimal::InitDouble, DECIMAL *_this, double value)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
_ASSERTE(_this != NULL);
HRESULT hr = VarDecFromR8(value, _this);
if (FAILED(hr))
FCThrowResVoid(kOverflowException, W("Overflow_Decimal"));
_this->wReserved = 0;
}
FCIMPLEND
#ifdef _MSC_VER
// C4702: unreachable code on IA64 retail
#pragma warning(push)
#pragma warning(disable:4702)
#endif
FCIMPL2(INT32, COMDecimal::DoCompare, DECIMAL * d1, DECIMAL * d2)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
HRESULT hr = VarDecCmp(d1, d2);
if (FAILED(hr) || (int)hr == VARCMP_NULL) {
_ASSERTE(!"VarDecCmp failed in Decimal::Compare");
FCThrowRes(kOverflowException, W("Overflow_Decimal"));
}
INT32 retVal = ((int)hr) - 1;
FC_GC_POLL_RET ();
return retVal;
}
FCIMPLEND
#ifdef _MSC_VER
#pragma warning(pop)
#endif
FCIMPL1(void, COMDecimal::DoFloor, DECIMAL * d)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
DECIMAL decRes;
HRESULT hr;
hr = VarDecInt(d, &decRes);
// VarDecInt can't overflow, as of source for OleAut32 build 4265.
// It only returns NOERROR
_ASSERTE(hr==NOERROR);
// copy decRes into d
COPYDEC(*d, decRes)
d->wReserved = 0;
FC_GC_POLL();
}
FCIMPLEND
FCIMPL1(INT32, COMDecimal::GetHashCode, DECIMAL *d)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
_ASSERTE(d != NULL);
double dbl;
VarR8FromDec(d, &dbl);
if (dbl == 0.0) {
// Ensure 0 and -0 have the same hash code
return 0;
}
// conversion to double is lossy and produces rounding errors so we mask off the lowest 4 bits
//
// For example these two numerically equal decimals with different internal representations produce
// slightly different results when converted to double:
//
// decimal a = new decimal(new int[] { 0x76969696, 0x2fdd49fa, 0x409783ff, 0x00160000 });
// => (decimal)1999021.176470588235294117647000000000 => (double)1999021.176470588
// decimal b = new decimal(new int[] { 0x3f0f0f0f, 0x1e62edcc, 0x06758d33, 0x00150000 });
// => (decimal)1999021.176470588235294117647000000000 => (double)1999021.1764705882
//
return ((((int *)&dbl)[0]) & 0xFFFFFFF0) ^ ((int *)&dbl)[1];
}
FCIMPLEND
FCIMPL3(void, COMDecimal::DoMultiply, DECIMAL * d1, DECIMAL * d2, CLR_BOOL * overflowed)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
DECIMAL decRes;
// GC is only triggered for throwing, no need to protect result
HRESULT hr = VarDecMul(d1, d2, &decRes);
if (FAILED(hr)) {
*overflowed = true;
FC_GC_POLL();
return;
}
// copy decRes into d1
COPYDEC(*d1, decRes)
d1->wReserved = 0;
*overflowed = false;
FC_GC_POLL();
}
FCIMPLEND
FCIMPL2(void, COMDecimal::DoMultiplyThrow, DECIMAL * d1, DECIMAL * d2)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
DECIMAL decRes;
// GC is only triggered for throwing, no need to protect result
HRESULT hr = VarDecMul(d1, d2, &decRes);
if (FAILED(hr)) {
FCThrowResVoid(kOverflowException, W("Overflow_Decimal"));
}
// copy decRes into d1
COPYDEC(*d1, decRes)
d1->wReserved = 0;
FC_GC_POLL();
}
FCIMPLEND
FCIMPL2(void, COMDecimal::DoRound, DECIMAL * d, INT32 decimals)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
DECIMAL decRes;
// GC is only triggered for throwing, no need to protect result
if (decimals < 0 || decimals > 28)
FCThrowArgumentOutOfRangeVoid(W("decimals"), W("ArgumentOutOfRange_DecimalRound"));
HRESULT hr = VarDecRound(d, decimals, &decRes);
if (FAILED(hr))
FCThrowResVoid(kOverflowException, W("Overflow_Decimal"));
// copy decRes into d
COPYDEC(*d, decRes)
d->wReserved = 0;
FC_GC_POLL();
}
FCIMPLEND
FCIMPL2_IV(void, COMDecimal::DoToCurrency, CY * result, DECIMAL d)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
// GC is only triggered for throwing, no need to protect result
HRESULT hr = VarCyFromDec(&d, result);
if (FAILED(hr)) {
_ASSERTE(hr != E_INVALIDARG);
FCThrowResVoid(kOverflowException, W("Overflow_Currency"));
}
}
FCIMPLEND
FCIMPL1(double, COMDecimal::ToDouble, FC_DECIMAL d)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
double result = 0.0;
// Note: this can fail if the input is an invalid decimal, but for compatibility we should return 0
VarR8FromDec(&d, &result);
return result;
}
FCIMPLEND
FCIMPL1(INT32, COMDecimal::ToInt32, FC_DECIMAL d)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
DECIMAL result;
HRESULT hr = VarDecRound(&d, 0, &result);
if (FAILED(hr))
FCThrowRes(kOverflowException, W("Overflow_Decimal"));
result.wReserved = 0;
if( DECIMAL_SCALE(result) != 0) {
d = result;
VarDecFix(&d, &result);
}
if (DECIMAL_HI32(result) == 0 && DECIMAL_MID32(result) == 0) {
INT32 i = DECIMAL_LO32(result);
if ((INT16)DECIMAL_SIGNSCALE(result) >= 0) {
if (i >= 0) return i;
}
else {
// Int32.MinValue is represented as sign being negative
// and Lo32 being 0x80000000 (-ve number). Return that as is without
// reversing the sign of the number.
if(i == 0x80000000) return i;
i = -i;
if (i <= 0) return i;
}
}
FCThrowRes(kOverflowException, W("Overflow_Int32"));
}
FCIMPLEND
FCIMPL1(float, COMDecimal::ToSingle, FC_DECIMAL d)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
float result = 0.0f;
// Note: this can fail if the input is an invalid decimal, but for compatibility we should return 0
VarR4FromDec(&d, &result);
return result;
}
FCIMPLEND
FCIMPL1(void, COMDecimal::DoTruncate, DECIMAL * d)
{
FCALL_CONTRACT;
ENSURE_OLEAUT32_LOADED();
DECIMAL decRes;
VarDecFix(d, &decRes);
// copy decRes into d
COPYDEC(*d, decRes)
d->wReserved = 0;
FC_GC_POLL();
}
FCIMPLEND
void COMDecimal::DecimalToNumber(DECIMAL* value, NUMBER* number)
{
WRAPPER_NO_CONTRACT
_ASSERTE(number != NULL);
_ASSERTE(value != NULL);
wchar_t buffer[DECIMAL_PRECISION+1];
DECIMAL d = *value;
number->precision = DECIMAL_PRECISION;
number->sign = DECIMAL_SIGN(d)? 1: 0;
wchar_t* p = buffer + DECIMAL_PRECISION;
while (DECIMAL_MID32(d) | DECIMAL_HI32(d)) {
p = COMNumber::Int32ToDecChars(p, DecDivMod1E9(&d), 9);
_ASSERTE(p != NULL);
}
p = COMNumber::Int32ToDecChars(p, DECIMAL_LO32(d), 0);
_ASSERTE(p != NULL);
int i = (int) (buffer + DECIMAL_PRECISION - p);
number->scale = i - DECIMAL_SCALE(d);
wchar_t* dst = number->digits;
_ASSERTE(dst != NULL);
while (--i >= 0) *dst++ = *p++;
*dst = 0;
}
int COMDecimal::NumberToDecimal(NUMBER* number, DECIMAL* value)
{
WRAPPER_NO_CONTRACT
_ASSERTE(number != NULL);
_ASSERTE(value != NULL);
DECIMAL d;
d.wReserved = 0;
DECIMAL_SIGNSCALE(d) = 0;
DECIMAL_HI32(d) = 0;
DECIMAL_LO32(d) = 0;
DECIMAL_MID32(d) = 0;
wchar_t* p = number->digits;
_ASSERT(p != NULL);
int e = number->scale;
if (!*p) {
// To avoid risking an app-compat issue with pre 4.5 (where some app was illegally using Reflection to examine the internal scale bits), we'll only force
// the scale to 0 if the scale was previously positive
if (e > 0) {
e = 0;
}
} else {
if (e > DECIMAL_PRECISION) return 0;
while ((e > 0 || (*p && e > -28)) &&
(DECIMAL_HI32(d) < 0x19999999 || (DECIMAL_HI32(d) == 0x19999999 &&
(DECIMAL_MID32(d) < 0x99999999 || (DECIMAL_MID32(d) == 0x99999999 &&
(DECIMAL_LO32(d) < 0x99999999 || (DECIMAL_LO32(d) == 0x99999999 && *p <= '5'))))))) {
DecMul10(&d);
if (*p) DecAddInt32(&d, *p++ - '0');
e--;
}
if (*p++ >= '5') {
bool round = true;
if (*(p-1) == '5' && *(p-2) % 2 == 0) { // Check if previous digit is even, only if the when we are unsure whether hows to do Banker's rounding
// For digits > 5 we will be roundinp up anyway.
int count = 20; // Look at the next 20 digits to check to round
while (*p == '0' && count != 0) {
p++;
count--;
}
if (*p == '\0' || count == 0)
round = false;// Do nothing
}
if (round) {
DecAddInt32(&d, 1);
if ((DECIMAL_HI32(d) | DECIMAL_MID32(d) | DECIMAL_LO32(d)) == 0) {
DECIMAL_HI32(d) = 0x19999999;
DECIMAL_MID32(d) = 0x99999999;
DECIMAL_LO32(d) = 0x9999999A;
e++;
}
}
}
}
if (e > 0) return 0;
if (e <= -DECIMAL_PRECISION)
{
// Parsing a large scale zero can give you more precision than fits in the decimal.
// This should only happen for actual zeros or very small numbers that round to zero.
DECIMAL_SIGNSCALE(d) = 0;
DECIMAL_HI32(d) = 0;
DECIMAL_LO32(d) = 0;
DECIMAL_MID32(d) = 0;
DECIMAL_SCALE(d) = (DECIMAL_PRECISION - 1);
}
else
{
DECIMAL_SCALE(d) = static_cast<BYTE>(-e);
}
DECIMAL_SIGN(d) = number->sign? DECIMAL_NEG: 0;
*value = d;
return 1;
}
#if defined(_TARGET_X86_)
#pragma warning(disable:4035)
unsigned int DecDivMod1E9(DECIMAL* value)
{
LIMITED_METHOD_CONTRACT
_asm {
mov ebx,value
mov ecx,1000000000
xor edx,edx
mov eax,[ebx+4]
div ecx
mov [ebx+4],eax
mov eax,[ebx+12]
div ecx
mov [ebx+12],eax
mov eax,[ebx+8]
div ecx
mov [ebx+8],eax
mov eax,edx
}
}
void DecMul10(DECIMAL* value)
{
LIMITED_METHOD_CONTRACT
_asm {
mov ebx,value
mov eax,[ebx+8]
mov edx,[ebx+12]
mov ecx,[ebx+4]
shl eax,1
rcl edx,1
rcl ecx,1
shl eax,1
rcl edx,1
rcl ecx,1
add eax,[ebx+8]
adc edx,[ebx+12]
adc ecx,[ebx+4]
shl eax,1
rcl edx,1
rcl ecx,1
mov [ebx+8],eax
mov [ebx+12],edx
mov [ebx+4],ecx
}
}
void DecAddInt32(DECIMAL* value, unsigned int i)
{
LIMITED_METHOD_CONTRACT
_asm {
mov edx,value
mov eax,i
add dword ptr [edx+8],eax
adc dword ptr [edx+12],0
adc dword ptr [edx+4],0
}
}
#pragma warning(default:4035)
#else // !(defined(_TARGET_X86_)
unsigned int D32DivMod1E9(unsigned int hi32, ULONG* lo32)
{
LIMITED_METHOD_CONTRACT
_ASSERTE(lo32 != NULL);
unsigned __int64 n = (unsigned __int64)hi32 << 32 | *lo32;
*lo32 = (unsigned int)(n / 1000000000);
return (unsigned int)(n % 1000000000);
}
unsigned int DecDivMod1E9(DECIMAL* value)
{
WRAPPER_NO_CONTRACT
_ASSERTE(value != NULL);
return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0,
&DECIMAL_HI32(*value)), &DECIMAL_MID32(*value)), &DECIMAL_LO32(*value));
}
void DecShiftLeft(DECIMAL* value)
{
LIMITED_METHOD_CONTRACT
_ASSERTE(value != NULL);
unsigned int c0 = DECIMAL_LO32(*value) & 0x80000000? 1: 0;
unsigned int c1 = DECIMAL_MID32(*value) & 0x80000000? 1: 0;
DECIMAL_LO32(*value) <<= 1;
DECIMAL_MID32(*value) = DECIMAL_MID32(*value) << 1 | c0;
DECIMAL_HI32(*value) = DECIMAL_HI32(*value) << 1 | c1;
}
int D32AddCarry(ULONG* value, unsigned int i)
{
LIMITED_METHOD_CONTRACT
_ASSERTE(value != NULL);
unsigned int v = *value;
unsigned int sum = v + i;
*value = sum;
return sum < v || sum < i? 1: 0;
}
void DecAdd(DECIMAL* value, DECIMAL* d)
{
WRAPPER_NO_CONTRACT
_ASSERTE(value != NULL && d != NULL);
if (D32AddCarry(&DECIMAL_LO32(*value), DECIMAL_LO32(*d))) {
if (D32AddCarry(&DECIMAL_MID32(*value), 1)) {
D32AddCarry(&DECIMAL_HI32(*value), 1);
}
}
if (D32AddCarry(&DECIMAL_MID32(*value), DECIMAL_MID32(*d))) {
D32AddCarry(&DECIMAL_HI32(*value), 1);
}
D32AddCarry(&DECIMAL_HI32(*value), DECIMAL_HI32(*d));
}
void DecMul10(DECIMAL* value)
{
WRAPPER_NO_CONTRACT
_ASSERTE(value != NULL);
DECIMAL d = *value;
DecShiftLeft(value);
DecShiftLeft(value);
DecAdd(value, &d);
DecShiftLeft(value);
}
void DecAddInt32(DECIMAL* value, unsigned int i)
{
WRAPPER_NO_CONTRACT
_ASSERTE(value != NULL);
if (D32AddCarry(&DECIMAL_LO32(*value), i)) {
if (D32AddCarry(&DECIMAL_MID32(*value), 1)) {
D32AddCarry(&DECIMAL_HI32(*value), 1);
}
}
}
#endif
/***
*
* Decimal Code ported from OleAut32
*
***********************************************************************/
// This OleAut code is only used on 64-bit and rotor platforms. It is desiriable to continue
// to call the OleAut routines in X86 because of the performance of the hand-tuned assembly
// code and because there are currently no inconsistencies in behavior accross platforms.
#ifndef UInt32x32To64
#define UInt32x32To64(a, b) ((DWORDLONG)((DWORD)(a)) * (DWORDLONG)((DWORD)(b)))
#endif
typedef union {
DWORDLONG int64;
struct {
#if BIGENDIAN
ULONG Hi;
ULONG Lo;
#else
ULONG Lo;
ULONG Hi;
#endif
} u;
} SPLIT64;
#define OVFL_MAX_1_HI 429496729
#define DEC_SCALE_MAX 28
#define POWER10_MAX 9
#define OVFL_MAX_9_HI 4u
#define OVFL_MAX_9_MID 1266874889u
#define OVFL_MAX_9_LO 3047500985u
#define OVFL_MAX_5_HI 42949
const ULONG rgulPower10[POWER10_MAX+1] = {1, 10, 100, 1000, 10000, 100000, 1000000,
10000000, 100000000, 1000000000};
struct DECOVFL
{
ULONG Hi;
ULONG Mid;
ULONG Lo;
};
const DECOVFL PowerOvfl[] = {
// This is a table of the largest values that can be in the upper two
// ULONGs of a 96-bit number that will not overflow when multiplied
// by a given power. For the upper word, this is a table of
// 2^32 / 10^n for 1 <= n <= 9. For the lower word, this is the
// remaining fraction part * 2^32. 2^32 = 4294967296.
//
{ 429496729u, 2576980377u, 2576980377u }, // 10^1 remainder 0.6
{ 42949672u, 4123168604u, 687194767u }, // 10^2 remainder 0.16
{ 4294967u, 1271310319u, 2645699854u }, // 10^3 remainder 0.616
{ 429496u, 3133608139u, 694066715u }, // 10^4 remainder 0.1616
{ 42949u, 2890341191u, 2216890319u }, // 10^5 remainder 0.51616
{ 4294u, 4154504685u, 2369172679u }, // 10^6 remainder 0.551616
{ 429u, 2133437386u, 4102387834u }, // 10^7 remainder 0.9551616
{ 42u, 4078814305u, 410238783u }, // 10^8 remainder 0.09991616
{ 4u, 1266874889u, 3047500985u }, // 10^9 remainder 0.709551616
};
/***
* IncreaseScale
*
* Entry:
* rgulNum - Pointer to 96-bit number as array of ULONGs, least-sig first
* ulPwr - Scale factor to multiply by
*
* Purpose:
* Multiply the two numbers. The low 96 bits of the result overwrite
* the input. The last 32 bits of the product are the return value.
*
* Exit:
* Returns highest 32 bits of product.
*
* Exceptions:
* None.
*
***********************************************************************/
ULONG IncreaseScale(ULONG *rgulNum, ULONG ulPwr)
{
LIMITED_METHOD_CONTRACT;
SPLIT64 sdlTmp;
sdlTmp.int64 = UInt32x32To64(rgulNum[0], ulPwr);
rgulNum[0] = sdlTmp.u.Lo;
sdlTmp.int64 = UInt32x32To64(rgulNum[1], ulPwr) + sdlTmp.u.Hi;
rgulNum[1] = sdlTmp.u.Lo;
sdlTmp.int64 = UInt32x32To64(rgulNum[2], ulPwr) + sdlTmp.u.Hi;
rgulNum[2] = sdlTmp.u.Lo;
return sdlTmp.u.Hi;
}
/***
* SearchScale
*
* Entry:
* ulResHi - Top ULONG of quotient
* ulResMid - Middle ULONG of quotient
* ulResLo - Bottom ULONG of quotient
* iScale - Scale factor of quotient, range -DEC_SCALE_MAX to DEC_SCALE_MAX
*
* Purpose:
* Determine the max power of 10, <= 9, that the quotient can be scaled
* up by and still fit in 96 bits.
*
* Exit:
* Returns power of 10 to scale by, -1 if overflow error.
*
***********************************************************************/
int SearchScale(ULONG ulResHi, ULONG ulResMid, ULONG ulResLo, int iScale)
{
WRAPPER_NO_CONTRACT;
int iCurScale;
// Quick check to stop us from trying to scale any more.
//
if (ulResHi > OVFL_MAX_1_HI || iScale >= DEC_SCALE_MAX) {
iCurScale = 0;
goto HaveScale;
}
if (iScale > DEC_SCALE_MAX - 9) {
// We can't scale by 10^9 without exceeding the max scale factor.
// See if we can scale to the max. If not, we'll fall into
// standard search for scale factor.
//
iCurScale = DEC_SCALE_MAX - iScale;
if (ulResHi < PowerOvfl[iCurScale - 1].Hi)
goto HaveScale;
if (ulResHi == PowerOvfl[iCurScale - 1].Hi) {
UpperEq:
if (ulResMid > PowerOvfl[iCurScale - 1].Mid ||
(ulResMid == PowerOvfl[iCurScale - 1].Mid && ulResLo > PowerOvfl[iCurScale - 1].Lo)) {
iCurScale--;
}
goto HaveScale;
}
}
else if (ulResHi < OVFL_MAX_9_HI || (ulResHi == OVFL_MAX_9_HI &&
ulResMid < OVFL_MAX_9_MID) || (ulResHi == OVFL_MAX_9_HI && ulResMid == OVFL_MAX_9_MID && ulResLo <= OVFL_MAX_9_LO))
return 9;
// Search for a power to scale by < 9. Do a binary search
// on PowerOvfl[].
//
iCurScale = 5;
if (ulResHi < OVFL_MAX_5_HI)
iCurScale = 7;
else if (ulResHi > OVFL_MAX_5_HI)
iCurScale = 3;
else
goto UpperEq;
// iCurScale is 3 or 7.
//
if (ulResHi < PowerOvfl[iCurScale - 1].Hi)
iCurScale++;
else if (ulResHi > PowerOvfl[iCurScale - 1].Hi)
iCurScale--;
else
goto UpperEq;
// iCurScale is 2, 4, 6, or 8.
//
// In all cases, we already found we could not use the power one larger.
// So if we can use this power, it is the biggest, and we're done. If
// we can't use this power, the one below it is correct for all cases
// unless it's 10^1 -- we might have to go to 10^0 (no scaling).
//
if (ulResHi > PowerOvfl[iCurScale - 1].Hi)
iCurScale--;
if (ulResHi == PowerOvfl[iCurScale - 1].Hi)
goto UpperEq;
HaveScale:
// iCurScale = largest power of 10 we can scale by without overflow,
// iCurScale < 9. See if this is enough to make scale factor
// positive if it isn't already.
//
if (iCurScale + iScale < 0)
iCurScale = -1;
return iCurScale;
}
//***********************************************************************
//
// Arithmetic Inlines
//
#define Div64by32(num, den) ((ULONG)((DWORDLONG)(num) / (ULONG)(den)))
#define Mod64by32(num, den) ((ULONG)((DWORDLONG)(num) % (ULONG)(den)))
inline DWORDLONG DivMod64by32(DWORDLONG num, ULONG den)
{
WRAPPER_NO_CONTRACT;
SPLIT64 sdl;
sdl.u.Lo = Div64by32(num, den);
sdl.u.Hi = Mod64by32(num, den);
return sdl.int64;
}
/***
* Div128By96
*
* Entry:
* rgulNum - Pointer to 128-bit dividend as array of ULONGs, least-sig first
* rgulDen - Pointer to 96-bit divisor.
*
* Purpose:
* Do partial divide, yielding 32-bit result and 96-bit remainder.
* Top divisor ULONG must be larger than top dividend ULONG. This is
* assured in the initial call because the divisor is normalized
* and the dividend can't be. In subsequent calls, the remainder
* is multiplied by 10^9 (max), so it can be no more than 1/4 of
* the divisor which is effectively multiplied by 2^32 (4 * 10^9).
*
* Exit:
* Remainder overwrites lower 96-bits of dividend.
* Returns quotient.
*
* Exceptions:
* None.
*
***********************************************************************/
ULONG Div128By96(ULONG *rgulNum, ULONG *rgulDen)
{
LIMITED_METHOD_CONTRACT;
SPLIT64 sdlQuo;
SPLIT64 sdlNum;
SPLIT64 sdlProd1;
SPLIT64 sdlProd2;
sdlNum.u.Lo = rgulNum[0];
sdlNum.u.Hi = rgulNum[1];
if (rgulNum[3] == 0 && rgulNum[2] < rgulDen[2])
// Result is zero. Entire dividend is remainder.
//
return 0;
// DivMod64by32 returns quotient in Lo, remainder in Hi.
//
sdlQuo.u.Lo = rgulNum[2];
sdlQuo.u.Hi = rgulNum[3];
sdlQuo.int64 = DivMod64by32(sdlQuo.int64, rgulDen[2]);
// Compute full remainder, rem = dividend - (quo * divisor).
//
sdlProd1.int64 = UInt32x32To64(sdlQuo.u.Lo, rgulDen[0]); // quo * lo divisor
sdlProd2.int64 = UInt32x32To64(sdlQuo.u.Lo, rgulDen[1]); // quo * mid divisor
sdlProd2.int64 += sdlProd1.u.Hi;
sdlProd1.u.Hi = sdlProd2.u.Lo;
sdlNum.int64 -= sdlProd1.int64;
rgulNum[2] = sdlQuo.u.Hi - sdlProd2.u.Hi; // sdlQuo.Hi is remainder
// Propagate carries
//
if (sdlNum.int64 > ~sdlProd1.int64) {
rgulNum[2]--;
if (rgulNum[2] >= ~sdlProd2.u.Hi)
goto NegRem;
}
else if (rgulNum[2] > ~sdlProd2.u.Hi) {
NegRem:
// Remainder went negative. Add divisor back in until it's positive,
// a max of 2 times.
//
sdlProd1.u.Lo = rgulDen[0];
sdlProd1.u.Hi = rgulDen[1];
for (;;) {
sdlQuo.u.Lo--;
sdlNum.int64 += sdlProd1.int64;
rgulNum[2] += rgulDen[2];
if (sdlNum.int64 < sdlProd1.int64) {
// Detected carry. Check for carry out of top
// before adding it in.
//
if (rgulNum[2]++ < rgulDen[2])
break;
}
if (rgulNum[2] < rgulDen[2])
break; // detected carry
}
}
rgulNum[0] = sdlNum.u.Lo;
rgulNum[1] = sdlNum.u.Hi;
return sdlQuo.u.Lo;
}
/***
* Div96By32
*
* Entry:
* rgulNum - Pointer to 96-bit dividend as array of ULONGs, least-sig first
* ulDen - 32-bit divisor.
*
* Purpose:
* Do full divide, yielding 96-bit result and 32-bit remainder.
*
* Exit:
* Quotient overwrites dividend.
* Returns remainder.
*
* Exceptions:
* None.
*
***********************************************************************/
ULONG Div96By32(ULONG *rgulNum, ULONG ulDen)
{
LIMITED_METHOD_CONTRACT;
SPLIT64 sdlTmp;
sdlTmp.u.Hi = 0;
if (rgulNum[2] != 0)
goto Div3Word;
if (rgulNum[1] >= ulDen)
goto Div2Word;
sdlTmp.u.Hi = rgulNum[1];
rgulNum[1] = 0;
goto Div1Word;
Div3Word:
sdlTmp.u.Lo = rgulNum[2];
sdlTmp.int64 = DivMod64by32(sdlTmp.int64, ulDen);
rgulNum[2] = sdlTmp.u.Lo;
Div2Word:
sdlTmp.u.Lo = rgulNum[1];
sdlTmp.int64 = DivMod64by32(sdlTmp.int64, ulDen);
rgulNum[1] = sdlTmp.u.Lo;
Div1Word:
sdlTmp.u.Lo = rgulNum[0];
sdlTmp.int64 = DivMod64by32(sdlTmp.int64, ulDen);
rgulNum[0] = sdlTmp.u.Lo;
return sdlTmp.u.Hi;
}
/***
* Div96By64
*
* Entry:
* rgulNum - Pointer to 96-bit dividend as array of ULONGs, least-sig first
* sdlDen - 64-bit divisor.
*
* Purpose:
* Do partial divide, yielding 32-bit result and 64-bit remainder.
* Divisor must be larger than upper 64 bits of dividend.
*
* Exit:
* Remainder overwrites lower 64-bits of dividend.
* Returns quotient.
*
* Exceptions:
* None.
*
***********************************************************************/
ULONG Div96By64(ULONG *rgulNum, SPLIT64 sdlDen)
{
LIMITED_METHOD_CONTRACT;
SPLIT64 sdlQuo;
SPLIT64 sdlNum;
SPLIT64 sdlProd;
sdlNum.u.Lo = rgulNum[0];
if (rgulNum[2] >= sdlDen.u.Hi) {
// Divide would overflow. Assume a quotient of 2^32, and set
// up remainder accordingly. Then jump to loop which reduces
// the quotient.
//
sdlNum.u.Hi = rgulNum[1] - sdlDen.u.Lo;
sdlQuo.u.Lo = 0;
goto NegRem;
}
// Hardware divide won't overflow
//
if (rgulNum[2] == 0 && rgulNum[1] < sdlDen.u.Hi)
// Result is zero. Entire dividend is remainder.
//
return 0;
// DivMod64by32 returns quotient in Lo, remainder in Hi.
//
sdlQuo.u.Lo = rgulNum[1];
sdlQuo.u.Hi = rgulNum[2];
sdlQuo.int64 = DivMod64by32(sdlQuo.int64, sdlDen.u.Hi);
sdlNum.u.Hi = sdlQuo.u.Hi; // remainder
// Compute full remainder, rem = dividend - (quo * divisor).
//
sdlProd.int64 = UInt32x32To64(sdlQuo.u.Lo, sdlDen.u.Lo); // quo * lo divisor
sdlNum.int64 -= sdlProd.int64;
if (sdlNum.int64 > ~sdlProd.int64) {
NegRem:
// Remainder went negative. Add divisor back in until it's positive,
// a max of 2 times.
//
do {
sdlQuo.u.Lo--;
sdlNum.int64 += sdlDen.int64;
}while (sdlNum.int64 >= sdlDen.int64);
}
rgulNum[0] = sdlNum.u.Lo;
rgulNum[1] = sdlNum.u.Hi;
return sdlQuo.u.Lo;
}
// Add a 32 bit unsigned long to an array of 3 unsigned longs representing a 96 integer
// Returns FALSE if there is an overflow
BOOL Add32To96(ULONG *rgulNum, ULONG ulValue) {
rgulNum[0] += ulValue;
if (rgulNum[0] < ulValue) {
if (++rgulNum[1] == 0) {
if (++rgulNum[2] == 0) {
return FALSE;
}
}
}
return TRUE;
}