-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
mydecimal.go
2172 lines (2010 loc) · 53 KB
/
mydecimal.go
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 2016 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"math"
"strconv"
"github.com/juju/errors"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/terror"
)
// RoundMode is the type for round mode.
type RoundMode string
// constant values.
const (
ten0 = 1
ten1 = 10
ten2 = 100
ten3 = 1000
ten4 = 10000
ten5 = 100000
ten6 = 1000000
ten7 = 10000000
ten8 = 100000000
ten9 = 1000000000
maxWordBufLen = 9 // A MyDecimal holds 9 words.
digitsPerWord = 9 // A word holds 9 digits.
wordSize = 4 // A word is 4 bytes int32.
digMask = ten8
wordBase = ten9
wordMax = wordBase - 1
notFixedDec = 31
DivFracIncr = 4
// ModeHalfEven rounds normally.
ModeHalfEven RoundMode = "ModeHalfEven"
// Truncate just truncates the decimal.
ModeTruncate RoundMode = "Truncate"
// Ceiling is not supported now.
modeCeiling RoundMode = "Ceiling"
)
var (
wordBufLen = 9
powers10 = [10]int32{ten0, ten1, ten2, ten3, ten4, ten5, ten6, ten7, ten8, ten9}
dig2bytes = [10]int{0, 1, 1, 2, 2, 3, 3, 4, 4, 4}
fracMax = [8]int32{
900000000,
990000000,
999000000,
999900000,
999990000,
999999000,
999999900,
999999990,
}
zeroMyDecimal = MyDecimal{}
)
// add adds a and b and carry, returns the sum and new carry.
func add(a, b, carry int32) (int32, int32) {
sum := a + b + carry
if sum >= wordBase {
carry = 1
sum -= wordBase
} else {
carry = 0
}
return sum, carry
}
// sub subtracts b and carry from a, returns the diff and new carry.
func sub(a, b, carry int32) (int32, int32) {
diff := a - b - carry
if diff < 0 {
carry = 1
diff += wordBase
} else {
carry = 0
}
return diff, carry
}
// sub2 subtracts b and carry from a, returns the diff and new carry.
// the new carry may be 2.
func sub2(a, b, carry int32) (int32, int32) {
diff := a - b - carry
if diff < 0 {
carry = 1
diff += wordBase
} else {
carry = 0
}
if diff < 0 {
diff += wordBase
carry++
}
return diff, carry
}
// fixWordCntError limits word count in wordBufLen, and returns overflow or truncate error.
func fixWordCntError(wordsInt, wordsFrac int) (newWordsInt int, newWordsFrac int, err error) {
if wordsInt+wordsFrac > wordBufLen {
if wordsInt > wordBufLen {
return wordBufLen, 0, ErrOverflow
}
return wordsInt, wordBufLen - wordsInt, ErrTruncated
}
return wordsInt, wordsFrac, nil
}
/*
countLeadingZeroes returns the number of leading zeroes that can be removed from fraction.
@param i start index
@param word value to compare against list of powers of 10
*/
func countLeadingZeroes(i int, word int32) int {
leading := 0
for word < powers10[i] {
i--
leading++
}
return leading
}
/*
countTrailingZeros returns the number of trailing zeroes that can be removed from fraction.
@param i start index
@param word value to compare against list of powers of 10
*/
func countTrailingZeroes(i int, word int32) int {
trailing := 0
for word%powers10[i] == 0 {
i++
trailing++
}
return trailing
}
func digitsToWords(digits int) int {
return (digits + digitsPerWord - 1) / digitsPerWord
}
// MyDecimalStructSize is the struct size of MyDecimal.
const MyDecimalStructSize = 40
// MyDecimal represents a decimal value.
type MyDecimal struct {
digitsInt int8 // the number of *decimal* digits before the point.
digitsFrac int8 // the number of decimal digits after the point.
resultFrac int8 // result fraction digits.
negative bool
// wordBuf is an array of int32 words.
// A word is an int32 value can hold 9 digits.(0 <= word < wordBase)
wordBuf [maxWordBufLen]int32
}
// IsNegative returns whether a decimal is negative.
func (d *MyDecimal) IsNegative() bool {
return d.negative
}
// GetDigitsFrac returns the digitsFrac.
func (d *MyDecimal) GetDigitsFrac() int8 {
return d.digitsFrac
}
// String returns the decimal string representation rounded to resultFrac.
func (d *MyDecimal) String() string {
tmp := *d
err := tmp.Round(&tmp, int(tmp.resultFrac), ModeHalfEven)
terror.Log(errors.Trace(err))
return string(tmp.ToString())
}
func (d *MyDecimal) stringSize() int {
// sign, zero integer and dot.
return int(d.digitsInt + d.digitsFrac + 3)
}
func (d *MyDecimal) removeLeadingZeros() (wordIdx int, digitsInt int) {
digitsInt = int(d.digitsInt)
i := ((digitsInt - 1) % digitsPerWord) + 1
for digitsInt > 0 && d.wordBuf[wordIdx] == 0 {
digitsInt -= i
i = digitsPerWord
wordIdx++
}
if digitsInt > 0 {
digitsInt -= countLeadingZeroes((digitsInt-1)%digitsPerWord, d.wordBuf[wordIdx])
} else {
digitsInt = 0
}
return
}
// ToString converts decimal to its printable string representation without rounding.
//
// RETURN VALUE
//
// str - result string
// errCode - eDecOK/eDecTruncate/eDecOverflow
//
func (d *MyDecimal) ToString() (str []byte) {
str = make([]byte, d.stringSize())
digitsFrac := int(d.digitsFrac)
wordStartIdx, digitsInt := d.removeLeadingZeros()
if digitsInt+digitsFrac == 0 {
digitsInt = 1
wordStartIdx = 0
}
digitsIntLen := digitsInt
if digitsIntLen == 0 {
digitsIntLen = 1
}
digitsFracLen := digitsFrac
length := digitsIntLen + digitsFracLen
if d.negative {
length++
}
if digitsFrac > 0 {
length++
}
str = str[:length]
strIdx := 0
if d.negative {
str[strIdx] = '-'
strIdx++
}
var fill int
if digitsFrac > 0 {
fracIdx := strIdx + digitsIntLen
fill = digitsFracLen - digitsFrac
wordIdx := wordStartIdx + digitsToWords(digitsInt)
str[fracIdx] = '.'
fracIdx++
for ; digitsFrac > 0; digitsFrac -= digitsPerWord {
x := d.wordBuf[wordIdx]
wordIdx++
for i := myMin(digitsFrac, digitsPerWord); i > 0; i-- {
y := x / digMask
str[fracIdx] = byte(y) + '0'
fracIdx++
x -= y * digMask
x *= 10
}
}
for ; fill > 0; fill-- {
str[fracIdx] = '0'
fracIdx++
}
}
fill = digitsIntLen - digitsInt
if digitsInt == 0 {
fill-- /* symbol 0 before digital point */
}
for ; fill > 0; fill-- {
str[strIdx] = '0'
strIdx++
}
if digitsInt > 0 {
strIdx += digitsInt
wordIdx := wordStartIdx + digitsToWords(digitsInt)
for ; digitsInt > 0; digitsInt -= digitsPerWord {
wordIdx--
x := d.wordBuf[wordIdx]
for i := myMin(digitsInt, digitsPerWord); i > 0; i-- {
y := x / 10
strIdx--
str[strIdx] = '0' + byte(x-y*10)
x = y
}
}
} else {
str[strIdx] = '0'
}
return
}
// FromString parses decimal from string.
func (d *MyDecimal) FromString(str []byte) error {
for i := 0; i < len(str); i++ {
if !isSpace(str[i]) {
str = str[i:]
break
}
}
if len(str) == 0 {
*d = zeroMyDecimal
return ErrBadNumber
}
switch str[0] {
case '-':
d.negative = true
fallthrough
case '+':
str = str[1:]
}
var strIdx int
for strIdx < len(str) && isDigit(str[strIdx]) {
strIdx++
}
digitsInt := strIdx
var digitsFrac int
var endIdx int
if strIdx < len(str) && str[strIdx] == '.' {
endIdx = strIdx + 1
for endIdx < len(str) && isDigit(str[endIdx]) {
endIdx++
}
digitsFrac = endIdx - strIdx - 1
} else {
digitsFrac = 0
endIdx = strIdx
}
if digitsInt+digitsFrac == 0 {
*d = zeroMyDecimal
return ErrBadNumber
}
wordsInt := digitsToWords(digitsInt)
wordsFrac := digitsToWords(digitsFrac)
wordsInt, wordsFrac, err := fixWordCntError(wordsInt, wordsFrac)
if err != nil {
digitsFrac = wordsFrac * digitsPerWord
if err == ErrOverflow {
digitsInt = wordsInt * digitsPerWord
}
}
d.digitsInt = int8(digitsInt)
d.digitsFrac = int8(digitsFrac)
wordIdx := wordsInt
strIdxTmp := strIdx
var word int32
var innerIdx int
for digitsInt > 0 {
digitsInt--
strIdx--
word += int32(str[strIdx]-'0') * powers10[innerIdx]
innerIdx++
if innerIdx == digitsPerWord {
wordIdx--
d.wordBuf[wordIdx] = word
word = 0
innerIdx = 0
}
}
if innerIdx != 0 {
wordIdx--
d.wordBuf[wordIdx] = word
}
wordIdx = wordsInt
strIdx = strIdxTmp
word = 0
innerIdx = 0
for digitsFrac > 0 {
digitsFrac--
strIdx++
word = int32(str[strIdx]-'0') + word*10
innerIdx++
if innerIdx == digitsPerWord {
d.wordBuf[wordIdx] = word
wordIdx++
word = 0
innerIdx = 0
}
}
if innerIdx != 0 {
d.wordBuf[wordIdx] = word * powers10[digitsPerWord-innerIdx]
}
if endIdx+1 < len(str) && (str[endIdx] == 'e' || str[endIdx] == 'E') {
exponent, err1 := strToInt(string(str[endIdx+1:]))
// TODO: need a way to check if there is at least one digit.
if err1 != nil {
*d = zeroMyDecimal
return ErrBadNumber
}
if exponent > math.MaxInt32/2 {
*d = zeroMyDecimal
return ErrOverflow
}
if exponent < math.MinInt32/2 && err != ErrOverflow {
*d = zeroMyDecimal
return ErrTruncated
}
if err != ErrOverflow {
err = d.Shift(int(exponent))
}
}
allZero := true
for i := 0; i < wordBufLen; i++ {
if d.wordBuf[i] != 0 {
allZero = false
break
}
}
if allZero {
d.negative = false
}
d.resultFrac = d.digitsFrac
return err
}
// Shift shifts decimal digits in given number (with rounding if it need), shift > 0 means shift to left shift,
// shift < 0 means right shift. In fact it is multiplying on 10^shift.
//
// RETURN
// eDecOK OK
// eDecOverflow operation lead to overflow, number is untoched
// eDecTruncated number was rounded to fit into buffer
//
func (d *MyDecimal) Shift(shift int) error {
var err error
if shift == 0 {
return nil
}
var (
// digitBegin is index of first non zero digit (all indexes from 0).
digitBegin int
// digitEnd is index of position after last decimal digit.
digitEnd int
// point is index of digit position just after point.
point = digitsToWords(int(d.digitsInt)) * digitsPerWord
// new point position.
newPoint = point + shift
// number of digits in result.
digitsInt, digitsFrac int
newFront int
)
digitBegin, digitEnd = d.digitBounds()
if digitBegin == digitEnd {
*d = zeroMyDecimal
return nil
}
digitsInt = newPoint - digitBegin
if digitsInt < 0 {
digitsInt = 0
}
digitsFrac = digitEnd - newPoint
if digitsFrac < 0 {
digitsFrac = 0
}
wordsInt := digitsToWords(digitsInt)
wordsFrac := digitsToWords(digitsFrac)
newLen := wordsInt + wordsFrac
if newLen > wordBufLen {
lack := newLen - wordBufLen
if wordsFrac < lack {
return ErrOverflow
}
/* cut off fraction part to allow new number to fit in our buffer */
err = ErrTruncated
wordsFrac -= lack
diff := digitsFrac - wordsFrac*digitsPerWord
err1 := d.Round(d, digitEnd-point-diff, ModeHalfEven)
if err1 != nil {
return errors.Trace(err1)
}
digitEnd -= diff
digitsFrac = wordsFrac * digitsPerWord
if digitEnd <= digitBegin {
/*
We lost all digits (they will be shifted out of buffer), so we can
just return 0.
*/
*d = zeroMyDecimal
return ErrTruncated
}
}
if shift%digitsPerWord != 0 {
var lMiniShift, rMiniShift, miniShift int
var doLeft bool
/*
Calculate left/right shift to align decimal digits inside our bug
digits correctly.
*/
if shift > 0 {
lMiniShift = shift % digitsPerWord
rMiniShift = digitsPerWord - lMiniShift
doLeft = lMiniShift <= digitBegin
} else {
rMiniShift = (-shift) % digitsPerWord
lMiniShift = digitsPerWord - rMiniShift
doLeft = (digitsPerWord*wordBufLen - digitEnd) < rMiniShift
}
if doLeft {
d.doMiniLeftShift(lMiniShift, digitBegin, digitEnd)
miniShift = -lMiniShift
} else {
d.doMiniRightShift(rMiniShift, digitBegin, digitEnd)
miniShift = rMiniShift
}
newPoint += miniShift
/*
If number is shifted and correctly aligned in buffer we can finish.
*/
if shift+miniShift == 0 && (newPoint-digitsInt) < digitsPerWord {
d.digitsInt = int8(digitsInt)
d.digitsFrac = int8(digitsFrac)
return err /* already shifted as it should be */
}
digitBegin += miniShift
digitEnd += miniShift
}
/* if new 'decimal front' is in first digit, we do not need move digits */
newFront = newPoint - digitsInt
if newFront >= digitsPerWord || newFront < 0 {
/* need to move digits */
var wordShift int
if newFront > 0 {
/* move left */
wordShift = newFront / digitsPerWord
to := digitBegin/digitsPerWord - wordShift
barier := (digitEnd-1)/digitsPerWord - wordShift
for ; to <= barier; to++ {
d.wordBuf[to] = d.wordBuf[to+wordShift]
}
for barier += wordShift; to <= barier; to++ {
d.wordBuf[to] = 0
}
wordShift = -wordShift
} else {
/* move right */
wordShift = (1 - newFront) / digitsPerWord
to := (digitEnd-1)/digitsPerWord + wordShift
barier := digitBegin/digitsPerWord + wordShift
for ; to >= barier; to-- {
d.wordBuf[to] = d.wordBuf[to-wordShift]
}
for barier -= wordShift; to >= barier; to-- {
d.wordBuf[to] = 0
}
}
digitShift := wordShift * digitsPerWord
digitBegin += digitShift
digitEnd += digitShift
newPoint += digitShift
}
/*
If there are gaps then fill them with 0.
Only one of following 'for' loops will work because wordIdxBegin <= wordIdxEnd.
*/
wordIdxBegin := digitBegin / digitsPerWord
wordIdxEnd := (digitEnd - 1) / digitsPerWord
wordIdxNewPoint := 0
/* We don't want negative new_point below */
if newPoint != 0 {
wordIdxNewPoint = (newPoint - 1) / digitsPerWord
}
if wordIdxNewPoint > wordIdxEnd {
for wordIdxNewPoint > wordIdxEnd {
d.wordBuf[wordIdxNewPoint] = 0
wordIdxNewPoint--
}
} else {
for ; wordIdxNewPoint < wordIdxBegin; wordIdxNewPoint++ {
d.wordBuf[wordIdxNewPoint] = 0
}
}
d.digitsInt = int8(digitsInt)
d.digitsFrac = int8(digitsFrac)
return err
}
/*
digitBounds returns bounds of decimal digits in the number.
start - index (from 0 ) of first decimal digits.
end - index of position just after last decimal digit.
*/
func (d *MyDecimal) digitBounds() (start, end int) {
var i int
bufBeg := 0
bufLen := digitsToWords(int(d.digitsInt)) + digitsToWords(int(d.digitsFrac))
bufEnd := bufLen - 1
/* find non-zero digit from number beginning */
for bufBeg < bufLen && d.wordBuf[bufBeg] == 0 {
bufBeg++
}
if bufBeg >= bufLen {
return 0, 0
}
/* find non-zero decimal digit from number beginning */
if bufBeg == 0 && d.digitsInt > 0 {
i = (int(d.digitsInt) - 1) % digitsPerWord
start = digitsPerWord - i - 1
} else {
i = digitsPerWord - 1
start = bufBeg * digitsPerWord
}
if bufBeg < bufLen {
start += countLeadingZeroes(i, d.wordBuf[bufBeg])
}
/* find non-zero digit at the end */
for bufEnd > bufBeg && d.wordBuf[bufEnd] == 0 {
bufEnd--
}
/* find non-zero decimal digit from the end */
if bufEnd == bufLen-1 && d.digitsFrac > 0 {
i = (int(d.digitsFrac)-1)%digitsPerWord + 1
end = bufEnd*digitsPerWord + i
i = digitsPerWord - i + 1
} else {
end = (bufEnd + 1) * digitsPerWord
i = 1
}
end -= countTrailingZeroes(i, d.wordBuf[bufEnd])
return start, end
}
/*
doMiniLeftShift does left shift for alignment of data in buffer.
shift number of decimal digits on which it should be shifted
beg/end bounds of decimal digits (see digitsBounds())
NOTE
Result fitting in the buffer should be garanted.
'shift' have to be from 1 to digitsPerWord-1 (inclusive)
*/
func (d *MyDecimal) doMiniLeftShift(shift, beg, end int) {
bufFrom := beg / digitsPerWord
bufEnd := (end - 1) / digitsPerWord
cShift := digitsPerWord - shift
if beg%digitsPerWord < shift {
d.wordBuf[bufFrom-1] = d.wordBuf[bufFrom] / powers10[cShift]
}
for bufFrom < bufEnd {
d.wordBuf[bufFrom] = (d.wordBuf[bufFrom]%powers10[cShift])*powers10[shift] + d.wordBuf[bufFrom+1]/powers10[cShift]
bufFrom++
}
d.wordBuf[bufFrom] = (d.wordBuf[bufFrom] % powers10[cShift]) * powers10[shift]
}
/*
doMiniRightShift does right shift for alignment of data in buffer.
shift number of decimal digits on which it should be shifted
beg/end bounds of decimal digits (see digitsBounds())
NOTE
Result fitting in the buffer should be garanted.
'shift' have to be from 1 to digitsPerWord-1 (inclusive)
*/
func (d *MyDecimal) doMiniRightShift(shift, beg, end int) {
bufFrom := (end - 1) / digitsPerWord
bufEnd := beg / digitsPerWord
cShift := digitsPerWord - shift
if digitsPerWord-((end-1)%digitsPerWord+1) < shift {
d.wordBuf[bufFrom+1] = (d.wordBuf[bufFrom] % powers10[shift]) * powers10[cShift]
}
for bufFrom > bufEnd {
d.wordBuf[bufFrom] = d.wordBuf[bufFrom]/powers10[shift] + (d.wordBuf[bufFrom-1]%powers10[shift])*powers10[cShift]
bufFrom--
}
d.wordBuf[bufFrom] = d.wordBuf[bufFrom] / powers10[shift]
}
// Round rounds the decimal to "frac" digits.
//
// to - result buffer. d == to is allowed
// frac - to what position after fraction point to round. can be negative!
// roundMode - round to nearest even or truncate
// ModeHalfEven rounds normally.
// Truncate just truncates the decimal.
//
// NOTES
// scale can be negative !
// one TRUNCATED error (line XXX below) isn't treated very logical :(
//
// RETURN VALUE
// eDecOK/eDecTruncated
func (d *MyDecimal) Round(to *MyDecimal, frac int, roundMode RoundMode) (err error) {
if frac > mysql.MaxDecimalScale {
frac = mysql.MaxDecimalScale
}
// wordsFracTo is the number of fraction words in buffer.
wordsFracTo := (frac + 1) / digitsPerWord
if frac > 0 {
wordsFracTo = digitsToWords(frac)
}
wordsFrac := digitsToWords(int(d.digitsFrac))
wordsInt := digitsToWords(int(d.digitsInt))
var roundDigit int32
/* TODO - fix this code as it won't work for CEILING mode */
switch roundMode {
case modeCeiling:
roundDigit = 0
case ModeHalfEven:
roundDigit = 5
case ModeTruncate:
roundDigit = 10
}
if wordsInt+wordsFracTo > wordBufLen {
wordsFracTo = wordBufLen - wordsInt
frac = wordsFracTo * digitsPerWord
err = ErrTruncated
}
if int(d.digitsInt)+frac < 0 {
*to = zeroMyDecimal
return nil
}
if to != d {
copy(to.wordBuf[:], d.wordBuf[:])
to.negative = d.negative
to.digitsInt = int8(myMin(wordsInt, wordBufLen) * digitsPerWord)
}
if wordsFracTo > wordsFrac {
idx := wordsInt + wordsFrac
for wordsFracTo > wordsFrac {
wordsFracTo--
to.wordBuf[idx] = 0
idx++
}
to.digitsFrac = int8(frac)
to.resultFrac = to.digitsFrac
return
}
if frac >= int(d.digitsFrac) {
to.digitsFrac = int8(frac)
to.resultFrac = to.digitsFrac
return
}
// Do increment.
toIdx := wordsInt + wordsFracTo - 1
if frac == wordsFracTo*digitsPerWord {
doInc := false
switch roundDigit {
// Notice: No support for ceiling mode now.
case 0:
// If any word after scale is not zero, do increment.
// e.g ceiling 3.0001 to scale 1, gets 3.1
idx := toIdx + (wordsFrac - wordsFracTo)
for idx > toIdx {
if d.wordBuf[idx] != 0 {
doInc = true
break
}
idx--
}
case 5:
digAfterScale := d.wordBuf[toIdx+1] / digMask // the first digit after scale.
// If first digit after scale is 5 and round even, do increment if digit at scale is odd.
doInc = (digAfterScale > 5) || (digAfterScale == 5)
case 10:
// Never round, just truncate.
doInc = false
}
if doInc {
if toIdx >= 0 {
to.wordBuf[toIdx]++
} else {
toIdx++
to.wordBuf[toIdx] = wordBase
}
} else if wordsInt+wordsFracTo == 0 {
*to = zeroMyDecimal
return nil
}
} else {
/* TODO - fix this code as it won't work for CEILING mode */
pos := wordsFracTo*digitsPerWord - frac - 1
shiftedNumber := to.wordBuf[toIdx] / powers10[pos]
digAfterScale := shiftedNumber % 10
if digAfterScale > roundDigit || (roundDigit == 5 && digAfterScale == 5) {
shiftedNumber += 10
}
to.wordBuf[toIdx] = powers10[pos] * (shiftedNumber - digAfterScale)
}
/*
In case we're rounding e.g. 1.5e9 to 2.0e9, the decimal words inside
the buffer are as follows.
Before <1, 5e8>
After <2, 5e8>
Hence we need to set the 2nd field to 0.
The same holds if we round 1.5e-9 to 2e-9.
*/
if wordsFracTo < wordsFrac {
idx := wordsInt + wordsFracTo
if frac == 0 && wordsInt == 0 {
idx = 1
}
for idx < wordBufLen {
to.wordBuf[idx] = 0
idx++
}
}
// Handle carry.
var carry int32
if to.wordBuf[toIdx] >= wordBase {
carry = 1
to.wordBuf[toIdx] -= wordBase
for carry == 1 && toIdx > 0 {
toIdx--
to.wordBuf[toIdx], carry = add(to.wordBuf[toIdx], 0, carry)
}
if carry > 0 {
if wordsInt+wordsFracTo >= wordBufLen {
wordsFracTo--
frac = wordsFracTo * digitsPerWord
err = ErrTruncated
}
for toIdx = wordsInt + myMax(wordsFracTo, 0); toIdx > 0; toIdx-- {
if toIdx < wordBufLen {
to.wordBuf[toIdx] = to.wordBuf[toIdx-1]
} else {
err = ErrOverflow
}
}
to.wordBuf[toIdx] = 1
/* We cannot have more than 9 * 9 = 81 digits. */
if int(to.digitsInt) < digitsPerWord*wordBufLen {
to.digitsInt++
} else {
err = ErrOverflow
}
}
} else {
for {
if to.wordBuf[toIdx] != 0 {
break
}
if toIdx == 0 {
/* making 'zero' with the proper scale */
idx := wordsFracTo + 1
to.digitsInt = 1
to.digitsFrac = int8(myMax(frac, 0))
to.negative = false
for toIdx < idx {
to.wordBuf[toIdx] = 0
toIdx++
}
to.resultFrac = to.digitsFrac
return nil
}
toIdx--
}
}
/* Here we check 999.9 -> 1000 case when we need to increase intDigCnt */
firstDig := to.digitsInt % digitsPerWord
if firstDig > 0 && to.wordBuf[toIdx] >= powers10[firstDig] {
to.digitsInt++
}
if frac < 0 {
frac = 0
}
to.digitsFrac = int8(frac)
to.resultFrac = to.digitsFrac
return
}
// FromInt sets the decimal value from int64.
func (d *MyDecimal) FromInt(val int64) *MyDecimal {
var uVal uint64
if val < 0 {
d.negative = true
uVal = uint64(-val)
} else {
uVal = uint64(val)
}
return d.FromUint(uVal)
}
// FromUint sets the decimal value from uint64.
func (d *MyDecimal) FromUint(val uint64) *MyDecimal {
x := val
wordIdx := 1
for x >= wordBase {
wordIdx++
x /= wordBase
}
d.digitsFrac = 0
d.digitsInt = int8(wordIdx * digitsPerWord)
x = val
for wordIdx > 0 {
wordIdx--
y := x / wordBase
d.wordBuf[wordIdx] = int32(x - y*wordBase)
x = y
}
return d
}
// ToInt returns int part of the decimal, returns the result and errcode.
func (d *MyDecimal) ToInt() (int64, error) {
var x int64
wordIdx := 0
for i := d.digitsInt; i > 0; i -= digitsPerWord {
y := x
/*
Attention: trick!
we're calculating -|from| instead of |from| here
because |LONGLONG_MIN| > LONGLONG_MAX
so we can convert -9223372036854775808 correctly
*/
x = x*wordBase - int64(d.wordBuf[wordIdx])
wordIdx++
if y < math.MinInt64/wordBase || x > y {
/*
the decimal is bigger than any possible integer
return border integer depending on the sign
*/
if d.negative {
return math.MinInt64, ErrOverflow
}
return math.MaxInt64, ErrOverflow
}
}
/* boundary case: 9223372036854775808 */
if !d.negative && x == math.MinInt64 {
return math.MaxInt64, ErrOverflow
}
if !d.negative {
x = -x
}
for i := d.digitsFrac; i > 0; i -= digitsPerWord {
if d.wordBuf[wordIdx] != 0 {
return x, ErrTruncated
}
wordIdx++
}
return x, nil
}
// ToUint returns int part of the decimal, returns the result and errcode.
func (d *MyDecimal) ToUint() (uint64, error) {
if d.negative {
return 0, ErrOverflow
}
var x uint64
wordIdx := 0
for i := d.digitsInt; i > 0; i -= digitsPerWord {
y := x
x = x*wordBase + uint64(d.wordBuf[wordIdx])
wordIdx++
if y > math.MaxUint64/wordBase || x < y {
return math.MaxUint64, ErrOverflow
}
}
for i := d.digitsFrac; i > 0; i -= digitsPerWord {
if d.wordBuf[wordIdx] != 0 {
return x, ErrTruncated
}
wordIdx++
}
return x, nil
}
// FromFloat64 creates a decimal from float64 value.
func (d *MyDecimal) FromFloat64(f float64) error {
s := strconv.FormatFloat(f, 'g', -1, 64)
return d.FromString([]byte(s))
}
// ToFloat64 converts decimal to float64 value.
func (d *MyDecimal) ToFloat64() (float64, error) {
f, err := strconv.ParseFloat(d.String(), 64)
if err != nil {
err = ErrOverflow
}
return f, err
}