-
Notifications
You must be signed in to change notification settings - Fork 34
/
DecimalUtil.h
1157 lines (1036 loc) · 40.3 KB
/
DecimalUtil.h
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
#pragma once
#include <limits>
#include <string>
#include <sstream>
#include <iomanip>
#include <map>
#include "CoreConcept.h"
#include "Exceptions.h"
#include "ScalarImp.h"
#include "Types.h"
#include "Util.h"
#include "WideInteger.h"
namespace decimal_util {
// Operations
ConstantSP decimalScalarAdd(const ConstantSP &lhs, const ConstantSP &rhs);
void decimalScalarAddInplace(const ConstantSP &lhs, const ConstantSP &rhs, const ConstantSP &result,
const INDEX outputStart, bool validate);
ConstantSP decimalScalarSub(const ConstantSP &lhs, const ConstantSP &rhs);
void decimalScalarSubInplace(const ConstantSP &lhs, const ConstantSP &rhs, const ConstantSP &result,
const INDEX outputStart, bool validate);
ConstantSP decimalScalarMultiply(const ConstantSP &lhs, const ConstantSP &rhs);
void decimalScalarMultiplyInplace(const ConstantSP &lhs, const ConstantSP &rhs, const ConstantSP &result,
const INDEX outputStart, bool validate);
ConstantSP decimalScalarDivide(const ConstantSP &lhs, const ConstantSP &rhs);
void decimalScalarDivideInplace(const ConstantSP &lhs, const ConstantSP &rhs, const ConstantSP &result,
const INDEX outputStart, bool validate);
ConstantSP decimalVectorAdd(const ConstantSP &lhs, const ConstantSP &rhs);
void decimalVectorAddInplace(const ConstantSP &lhs, const ConstantSP &rhs, const ConstantSP &result,
const INDEX outputStart, bool validate, const INDEX inputStart, const INDEX inputLen);
ConstantSP decimalVectorSub(const ConstantSP &lhs, const ConstantSP &rhs);
void decimalVectorSubInplace(const ConstantSP &lhs, const ConstantSP &rhs, const ConstantSP &result,
const INDEX outputStart, bool validate, const INDEX inputStart, const INDEX inputLen);
ConstantSP decimalVectorMultiply(const ConstantSP &lhs, const ConstantSP &rhs);
void decimalVectorMultiplyInplace(const ConstantSP &lhs, const ConstantSP &rhs, const ConstantSP &result,
const INDEX outputStart, bool validate, const INDEX inputStart,
const INDEX inputLen);
ConstantSP decimalVectorDivide(const ConstantSP &lhs, const ConstantSP &rhs);
void decimalVectorDivideInplace(const ConstantSP &lhs, const ConstantSP &rhs, const ConstantSP &result,
const INDEX outputStart, bool validate, const INDEX inputStart, const INDEX inputLen);
ConstantSP decimalScalarFloorDivide(const ConstantSP &lhs, const ConstantSP &rhs);
ConstantSP decimalVectorFloorDivide(const ConstantSP &lhs, const ConstantSP &rhs);
ConstantSP contextSum(const ConstantSP &a, const ConstantSP &b);
ConstantSP round(const ConstantSP &obj, const int new_scale);
ConstantSP ceil(const ConstantSP &obj);
ConstantSP floor(const ConstantSP &obj);
ConstantSP decimalScalarMultiply(const ConstantSP &lhs, const ConstantSP &rhs, int resultScale);
ConstantSP decimalVectorMultiply(const ConstantSP &lhs, const ConstantSP &rhs, int resultScale);
// Decimal implementation details
template <typename T>
struct RawDecimal {
/// Determines how many decimal digits fraction can have.
/// Valid range: [0, MaxPrecision]
int scale;
/// 0.001 => 1
/// 12.345 => 12345
T rawData;
};
enum class RoundingMode {
round,
trunc,
};
/// Default rounding mode.
extern RoundingMode gDefaultRoundingMode;
template <typename T>
struct MinPrecision { static constexpr int value = 1; };
template <typename T>
struct MaxPrecision;
template <> struct MaxPrecision<int> { static constexpr int value = 9; };
template <> struct MaxPrecision<long long> { static constexpr int value = 18; };
template <> struct MaxPrecision<int128> { static constexpr int value = 38; };
template <typename T>
struct DecimalType;
template <> struct DecimalType<int> { static constexpr DATA_TYPE value = DT_DECIMAL32; };
template <> struct DecimalType<long long> { static constexpr DATA_TYPE value = DT_DECIMAL64; };
template <> struct DecimalType<int128> { static constexpr DATA_TYPE value = DT_DECIMAL128; };
inline int exp10_i32(int x) {
constexpr int values[] = {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000
};
assert(x >= 0 && static_cast<size_t>(x) < sizeof(values)/sizeof(values[0]));
return values[x];
}
inline long long exp10_i64(int x) {
constexpr long long values[] = {
1LL,
10LL,
100LL,
1000LL,
10000LL,
100000LL,
1000000LL,
10000000LL,
100000000LL,
1000000000LL,
10000000000LL,
100000000000LL,
1000000000000LL,
10000000000000LL,
100000000000000LL,
1000000000000000LL,
10000000000000000LL,
100000000000000000LL,
1000000000000000000LL
};
assert(x >= 0 && static_cast<size_t>(x) < sizeof(values)/sizeof(values[0]));
return values[x];
}
inline int128 exp10_i128(int x) {
using int128 = int128;
constexpr int128 values[] =
{
static_cast<int128>(1LL),
static_cast<int128>(10LL),
static_cast<int128>(100LL),
static_cast<int128>(1000LL),
static_cast<int128>(10000LL),
static_cast<int128>(100000LL),
static_cast<int128>(1000000LL),
static_cast<int128>(10000000LL),
static_cast<int128>(100000000LL),
static_cast<int128>(1000000000LL),
static_cast<int128>(10000000000LL),
static_cast<int128>(100000000000LL),
static_cast<int128>(1000000000000LL),
static_cast<int128>(10000000000000LL),
static_cast<int128>(100000000000000LL),
static_cast<int128>(1000000000000000LL),
static_cast<int128>(10000000000000000LL),
static_cast<int128>(100000000000000000LL),
static_cast<int128>(1000000000000000000LL),
static_cast<int128>(1000000000000000000LL) * 10LL,
static_cast<int128>(1000000000000000000LL) * 100LL,
static_cast<int128>(1000000000000000000LL) * 1000LL,
static_cast<int128>(1000000000000000000LL) * 10000LL,
static_cast<int128>(1000000000000000000LL) * 100000LL,
static_cast<int128>(1000000000000000000LL) * 1000000LL,
static_cast<int128>(1000000000000000000LL) * 10000000LL,
static_cast<int128>(1000000000000000000LL) * 100000000LL,
static_cast<int128>(1000000000000000000LL) * 1000000000LL,
static_cast<int128>(1000000000000000000LL) * 10000000000LL,
static_cast<int128>(1000000000000000000LL) * 100000000000LL,
static_cast<int128>(1000000000000000000LL) * 1000000000000LL,
static_cast<int128>(1000000000000000000LL) * 10000000000000LL,
static_cast<int128>(1000000000000000000LL) * 100000000000000LL,
static_cast<int128>(1000000000000000000LL) * 1000000000000000LL,
static_cast<int128>(1000000000000000000LL) * 10000000000000000LL,
static_cast<int128>(1000000000000000000LL) * 100000000000000000LL,
static_cast<int128>(1000000000000000000LL) * 100000000000000000LL * 10LL,
static_cast<int128>(1000000000000000000LL) * 100000000000000000LL * 100LL,
static_cast<int128>(1000000000000000000LL) * 100000000000000000LL * 1000LL
};
assert(x >= 0 && static_cast<size_t>(x) < sizeof(values)/sizeof(values[0]));
return values[x];
}
template <typename T>
inline T scaleMultiplier(int scale);
template <>
inline int scaleMultiplier<int>(int scale) {
return exp10_i32(scale);
}
template <>
inline long long scaleMultiplier<long long>(int scale) {
return exp10_i64(scale);
}
template <>
inline int128 scaleMultiplier<int128>(int scale) {
return exp10_i128(scale);
}
/**
* calculate greatest common divisor
*/
template <typename T>
inline T gcd(T a, T b) {
T c;
while (a != 0) {
c = a;
a = b % a;
b = c;
}
return b;
}
// since we use min() as nullValue, so a+b=min() cause overflow
template <typename T>
inline bool addOverflow(T a, T b, T &res) {
res = a + b;
if (b > 0 && a > std::numeric_limits<T>::max() - b) {
return true;
}
if (b < 0 && a <= std::numeric_limits<T>::min() - b) {
return true;
}
return false;
}
// since we use min() as nullValue, so a-b=min() cause overflow
template <typename T>
inline bool subOverflow(T a, T b, T &res) {
res = a - b;
if (b < 0 && a > std::numeric_limits<T>::max() + b) {
return true;
}
if (b > 0 && a <= std::numeric_limits<T>::min() + b) {
return true;
}
return false;
}
template <typename T, typename U, typename R = typename std::conditional<sizeof(T) >= sizeof(U), T, U>::type>
inline bool mulOverflow(T a, U b, R &result) {
result = a * b;
if (a == 0 || b == 0) {
return false;
}
if ((a < 0) != (b < 0)) { // different sign
if (a == std::numeric_limits<R>::min()) {
return b > 1;
} else if (b == std::numeric_limits<R>::min()) {
return a > 1;
}
if (a < 0) {
return (-a) > std::numeric_limits<R>::max() / b;
}
if (b < 0) {
return a > std::numeric_limits<R>::max() / (-b);
}
} else if (a < 0 && b < 0) {
if (a == std::numeric_limits<R>::min()) {
return b <= -1;
} else if (b == std::numeric_limits<R>::min()) {
return a <= -1;
}
return (-a) > std::numeric_limits<R>::max() / (-b);
}
return a > std::numeric_limits<R>::max() / b;
}
/**
* @brief result = value1 * value2 / divisor
*
* @return overflow or not
*/
template <typename T>
inline bool mulDivOverflow(T value1, T value2, T divisor, T &result) {
// minimize value1 & divisor
{
T c = gcd(value1, divisor);
if (c != 1) {
value1 /= c;
divisor /= c;
}
}
// minimize value2 & divisor
{
T c = gcd(value2, divisor);
if (c != 1) {
value2 /= c;
divisor /= c;
}
}
bool overflow = mulOverflow(value1, value2, result);
result /= divisor;
return overflow;
}
// Decimal <=> String
template <typename T>
inline std::string toString(int scale, T rawData) {
std::stringstream ss;
if (scale == 0) {
ss << rawData;
} else {
auto multiplier = scaleMultiplier<T>(scale);
T integer = rawData / multiplier;
if (rawData < 0 && integer == 0) {
ss << '-';
}
ss << integer;
int sign = rawData < 0 ? -1 : 1;
auto frac = rawData % multiplier * sign;
ss << "." << std::setw(scale) << std::setfill('0') << std::right << frac;
}
return ss.str();
}
struct DecimalParser {
struct Context {
/// The specified scale of decimal (i.e. the digits count of decimal fraction). This field only valid
/// when `determine_scale_automatically` set to false.
int scale = 0;
/// Indicate whether determine `scale` automatically. If true, will ignore the `scale` field.
bool determine_scale_automatically = true;
/// Rounding mode, see @c RoundingMode
RoundingMode rounding = gDefaultRoundingMode;
/// Indicate whether in strict mode. If true, string like "2013.06.13" will treated as invalid,
/// if false, "2013.06.13" will be parsed to "2013.06".
/// Note: string that does not contain any numerical digits at the beginning (e.g. "aaa123") will
/// be parsed to "NULL", no matter whether `strict` is set to true or false.
bool strict = false;
/// Providing specified scale.
explicit Context(int _scale, RoundingMode _rounding = gDefaultRoundingMode, bool _strict = false)
: scale(_scale), determine_scale_automatically(false), rounding(_rounding), strict(_strict) {
}
/// No specified scale, determine scale automatically.
explicit Context(RoundingMode _rounding = gDefaultRoundingMode, bool _strict = false)
: scale(0), determine_scale_automatically(true), rounding(_rounding), strict(_strict) {
}
};
/**
* @brief Parse string to decimal.
*
* @param[out] errMsg The reason if parse failed, caller MUST check it after calling this function.
* @param ctx The parser context, see @c Context above.
*
* @note Not support string like: "1E-16" | "-0x1afp-2" | "inf" | "NaN" | "NULL"
*/
template <typename T>
static RawDecimal<T> parse(const string &str, string &errMsg, const Context &ctx) {
return parse<T>(str.data(), str.size(), errMsg, ctx);
}
template <typename T>
static RawDecimal<T> parse(const char *str, size_t str_len, string &errMsg, const Context &ctx) {
enum class State {
BeforeSign,
BeforeFirstDigit,
BeforeDecPoint,
AfterDecPoint,
/*------*/
Finish
};
enum class Error {
Ok = 0,
WrongChar,
WrongState,
Overflow,
ScaleOverflow,
/*------*/
Count
};
const char *const kErrorMsg[] = {
"", // No error.
"Invalid string",
"Invalid string",
"Decimal overflow",
"Scale out of bounds",
"BUG!"
};
const char dec_point = '.';
Error error = Error::Ok;
State prevState = State::BeforeSign;
State state = State::BeforeSign;
int scale = ctx.scale;
T rawData = 0;
const auto buildErrorMsg = [&](Error err) {
assert(err < Error::Count);
return "Failed to parse \"" + std::string(str, str_len) + "\" to " +
Util::getDataTypeString(DecimalType<T>::value) + "(" + std::to_string(scale) + "): " +
kErrorMsg[static_cast<int>(err)];
};
const bool determine_scale = ctx.determine_scale_automatically;
if (determine_scale) {
scale = decimal_util::MaxPrecision<T>::value;
} else {
if (scale < 0 || scale > MaxPrecision<T>::value) {
errMsg = buildErrorMsg(Error::ScaleOverflow) + " (valid range: [0, " +
std::to_string(MaxPrecision<T>::value) + "], but get: " + std::to_string(scale) +
"). RefId: S05010";
return RawDecimal<T>{.scale = -9529, .rawData = 0};
}
}
// For compatibility with floating in DDB, '+' and '-' are treated as digit,
// but '.' is not considered a digit, e.g.:
// "+" => 0
// "-" => 0
// "," => NULL
bool no_digits = true;
// Total digits count, ignore leading zeros, e.g.: "001.11" => 3
int digits_count = 0;
// Fraction digits count, e.g.: "1.11" => 2, "1.1100" => 4
int frac_digits_count = 0;
int sign = 1;
bool need_rounding = false;
for (size_t i = 0; (i < str_len) && (state != State::Finish); /*nop*/) {
const char c = str[i++];
switch (state) {
case State::BeforeSign:
if (c == '-') {
sign = -1;
no_digits = false;
state = State::BeforeFirstDigit;
} else if (c == '+') {
no_digits = false;
state = State::BeforeFirstDigit;
} else if ((c >= '0') && (c <= '9')) {
no_digits = false;
if (c != '0') {
assert(digits_count == 0);
digits_count++;
}
assert(rawData == 0);
rawData = static_cast<int>(c - '0');
state = State::BeforeDecPoint;
} else if (c == dec_point) {
state = State::AfterDecPoint;
} else if ((c == ' ') || (c == '\t')) {
// Skip whitespace.
} else {
error = Error::WrongChar;
prevState = state;
state = State::Finish;
}
// else: Skip whitespace.
break;
case State::BeforeFirstDigit:
if ((c >= '0') && (c <= '9')) {
if (c != '0') {
assert(digits_count == 0);
digits_count++;
}
assert(rawData == 0);
rawData = static_cast<int>(c - '0');
state = State::BeforeDecPoint;
} else if (c == dec_point) {
state = State::AfterDecPoint;
} else {
error = Error::WrongChar;
prevState = state;
state = State::Finish;
}
break;
case State::BeforeDecPoint:
if ((c >= '0') && (c <= '9')) {
// Case: 000001.123 => 1.234
if (digits_count != 0 || c != '0') {
if (digits_count + 1 > decimal_util::MaxPrecision<T>::value) {
error = Error::Overflow;
state = State::Finish;
break;
}
digits_count++;
}
rawData = 10 * rawData + static_cast<int>(c - '0');
} else if (c == dec_point) {
state = State::AfterDecPoint;
} else {
error = Error::WrongChar;
prevState = state;
state = State::Finish;
}
break;
case State::AfterDecPoint:
if ((c >= '0') && (c <= '9')) {
// Case: "." => NULL
// Case: ".000" => 0 (This is not compatible with floating in DDB)
no_digits = false;
if (frac_digits_count + 1 > scale) {
need_rounding = (static_cast<int>(c - '0') >= 5);
state = State::Finish;
break;
}
if (digits_count + 1 > decimal_util::MaxPrecision<T>::value) {
error = Error::Overflow;
state = State::Finish;
break;
}
digits_count++;
frac_digits_count++;
rawData = 10 * rawData + static_cast<int>(c - '0');
} else {
error = Error::WrongChar;
prevState = state;
state = State::Finish;
}
break;
default:
error = Error::WrongState;
state = State::Finish;
break;
}
}
if (ctx.rounding == RoundingMode::round && need_rounding) {
rawData += 1;
}
if (determine_scale) {
scale = frac_digits_count;
}
RawDecimal<T> result{.scale = scale, .rawData = rawData};
const auto buildResult = [&]() {
// Case: 1.234aaaa =>
// if ctx.strict == false:
// 1.234
// else:
// Failed
if (error == Error::Ok || (ctx.strict == false && error == Error::WrongChar)) {
if (no_digits) {
// Case: aaaa => NULL
result.rawData = std::numeric_limits<T>::min();
return;
}
if (determine_scale || scale > frac_digits_count) {
if (digits_count + scale - frac_digits_count > decimal_util::MaxPrecision<T>::value) {
result.scale = -9527;
result.rawData = 0;
errMsg = buildErrorMsg(Error::Overflow);
return;
} else {
result.rawData = rawData * decimal_util::scaleMultiplier<T>(scale - frac_digits_count);
}
}
if (sign < 0) {
result.rawData = -result.rawData;
}
} else {
if (error == Error::WrongChar && prevState == State::BeforeSign) {
// Case: aaaa => NULL
result.rawData = std::numeric_limits<T>::min();
return;
}
result.scale = -9528;
result.rawData = 0;
errMsg = buildErrorMsg(error);
}
};
buildResult();
return result;
}
};
template <typename T>
inline RawDecimal<T> toDecimal(const string &str, int scale) {
const DecimalParser::Context ctx(scale, gDefaultRoundingMode);
std::string errMsg;
const auto dec = DecimalParser::parse<T>(str, errMsg, ctx);
if (errMsg.empty() == false) {
throw RuntimeException(errMsg);
}
assert(dec.scale == scale);
return dec;
}
inline RawDecimal<Decimal32::raw_data_t> toDecimal32(const string &str, int scale) {
return toDecimal<Decimal32::raw_data_t>(str, scale);
}
inline RawDecimal<Decimal64::raw_data_t> toDecimal64(const string &str, int scale) {
return toDecimal<Decimal64::raw_data_t>(str, scale);
}
inline RawDecimal<Decimal128::raw_data_t> toDecimal128(const string &str, int scale) {
return toDecimal<Decimal128::raw_data_t>(str, scale);
}
template <typename T>
inline Decimal<T> toDecimal(const ConstantSP &obj, int scale) {
Decimal<T> ret{scale};
if (false == ret.assign(obj)) {
throw RuntimeException("Can't convert " + Util::getDataTypeString(obj->getType()) + " to " +
Util::getDataTypeString(DecimalType<T>::value) + "(" + std::to_string(scale) + ")");
}
return ret;
}
// Misc
template <typename T> inline long double to_long_double(T v) {
return static_cast<long double>(v);
}
// Ref: https://github.com/abseil/abseil-cpp/blob/master/absl/numeric/int128_no_intrinsic.inc#L135-L146
inline long double to_long_double(int128 v) {
#ifdef WINDOWS
assert(v != INT128_MIN);
return (v < 0 ? -static_cast<long double>(-v) : static_cast<long double>(v));
#else
return static_cast<long double>(v);
#endif
}
inline std::pair<DATA_TYPE, int> determineOperateResultType(const std::pair<DATA_TYPE, int> &lhs,
const std::pair<DATA_TYPE, int> &rhs,
bool is_mul, bool is_div) {
ASSERT(Util::getCategory(lhs.first) == DENARY && Util::getCategory(rhs.first) == DENARY);
DATA_TYPE resultType = std::max(lhs.first, rhs.first);
int resultScale = -1;
if (is_mul) {
resultScale = lhs.second + rhs.second;
} else if (is_div) {
resultScale = lhs.second;
} else {
resultScale = std::max(lhs.second, rhs.second);
}
if (resultType == DT_DECIMAL32) {
if (resultScale > decimal_util::MaxPrecision<Decimal32::raw_data_t>::value) {
resultType = DT_DECIMAL64;
}
} else if (resultType == DT_DECIMAL64) {
if (resultScale > decimal_util::MaxPrecision<Decimal64::raw_data_t>::value) {
resultType = DT_DECIMAL128;
}
}
return {resultType, resultScale};
}
inline std::pair<DATA_TYPE, int> determineOperateResultType(const ConstantSP &lhs, const ConstantSP &rhs,
bool is_mul, bool is_div) {
if (lhs->getCategory() == DENARY && rhs->getCategory() == DENARY) {
return determineOperateResultType({lhs->getType(), lhs->getExtraParamForType()},
{rhs->getType(), rhs->getExtraParamForType()}, is_mul, is_div);
} else if (lhs->getCategory() == DENARY) {
return {lhs->getType(), lhs->getExtraParamForType()};
} else /* (rhs->getCategory() == DENARY) */ {
return {rhs->getType(), rhs->getExtraParamForType()};
}
}
inline void validateScale(const DATA_TYPE type, const int scale) {
#define CASE_DECIMAL(bits) \
case DT_DECIMAL##bits: { \
using T = Decimal##bits::raw_data_t; \
if (scale < 0 || scale > MaxPrecision<T>::value) { \
throw RuntimeException("Scale out of bounds for Decimal" #bits \
" (valid range: [0, " + std::to_string(MaxPrecision<T>::value) + \
"], but get: " + std::to_string(scale) + "). RefId: S05010"); \
} \
break; \
} \
//======
if (Util::getCategory(type) == DENARY) {
switch (type) {
CASE_DECIMAL(32)
CASE_DECIMAL(64)
CASE_DECIMAL(128)
default:
throw RuntimeException("Unknown Decimal type: " + std::to_string(static_cast<int>(type)));
}
}
#undef CASE_DECIMAL
}
inline bool isDecimalType(DATA_TYPE type) {
if (type >= ARRAY_TYPE_BASE) {
type = static_cast<DATA_TYPE>(type - ARRAY_TYPE_BASE);
}
return (Util::getCategory(type) == DENARY);
}
inline std::string categoryToString(const DATA_CATEGORY cat) {
#define NORMAL_CASE(tag) case tag: return #tag;
switch (cat) {
NORMAL_CASE(LOGICAL);
NORMAL_CASE(INTEGRAL);
NORMAL_CASE(FLOATING);
NORMAL_CASE(TEMPORAL);
NORMAL_CASE(LITERAL);
NORMAL_CASE(SYSTEM);
NORMAL_CASE(MIXED);
NORMAL_CASE(BINARY);
NORMAL_CASE(COMPLEX);
NORMAL_CASE(ARRAY);
NORMAL_CASE(DENARY);
default: return "UNKNOWN(" + std::to_string(static_cast<int>(cat)) + ")";
}
#undef NORMAL_CASE
}
inline void checkArithmeticOperation(const DATA_CATEGORY cat) {
if (cat != NOTHING && cat != INTEGRAL && cat != FLOATING && cat != DENARY) {
throw RuntimeException("Not allow to perform arithmetic operation between DECIMAL and " +
categoryToString(cat));
}
}
inline void checkComparison(const DATA_CATEGORY cat) {
if (cat != NOTHING && cat != INTEGRAL && cat != FLOATING && cat != DENARY) {
throw RuntimeException("Not allow to perform comparison between DECIMAL and " + categoryToString(cat));
}
}
/**
* @brief valid str: "DECIMAL32(2)", "decimal64(8)", or "decimal128(10)"
* "DECIMAL32(2)[]"
*
* @return std::pair<DATA_TYPE, int> second: scale
*/
inline std::pair<DATA_TYPE, int> parseDecimalType(const std::string &str) {
std::pair<DATA_TYPE, int> ret{DT_VOID, 0};
if (false == Util::startWith(Util::lower(str), "decimal")) {
return ret;
}
constexpr size_t kDecLen = sizeof("decimal") - 1;
if (str.size() < kDecLen + 2) {
throw RuntimeException("Invalid decimal data type");
}
size_t i = kDecLen;
if (str[i] == '3' && str[i+1] == '2') {
ret.first = DT_DECIMAL32;
i += 2;
} else if (str[i] == '6' && str[i+1] == '4') {
ret.first = DT_DECIMAL64;
i += 2;
} else if (str[i] == '1' && str[i+1] == '2') {
if (str.size() < kDecLen + 3 || str[i+2] != '8') {
throw RuntimeException("Invalid decimal data type");
}
ret.first = DT_DECIMAL128;
i += 3;
} else {
throw RuntimeException("Invalid decimal data type");
}
if (str.size() < i + 1 || str[i] != '(' /*|| str[str.size()-1] != ')'*/) {
throw RuntimeException("Invalid decimal data type");
}
++i;
char digits[4] = {0};
bool noDigits = true;
for (size_t j = 0; j < 3 && i < str.size(); ++j) {
if (str[i] == ')') {
break;
}
if (false == std::isdigit(str[i])) {
throw RuntimeException("Invalid scale for decimal data type");
}
digits[j] = str[i];
noDigits = false;
++i;
}
if (str[i] != ')') {
throw RuntimeException("Invalid decimal data type");
}
if (noDigits) {
throw RuntimeException("Must specify scale for decimal data type");
}
ret.second = std::strtol(digits, nullptr, 10);
++i;
if (i < str.size()) {
if (str.size() != i + 2 || str[i] != '[' || str[i+1] != ']') {
throw RuntimeException("Invalid decimal data type");
}
// decimal array vector
ret.first = static_cast<DATA_TYPE>(static_cast<int>(ret.first) + ARRAY_TYPE_BASE);
}
return ret;
}
inline int packDecimalTypeAndScale(DATA_TYPE type, int scale) {
ASSERT(isDecimalType(type));
if (false == isDecimalType(type)) {
return static_cast<int>(type);
}
/*
* 31 16 0
* +---+-----------+-------------+
* | 1 | scale | data type |
* +---+-----------+-------------+
*/
return ((scale << 16) | 0x80000000) | (type & 0xffff);
}
inline std::pair<DATA_TYPE, int> unpackDecimalTypeAndScale(const int value) {
DATA_TYPE type = static_cast<DATA_TYPE>(value);
int scale = 0;
if (value & 0x80000000) {
/*
* 31 16 0
* +---+-----------+-------------+
* | 1 | scale | data type |
* +---+-----------+-------------+
*/
scale = (value & (~0x80000000)) >> 16;
type = static_cast<DATA_TYPE>(value & 0xffff);
if (type >= ARRAY_TYPE_BASE) {
if (Util::getCategory(static_cast<DATA_TYPE>(static_cast<int>(type) - ARRAY_TYPE_BASE)) != DENARY) {
type = DT_VOID;
}
} else {
if (Util::getCategory(type) != DENARY) {
type = DT_VOID;
}
}
}
return {type, scale};
}
/**
* 32 24 0
* +-----------------+-------+
* | compress method | scale |
* +-----------------+-------+
*/
inline int getScaleFromExtraParam(int extra) {
return extra & 0x00ffffff;
}
/**
* trunc(1.236, 3, 1) => 1.2
* trunc(1.236, 3, 2) => 1.23
* trunc(1.236, 3, 4) => 1.2360
*/
template <typename T>
T trunc(const T old_raw_data, const int old_scale, const int new_scale) {
assert(new_scale >= 0);
T new_raw_data;
if (old_raw_data == std::numeric_limits<T>::min()) {
new_raw_data = old_raw_data;
return new_raw_data;
}
if (old_scale > new_scale) {
new_raw_data = old_raw_data / scaleMultiplier<T>(old_scale - new_scale);
} else {
if (mulOverflow(old_raw_data, scaleMultiplier<T>(new_scale - old_scale), new_raw_data)) {
throw MathException("Decimal math overflow. RefId:S05003");
}
}
return new_raw_data;
}
/**
* round(1.236, 3, 1) => 1.2
* round(1.236, 3, 2) => 1.24
* round(1.236, 3, 4) => 1.2360
*/
template <typename T>
T round(const T old_raw_data, const int old_scale, const int new_scale) {
assert(new_scale >= 0);
if (old_raw_data == std::numeric_limits<T>::min() || old_scale == new_scale) {
return old_raw_data;
}
T new_raw_data{};
if (old_scale > new_scale) {
const int sign = (old_raw_data < 0) ? -1 : 1;
const T diff_pow10 = scaleMultiplier<T>(old_scale - new_scale);
const T rounded = sign * old_raw_data % diff_pow10;
new_raw_data = old_raw_data / diff_pow10;
if (rounded >= (diff_pow10 / 2)) {
new_raw_data += (sign);
}
} else {
if (mulOverflow(old_raw_data, scaleMultiplier<T>(new_scale - old_scale), new_raw_data)) {
throw MathException("Decimal math overflow. RefId:S05003");
}
}
return new_raw_data;
}
/**
* ceil(1.3) == 2
* ceil(1.6) == 2
* ceil(-1.3) == -1
* ceil(-1.6) == -1
*/
template <typename T>
T ceil(const T old_raw_data, const int old_scale) {
T new_raw_data;
if (old_raw_data == std::numeric_limits<T>::min()) {
new_raw_data = old_raw_data;
return new_raw_data;
}
if (old_scale == 0) {
new_raw_data = old_raw_data;
} else {
T delta = 0;
if (old_raw_data > 0) {
if ((old_raw_data % scaleMultiplier<T>(old_scale)) != 0) {
delta = 1;
}
}
new_raw_data = old_raw_data / scaleMultiplier<T>(old_scale);
if (delta != 0 && addOverflow(new_raw_data, delta, new_raw_data)) {
throw MathException("Decimal math overflow. RefId:S05003");
}
}
return new_raw_data;
}
/**
* floor(1.3) == 1
* floor(1.6) == 1
* floor(-1.3) == -2
* floor(-1.6) == -2
*/
template <typename T>
T floor(const T old_raw_data, const int old_scale) {
T new_raw_data;
if (old_raw_data == std::numeric_limits<T>::min()) {
new_raw_data = old_raw_data;
return new_raw_data;
}
if (old_scale == 0) {
new_raw_data = old_raw_data;
} else {
T delta = 0;
if (old_raw_data < 0) {
if ((old_raw_data % scaleMultiplier<T>(old_scale)) != 0) {
delta = -1;
}
}
new_raw_data = old_raw_data / scaleMultiplier<T>(old_scale);
if (delta != 0 && addOverflow(new_raw_data, delta, new_raw_data)) {
throw MathException("Decimal math overflow. RefId:S05003");
}
}
return new_raw_data;
}
#define ENABLE_FOR_DECIMAL(bits, T, return_type_t) \
template <typename U = T> \
typename std::enable_if<std::is_same<U, Decimal##bits::raw_data_t>::value == true, return_type_t>::type \
//======
#define ENABLE_FOR_DECIMAL32(T, return_type_t) ENABLE_FOR_DECIMAL(32, T, return_type_t)
#define ENABLE_FOR_DECIMAL64(T, return_type_t) ENABLE_FOR_DECIMAL(64, T, return_type_t)
#define ENABLE_FOR_DECIMAL128(T, return_type_t) ENABLE_FOR_DECIMAL(128, T, return_type_t)