forked from pingcap/tiflash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionsRound.h
More file actions
1672 lines (1447 loc) · 58.7 KB
/
FunctionsRound.h
File metadata and controls
1672 lines (1447 loc) · 58.7 KB
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
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <Common/Decimal.h>
#include <Common/TiFlashException.h>
#include <Common/toSafeUnsigned.h>
#include <Functions/FunctionHelpers.h>
#include <Functions/FunctionUnaryArithmetic.h>
#include <IO/WriteHelpers.h>
#include <array>
#include <cfenv>
#include <cmath>
#include <ext/bit_cast.h>
#include <type_traits>
#if __SSE4_1__
#include <smmintrin.h>
#endif
#include <fmt/format.h>
namespace DB
{
namespace ErrorCodes
{
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
extern const int OVERFLOW_ERROR;
} // namespace ErrorCodes
/** Rounding Functions:
* round(x, N) - rounding to nearest (N = 0 by default). Use banker's rounding for floating point numbers.
* floor(x, N) is the largest number <= x (N = 0 by default).
* ceil(x, N) is the smallest number >= x (N = 0 by default).
* trunc(x, N) - is the largest by absolute value number that is not greater than x by absolute value (N = 0 by default).
*
* The value of the parameter N (scale):
* - N > 0: round to the number with N decimal places after the decimal point
* - N < 0: round to an integer with N zero characters
* - N = 0: round to an integer
*
* Type of the result is the type of argument.
* For integer arguments, when passing negative scale, overflow can occur.
* In that case, the behavior is implementation specific.
*
* roundToExp2 - down to the nearest power of two (see below);
*
* Deprecated functions:
* roundDuration - down to the nearest of: 0, 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000;
* roundAge - down to the nearest of: 0, 18, 25, 35, 45, 55.
*/
template <typename T>
inline std::enable_if_t<std::is_integral_v<T> && (sizeof(T) <= sizeof(UInt32)), T> roundDownToPowerOfTwo(T x)
{
return x <= 0 ? 0 : (T(1) << (31 - __builtin_clz(x)));
}
template <typename T>
inline std::enable_if_t<std::is_integral_v<T> && (sizeof(T) == sizeof(UInt64)), T> roundDownToPowerOfTwo(T x)
{
return x <= 0 ? 0 : (T(1) << (63 - __builtin_clzll(x)));
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, Float32>, T> roundDownToPowerOfTwo(T x)
{
return ext::bit_cast<T>(ext::bit_cast<UInt32>(x) & ~((1ULL << 23) - 1));
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, Float64>, T> roundDownToPowerOfTwo(T x)
{
return ext::bit_cast<T>(ext::bit_cast<UInt64>(x) & ~((1ULL << 52) - 1));
}
template <typename T>
inline T roundDownToPowerOfTwo(Decimal<T>)
{
throw Exception("have not implement roundDownToPowerOfTwo of type Decimal.");
}
/** For integer data types:
* - if number is greater than zero, round it down to nearest power of two (example: roundToExp2(100) = 64, roundToExp2(64) = 64);
* - otherwise, return 0.
*
* For floating point data types: zero out mantissa, but leave exponent.
* - if number is greater than zero, round it down to nearest power of two (example: roundToExp2(3) = 2);
* - negative powers are also used (example: roundToExp2(0.7) = 0.5);
* - if number is zero, return zero;
* - if number is less than zero, the result is symmetrical: roundToExp2(x) = -roundToExp2(-x). (example: roundToExp2(-0.3) = -0.25);
*/
template <typename T>
struct RoundToExp2Impl
{
using ResultType = T;
static inline T apply(T x) { return roundDownToPowerOfTwo<T>(x); }
};
template <typename A>
struct RoundDurationImpl
{
using ResultType = UInt16;
static inline ResultType apply(A x)
{
// clang-format off
return x < 1 ? 0
: (x < 10 ? 1
: (x < 30 ? 10
: (x < 60 ? 30
: (x < 120 ? 60
: (x < 180 ? 120
: (x < 240 ? 180
: (x < 300 ? 240
: (x < 600 ? 300
: (x < 1200 ? 600
: (x < 1800 ? 1200
: (x < 3600 ? 1800
: (x < 7200 ? 3600
: (x < 18000 ? 7200
: (x < 36000 ? 18000
: 36000))))))))))))));
// clang-format on
}
};
template <typename T>
struct RoundDurationImpl<Decimal<T>>
{
using ResultType = UInt16;
static inline ResultType apply(Decimal<T>) { throw Exception("RoundDuration of decimal is not implemented yet."); }
};
template <typename A>
struct RoundAgeImpl
{
using ResultType = UInt8;
static inline ResultType apply(A x)
{
// clang-format off
return x < 1 ? 0
: (x < 18 ? 17
: (x < 25 ? 18
: (x < 35 ? 25
: (x < 45 ? 35
: (x < 55 ? 45
: 55)))));
// clang-format on
}
};
template <typename T>
struct RoundAgeImpl<Decimal<T>>
{
using ResultType = UInt8;
static inline ResultType apply(Decimal<T>) { throw Exception("RoundAge of decimal is not implemented yet."); }
};
/** This parameter controls the behavior of the rounding functions.
*/
enum class ScaleMode
{
Positive, // round to a number with N decimal places after the decimal point
Negative, // round to an integer with N zero characters
Zero, // round to an integer
};
enum class RoundingMode
{
#if __SSE4_1__
Round = _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC,
Floor = _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC,
Ceil = _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC,
Trunc = _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC,
#else
Round = 8, /// Values are correspond to above just in case.
Floor = 9,
Ceil = 10,
Trunc = 11,
#endif
};
/** Rounding functions for integer values.
*/
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode>
struct IntegerRoundingComputation
{
static const size_t data_count = 1;
static size_t prepare(size_t scale) { return scale; }
static ALWAYS_INLINE T computeImpl(T x, T scale)
{
if constexpr (rounding_mode == RoundingMode::Trunc)
{
return x / scale * scale;
}
else if constexpr (rounding_mode == RoundingMode::Floor)
{
if (x < 0)
x -= scale - 1;
return x / scale * scale;
}
else if constexpr (rounding_mode == RoundingMode::Ceil)
{
if (x >= 0)
x += scale - 1;
return x / scale * scale;
}
else if constexpr (rounding_mode == RoundingMode::Round)
{
bool negative = x < 0;
if (negative)
x = -x;
x = (x + scale / 2) / scale * scale;
if (negative)
x = -x;
return x;
}
}
static ALWAYS_INLINE T compute(T x, T scale)
{
if constexpr (scale_mode == ScaleMode::Zero)
{
(void)scale;
return x;
}
else if constexpr (scale_mode == ScaleMode::Positive)
{
(void)scale;
return x;
}
else if constexpr (scale_mode == ScaleMode::Negative)
{
return computeImpl(x, scale);
}
}
static ALWAYS_INLINE void compute(const T * __restrict in, T scale, T * __restrict out)
{
*out = compute(*in, scale);
}
};
/** Rounding functions for decimal values
*/
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode, typename OutputType>
struct DecimalRoundingComputation
{
static_assert(IsDecimal<T>);
using NativeType = T::NativeType;
static const size_t data_count = 1;
static size_t prepare(size_t scale) { return scale; }
// compute need decimal_scale to interpret decimals
static inline void compute(
const T * __restrict in,
size_t scale,
OutputType * __restrict out,
NativeType decimal_scale)
{
static_assert(std::is_same_v<T, OutputType> || std::is_same_v<OutputType, Int64>);
// Currently, we only use DecimalRoundingComputation for floor/ceil.
// As for round/truncate, we always use tidbRoundWithFrac/tidbTruncateWithFrac.
// So, we only handle ScaleMode::Zero here.
if constexpr (scale_mode == ScaleMode::Zero)
{
try
{
if constexpr (rounding_mode == RoundingMode::Floor)
{
auto x = in->value;
if (x < 0)
x -= decimal_scale - 1;
*out = static_cast<OutputType>(x / decimal_scale);
}
else if constexpr (rounding_mode == RoundingMode::Ceil)
{
auto x = in->value;
if (x >= 0)
x += decimal_scale - 1;
*out = static_cast<OutputType>(x / decimal_scale);
}
else
{
throw Exception(
"Logical error: unexpected 'rounding_mode' of DecimalRoundingComputation",
ErrorCodes::LOGICAL_ERROR);
}
}
catch (const std::overflow_error & e)
{
throw Exception(
"Logical error: unexpected overflow in DecimalRoundingComputation",
ErrorCodes::LOGICAL_ERROR);
}
}
else
{
throw Exception(
"Logical error: unexpected 'scale_mode' of DecimalRoundingComputation and unexpected scale: "
+ toString(scale),
ErrorCodes::LOGICAL_ERROR);
}
}
};
#if __SSE4_1__
template <typename T>
class BaseFloatRoundingComputation;
template <>
class BaseFloatRoundingComputation<Float32>
{
public:
using ScalarType = Float32;
using VectorType = __m128;
static const size_t data_count = 4;
static VectorType load(const ScalarType * in) { return _mm_loadu_ps(in); }
static VectorType load1(const ScalarType in) { return _mm_load1_ps(&in); }
static void store(ScalarType * out, VectorType val) { _mm_storeu_ps(out, val); }
static VectorType multiply(VectorType val, VectorType scale) { return _mm_mul_ps(val, scale); }
static VectorType divide(VectorType val, VectorType scale) { return _mm_div_ps(val, scale); }
template <RoundingMode mode>
static VectorType apply(VectorType val)
{
return _mm_round_ps(val, int(mode));
}
static VectorType prepare(size_t scale) { return load1(scale); }
};
template <>
class BaseFloatRoundingComputation<Float64>
{
public:
using ScalarType = Float64;
using VectorType = __m128d;
static const size_t data_count = 2;
static VectorType load(const ScalarType * in) { return _mm_loadu_pd(in); }
static VectorType load1(const ScalarType in) { return _mm_load1_pd(&in); }
static void store(ScalarType * out, VectorType val) { _mm_storeu_pd(out, val); }
static VectorType multiply(VectorType val, VectorType scale) { return _mm_mul_pd(val, scale); }
static VectorType divide(VectorType val, VectorType scale) { return _mm_div_pd(val, scale); }
template <RoundingMode mode>
static VectorType apply(VectorType val)
{
return _mm_round_pd(val, int(mode));
}
static VectorType prepare(size_t scale) { return load1(scale); }
};
#else
/// Implementation for ARM. Not vectorized.
inline float roundWithMode(float x, RoundingMode mode)
{
switch (mode)
{
case RoundingMode::Round:
return roundf(x);
case RoundingMode::Floor:
return floorf(x);
case RoundingMode::Ceil:
return ceilf(x);
case RoundingMode::Trunc:
return truncf(x);
default:
throw Exception(
"Logical error: unexpected 'mode' parameter passed to function roundWithMode",
ErrorCodes::LOGICAL_ERROR);
}
}
inline double roundWithMode(double x, RoundingMode mode)
{
switch (mode)
{
case RoundingMode::Round:
return round(x);
case RoundingMode::Floor:
return floor(x);
case RoundingMode::Ceil:
return ceil(x);
case RoundingMode::Trunc:
return trunc(x);
default:
throw Exception(
"Logical error: unexpected 'mode' parameter passed to function roundWithMode",
ErrorCodes::LOGICAL_ERROR);
}
}
template <typename T>
class BaseFloatRoundingComputation
{
public:
using ScalarType = T;
using VectorType = T;
static const size_t data_count = 1;
static VectorType load(const ScalarType * in) { return *in; }
static VectorType load1(const ScalarType in) { return in; }
static VectorType store(ScalarType * out, ScalarType val) { return *out = val; }
static VectorType multiply(VectorType val, VectorType scale) { return val * scale; }
static VectorType divide(VectorType val, VectorType scale) { return val / scale; }
template <RoundingMode mode>
static VectorType apply(VectorType val)
{
return roundWithMode(val, mode);
}
static VectorType prepare(size_t scale) { return load1(scale); }
};
#endif
/** Implementation of low-level round-off functions for floating-point values.
*/
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode>
class FloatRoundingComputation : public BaseFloatRoundingComputation<T>
{
using Base = BaseFloatRoundingComputation<T>;
public:
static inline void compute(const T * __restrict in, const typename Base::VectorType & scale, T * __restrict out)
{
auto val = Base::load(in);
if (scale_mode == ScaleMode::Positive)
val = Base::multiply(val, scale);
else if (scale_mode == ScaleMode::Negative)
val = Base::divide(val, scale);
val = Base::template apply<rounding_mode>(val);
if (scale_mode == ScaleMode::Positive)
val = Base::divide(val, scale);
else if (scale_mode == ScaleMode::Negative)
val = Base::multiply(val, scale);
Base::store(out, val);
}
};
/** Implementing high-level rounding functions.
*/
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode>
struct FloatRoundingImpl
{
private:
using Op = FloatRoundingComputation<T, rounding_mode, scale_mode>;
using Data = std::array<T, Op::data_count>;
public:
static NO_INLINE void apply(const PaddedPODArray<T> & in, size_t scale, typename ColumnVector<T>::Container & out)
{
auto mm_scale = Op::prepare(scale);
const size_t data_count = std::tuple_size<Data>();
const T * end_in = in.data() + in.size();
const T * limit = in.data() + in.size() / data_count * data_count;
const T * __restrict p_in = in.data();
T * __restrict p_out = out.data();
while (p_in < limit)
{
Op::compute(p_in, mm_scale, p_out);
p_in += data_count;
p_out += data_count;
}
if (p_in < end_in)
{
Data tmp_src{{}};
Data tmp_dst;
size_t tail_size_bytes = (end_in - p_in) * sizeof(*p_in);
memcpy(&tmp_src, p_in, tail_size_bytes);
Op::compute(reinterpret_cast<T *>(&tmp_src), mm_scale, reinterpret_cast<T *>(&tmp_dst));
memcpy(p_out, &tmp_dst, tail_size_bytes);
}
}
};
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode>
struct IntegerRoundingImpl
{
private:
using Op = IntegerRoundingComputation<T, rounding_mode, scale_mode>;
using Data = T;
public:
template <size_t scale>
static NO_INLINE void applyImpl(const PaddedPODArray<T> & in, typename ColumnVector<T>::Container & out)
{
const T * end_in = in.data() + in.size();
const T * __restrict p_in = in.data();
T * __restrict p_out = out.data();
while (p_in < end_in)
{
Op::compute(p_in, static_cast<T>(scale), p_out);
++p_in;
++p_out;
}
}
static NO_INLINE void apply(const PaddedPODArray<T> & in, size_t scale, typename ColumnVector<T>::Container & out)
{
/// Manual function cloning for compiler to generate integer division by constant.
switch (scale)
{
case 1ULL:
return applyImpl<1ULL>(in, out);
case 10ULL:
return applyImpl<10ULL>(in, out);
case 100ULL:
return applyImpl<100ULL>(in, out);
case 1000ULL:
return applyImpl<1000ULL>(in, out);
case 10000ULL:
return applyImpl<10000ULL>(in, out);
case 100000ULL:
return applyImpl<100000ULL>(in, out);
case 1000000ULL:
return applyImpl<1000000ULL>(in, out);
case 10000000ULL:
return applyImpl<10000000ULL>(in, out);
case 100000000ULL:
return applyImpl<100000000ULL>(in, out);
case 1000000000ULL:
return applyImpl<1000000000ULL>(in, out);
case 10000000000ULL:
return applyImpl<10000000000ULL>(in, out);
case 100000000000ULL:
return applyImpl<100000000000ULL>(in, out);
case 1000000000000ULL:
return applyImpl<1000000000000ULL>(in, out);
case 10000000000000ULL:
return applyImpl<10000000000000ULL>(in, out);
case 100000000000000ULL:
return applyImpl<100000000000000ULL>(in, out);
case 1000000000000000ULL:
return applyImpl<1000000000000000ULL>(in, out);
case 10000000000000000ULL:
return applyImpl<10000000000000000ULL>(in, out);
case 100000000000000000ULL:
return applyImpl<100000000000000000ULL>(in, out);
case 1000000000000000000ULL:
return applyImpl<1000000000000000000ULL>(in, out);
case 10000000000000000000ULL:
return applyImpl<10000000000000000000ULL>(in, out);
default:
throw Exception(
"Logical error: unexpected 'scale' parameter passed to function IntegerRoundingComputation::compute",
ErrorCodes::LOGICAL_ERROR);
}
}
};
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode, typename OutputType>
struct DecimalRoundingImpl;
// We may need round decimal to other types, currently the only choice is Int64
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode>
struct DecimalRoundingImpl<T, rounding_mode, scale_mode, Int64>
{
static_assert(IsDecimal<T>);
using NativeType = typename T::NativeType;
private:
using Op = DecimalRoundingComputation<T, rounding_mode, scale_mode, Int64>;
using Data = T;
public:
static NO_INLINE void apply(
const DecimalPaddedPODArray<T> & in,
size_t scale,
typename ColumnVector<Int64>::Container & out)
{
ScaleType in_scale = in.getScale();
auto decimal_scale = intExp10OfSize<NativeType>(in_scale);
const T * end_in = in.data() + in.size();
const T * __restrict p_in = in.data();
Int64 * __restrict p_out = out.data();
while (p_in < end_in)
{
Op::compute(p_in, scale, p_out, decimal_scale);
++p_in;
++p_out;
}
}
};
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode>
struct DecimalRoundingImpl<T, rounding_mode, scale_mode, T>
{
static_assert(IsDecimal<T>);
using NativeType = typename T::NativeType;
private:
using Op = DecimalRoundingComputation<T, rounding_mode, scale_mode, T>;
using Data = T;
public:
static NO_INLINE void apply(
const DecimalPaddedPODArray<T> & in,
size_t scale,
typename ColumnDecimal<T>::Container & out)
{
ScaleType in_scale = in.getScale();
auto decimal_scale = intExp10OfSize<NativeType>(in_scale);
const T * end_in = in.data() + in.size();
const T * __restrict p_in = in.data();
T * __restrict p_out = out.data();
while (p_in < end_in)
{
Op::compute(p_in, scale, p_out, decimal_scale);
++p_in;
++p_out;
}
}
};
template <typename T, RoundingMode rounding_mode, ScaleMode scale_mode, typename OutputType = T>
using FunctionRoundingImpl = std::conditional_t<
std::is_floating_point_v<T>,
FloatRoundingImpl<T, rounding_mode, scale_mode>,
std::conditional_t<
std::is_integral_v<T>,
IntegerRoundingImpl<T, rounding_mode, scale_mode>,
DecimalRoundingImpl<T, rounding_mode, scale_mode, OutputType>>>;
/** Select the appropriate processing algorithm depending on the scale and OutputType
*/
template <typename T, RoundingMode rounding_mode, typename OutputType = T>
struct Dispatcher
{
template <typename Col>
static void apply(Block & block, const Col * col, const ColumnNumbers & arguments, size_t result)
{
static_assert(std::is_same_v<Col, ColumnVector<T>> || std::is_same_v<Col, ColumnDecimal<T>>);
Int64 scale_arg = 0;
if (arguments.size() == 2)
{
const IColumn & scale_column = *block.getByPosition(arguments[1]).column;
if (!scale_column.isColumnConst())
throw Exception("Scale argument for rounding functions must be constant.", ErrorCodes::ILLEGAL_COLUMN);
Field scale_field = static_cast<const ColumnConst &>(scale_column).getField();
if (scale_field.getType() != Field::Types::UInt64 && scale_field.getType() != Field::Types::Int64)
throw Exception(
"Scale argument for rounding functions must have integer type.",
ErrorCodes::ILLEGAL_COLUMN);
scale_arg = scale_field.get<Int64>();
}
if constexpr (IsDecimal<OutputType>)
{
UInt32 res_scale = 0;
if constexpr (rounding_mode == RoundingMode::Round || rounding_mode == RoundingMode::Trunc)
{
res_scale = col->getData().getScale();
}
auto col_res = ColumnDecimal<OutputType>::create(col->getData().size(), res_scale);
typename ColumnDecimal<OutputType>::Container & vec_res = col_res->getData();
applyInternal(col, vec_res, col_res, block, scale_arg, result);
}
else
{
auto col_res = ColumnVector<OutputType>::create();
typename ColumnVector<OutputType>::Container & vec_res = col_res->getData();
applyInternal(col, vec_res, col_res, block, scale_arg, result);
}
}
private:
template <typename VecRes, typename ColRes, typename Col>
static void applyInternal(
const Col * col,
VecRes & vec_res,
ColRes & col_res,
Block & block,
Int64 scale_arg,
size_t result)
{
size_t scale = 1;
vec_res.resize(col->getData().size());
if (vec_res.empty())
{
block.getByPosition(result).column = std::move(col_res);
return;
}
if (scale_arg == 0)
{
scale = 1;
FunctionRoundingImpl<T, rounding_mode, ScaleMode::Zero, OutputType>::apply(col->getData(), scale, vec_res);
}
else if (scale_arg > 0)
{
scale = pow(10, scale_arg);
FunctionRoundingImpl<T, rounding_mode, ScaleMode::Positive, OutputType>::apply(
col->getData(),
scale,
vec_res);
}
else
{
scale = pow(10, -scale_arg);
FunctionRoundingImpl<T, rounding_mode, ScaleMode::Negative, OutputType>::apply(
col->getData(),
scale,
vec_res);
}
block.getByPosition(result).column = std::move(col_res);
}
};
/** A template for functions that round the value of an input parameter of type
* (U)Int8/16/32/64 or Float32/64, and accept an additional optional
* parameter (default is 0).
*/
template <typename Name, RoundingMode rounding_mode>
class FunctionRounding : public IFunction
{
public:
static constexpr auto name = Name::name;
static FunctionPtr create(const Context &) { return std::make_shared<FunctionRounding>(); }
private:
template <typename T>
bool executeForType(Block & block, const ColumnNumbers & arguments, size_t result) const
{
if constexpr (IsDecimal<T>)
{
if (auto col = checkAndGetColumn<ColumnDecimal<T>>(block.getByPosition(arguments[0]).column.get()))
{
Dispatcher<T, rounding_mode>::apply(block, col, arguments, result);
return true;
}
return false;
}
else
{
if (auto col = checkAndGetColumn<ColumnVector<T>>(block.getByPosition(arguments[0]).column.get()))
{
Dispatcher<T, rounding_mode>::apply(block, col, arguments, result);
return true;
}
return false;
}
}
public:
String getName() const override { return name; }
bool isVariadic() const override { return true; }
size_t getNumberOfArguments() const override { return 0; }
/// Get result types by argument types. If the function does not apply to these arguments, throw an exception.
DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{
if ((arguments.empty()) || (arguments.size() > 2))
throw Exception(
fmt::format(
"Number of arguments for function {} doesn't match: passed {}, should be 1 or 2.",
getName(),
arguments.size()),
ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
for (const auto & type : arguments)
if (!type->isNumber() && !type->isDecimal())
throw Exception(
fmt::format("Illegal type {} of argument of function {}", arguments[0]->getName(), getName()),
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
if constexpr (rounding_mode == RoundingMode::Ceil || rounding_mode == RoundingMode::Floor)
{
if (arguments[0]->isDecimal())
{
if (const auto * decimal_type32 = checkAndGetDataType<DataTypeDecimal32>(arguments[0].get()))
return std::make_shared<DataTypeDecimal32>(decimal_type32->getPrec(), 0);
else if (const auto * decimal_type64 = checkAndGetDataType<DataTypeDecimal64>(arguments[0].get()))
return std::make_shared<DataTypeDecimal64>(decimal_type64->getPrec(), 0);
else if (const auto * decimal_type128 = checkAndGetDataType<DataTypeDecimal128>(arguments[0].get()))
return std::make_shared<DataTypeDecimal128>(decimal_type128->getPrec(), 0);
else if (const auto * decimal_type256 = checkAndGetDataType<DataTypeDecimal256>(arguments[0].get()))
return std::make_shared<DataTypeDecimal256>(decimal_type256->getPrec(), 0);
}
}
return arguments[0];
}
bool useDefaultImplementationForConstants() const override { return true; }
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1}; }
void executeImpl(Block & block, const ColumnNumbers & arguments, size_t result) const override
{
if (!(executeForType<UInt8>(block, arguments, result) || executeForType<UInt16>(block, arguments, result)
|| executeForType<UInt32>(block, arguments, result) || executeForType<UInt64>(block, arguments, result)
|| executeForType<Int8>(block, arguments, result) || executeForType<Int16>(block, arguments, result)
|| executeForType<Int32>(block, arguments, result) || executeForType<Int64>(block, arguments, result)
|| executeForType<Float32>(block, arguments, result) || executeForType<Float64>(block, arguments, result)
|| executeForType<Decimal32>(block, arguments, result)
|| executeForType<Decimal64>(block, arguments, result)
|| executeForType<Decimal128>(block, arguments, result)
|| executeForType<Decimal256>(block, arguments, result)))
{
throw Exception(
fmt::format(
"Illegal column {} of argument of function {}",
block.getByPosition(arguments[0]).column->getName(),
getName()),
ErrorCodes::ILLEGAL_COLUMN);
}
}
bool hasInformationAboutMonotonicity() const override { return true; }
Monotonicity getMonotonicityForRange(const IDataType &, const Field &, const Field &) const override
{
return {true, true, true};
}
};
/** FunctionRounding can only cast typeA to typeA
* but TiDB may push down RoundDecimalToInt
* (and this is the only round function that return type is different from arg type)
* so we specialize RoundDecimalToInt and not use template
*/
template <typename Name, RoundingMode rounding_mode>
class FunctionRoundingDecimalToInt : public IFunction
{
public:
static constexpr auto name = Name::name;
static FunctionPtr create(const Context &) { return std::make_shared<FunctionRoundingDecimalToInt>(); }
private:
template <typename T>
bool executeForType(Block & block, const ColumnNumbers & arguments, size_t result) const
{
static_assert(IsDecimal<T>);
if (auto col = checkAndGetColumn<ColumnDecimal<T>>(block.getByPosition(arguments[0]).column.get()))
{
Dispatcher<T, rounding_mode, Int64>::apply(block, col, arguments, result);
return true;
}
return false;
}
public:
String getName() const override { return name; }
bool isVariadic() const override { return true; }
size_t getNumberOfArguments() const override { return 0; }
DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{
if ((arguments.empty()) || (arguments.size() > 2))
throw Exception(
fmt::format(
"Number of arguments for function {} doesn't match: passed {}, should be 1 or 2.",
getName(),
arguments.size()),
ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
for (const auto & type : arguments)
if (!type->isDecimal())
throw Exception(
fmt::format("Illegal type {} of argument of function {}", arguments[0]->getName(), getName()),
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
return std::make_shared<DataTypeInt64>();
}
bool useDefaultImplementationForConstants() const override { return true; }
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1}; }
void executeImpl(Block & block, const ColumnNumbers & arguments, size_t result) const override
{
if (!(executeForType<Decimal32>(block, arguments, result) || executeForType<Decimal64>(block, arguments, result)
|| executeForType<Decimal128>(block, arguments, result)
|| executeForType<Decimal256>(block, arguments, result)))
{
throw Exception(
fmt::format(
"Illegal column {} of argument of function {}",
block.getByPosition(arguments[0]).column->getName(),
getName()),
ErrorCodes::ILLEGAL_COLUMN);
}
}
bool hasInformationAboutMonotonicity() const override { return true; }
Monotonicity getMonotonicityForRange(const IDataType &, const Field &, const Field &) const override
{
return {true, true, true};
}
};
/**
* differences between prec/scale/frac:
* - prec/precision: number of decimal digits, including digits before and after decimal point.
* - scale: number of decimal digits after decimal point.
* - frac: the second argument of ROUND.
* - optional, and default to zero.
* - in MySQL, frac <= 30, which is decimal_max_scale.
*
* both prec and scale are non-negative, but frac can be negative.
*/
using FracType = Int64;
// build constant table of up to Nth power of 10 at compile time.
template <typename T, size_t N>
struct ConstPowOf10
{
using ArrayType = std::array<T, N + 1>;
static constexpr T base = static_cast<T>(10);
static constexpr std::pair<ArrayType, bool> build()
{
ArrayType result{1};
bool overflow = false;
for (size_t i = 1; i <= N; ++i)
{
result[i] = result[i - 1] * base;
overflow |= (result[i - 1] != result[i] / base);
}
return {result, overflow};
}
static constexpr auto pair = build();
static constexpr auto result = pair.first;
static constexpr bool overflow = pair.second;
static_assert(!overflow, "Computation overflows");
};
template <typename InputType, typename OutputType>
struct TiDBFloatingRound
{
static_assert(std::is_floating_point_v<InputType>);
static_assert(std::is_floating_point_v<OutputType>);
static_assert(sizeof(OutputType) >= sizeof(InputType));
static OutputType eval(InputType input, FracType frac)
{
// modified from <https://github.com/pingcap/tidb/blob/26237b35f857c2388eab46f9ee3b351687143681/types/helper.go#L33-L48>.
auto value = static_cast<OutputType>(input);
auto base = 1.0;
if (frac != 0)