-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdecimal.go
3515 lines (3061 loc) · 88.1 KB
/
decimal.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
package decimal
import (
"database/sql/driver"
"errors"
"fmt"
"math"
"strconv"
"unsafe"
)
// Decimal represents a finite floating-point decimal number.
// Its zero value corresponds to the numeric value of 0.
// Decimal is designed to be safe for concurrent use by multiple goroutines.
type Decimal struct {
neg bool // indicates whether the decimal is negative
scale int8 // position of the floating decimal point
coef fint // numeric value without decimal point
}
const (
MaxPrec = 19 // MaxPrec is the maximum length of the coefficient in decimal digits.
MinScale = 0 // MinScale is the minimum number of digits after the decimal point.
MaxScale = 19 // MaxScale is the maximum number of digits after the decimal point.
maxCoef = maxFint // maxCoef is the maximum absolute value of the coefficient, which is equal to (10^MaxPrec - 1).
)
var (
NegOne = MustNew(-1, 0) // NegOne represents the decimal value of -1.
Zero = MustNew(0, 0) // Zero represents the decimal value of 0. For comparison purposes, use the IsZero method.
One = MustNew(1, 0) // One represents the decimal value of 1.
Two = MustNew(2, 0) // Two represents the decimal value of 2.
Ten = MustNew(10, 0) // Ten represents the decimal value of 10.
Hundred = MustNew(100, 0) // Hundred represents the decimal value of 100.
Thousand = MustNew(1_000, 0) // Thousand represents the decimal value of 1,000.
E = MustNew(2_718_281_828_459_045_235, 18) // E represents Euler’s number rounded to 18 digits.
Pi = MustNew(3_141_592_653_589_793_238, 18) // Pi represents the value of π rounded to 18 digits.
errDecimalOverflow = errors.New("decimal overflow")
errInvalidDecimal = errors.New("invalid decimal")
errScaleRange = errors.New("scale out of range")
errInvalidOperation = errors.New("invalid operation")
errInexactDivision = errors.New("inexact division")
errDivisionByZero = errors.New("division by zero")
)
// newUnsafe creates a new decimal without checking the scale and coefficient.
// Use it only if you are absolutely sure that the arguments are valid.
func newUnsafe(neg bool, coef fint, scale int) Decimal {
if coef == 0 {
neg = false
}
//nolint:gosec
return Decimal{neg: neg, coef: coef, scale: int8(scale)}
}
// newSafe creates a new decimal and checks the scale and coefficient.
func newSafe(neg bool, coef fint, scale int) (Decimal, error) {
switch {
case scale < MinScale || scale > MaxScale:
return Decimal{}, errScaleRange
case coef > maxCoef:
return Decimal{}, errDecimalOverflow
}
return newUnsafe(neg, coef, scale), nil
}
// newFromFint creates a new decimal from a uint64 coefficient.
// This method does not use overflowError to return descriptive errors,
// as it must be as fast as possible.
func newFromFint(neg bool, coef fint, scale, minScale int) (Decimal, error) {
var ok bool
// Scale normalization
switch {
case scale < minScale:
coef, ok = coef.lsh(minScale - scale)
if !ok {
return Decimal{}, errDecimalOverflow
}
scale = minScale
case scale > MaxScale:
coef = coef.rshHalfEven(scale - MaxScale)
scale = MaxScale
}
return newSafe(neg, coef, scale)
}
// newFromBint creates a new decimal from a *big.Int coefficient.
// This method uses overflowError to return descriptive errors.
func newFromBint(neg bool, coef *bint, scale, minScale int) (Decimal, error) {
// Overflow validation
prec := coef.prec()
if prec-scale > MaxPrec-minScale {
return Decimal{}, overflowError(prec, scale, minScale)
}
// Scale normalization
switch {
case scale < minScale:
coef.lsh(coef, minScale-scale)
scale = minScale
case scale >= prec && scale > MaxScale: // no integer part
coef.rshHalfEven(coef, scale-MaxScale)
scale = MaxScale
case prec > scale && prec > MaxPrec: // there is an integer part
coef.rshHalfEven(coef, prec-MaxPrec)
scale = MaxPrec - prec + scale
}
// Handling the rare case when rshHalfEven rounded
// a 19-digit coefficient to a 20-digit coefficient.
if coef.hasPrec(MaxPrec + 1) {
return newFromBint(neg, coef, scale, minScale)
}
return newSafe(neg, coef.fint(), scale)
}
func overflowError(gotPrec, gotScale, wantScale int) error {
maxDigits := MaxPrec - wantScale
gotDigits := gotPrec - gotScale
switch wantScale {
case 0:
return fmt.Errorf("%w: the integer part of a %T can have at most %v digits, but it has %v digits", errDecimalOverflow, Decimal{}, maxDigits, gotDigits)
default:
return fmt.Errorf("%w: with %v significant digits after the decimal point, the integer part of a %T can have at most %v digits, but it has %v digits", errDecimalOverflow, wantScale, Decimal{}, maxDigits, gotDigits)
}
}
func unknownOverflowError() error {
return fmt.Errorf("%w: the integer part of a %T can have at most %v digits, but it has significantly more digits", errDecimalOverflow, Decimal{}, MaxPrec)
}
// MustNew is like [New] but panics if the decimal cannot be constructed.
// It simplifies safe initialization of global variables holding decimals.
func MustNew(value int64, scale int) Decimal {
d, err := New(value, scale)
if err != nil {
panic(fmt.Sprintf("New(%v, %v) failed: %v", value, scale, err))
}
return d
}
// New returns a decimal equal to value / 10^scale.
// New keeps trailing zeros in the fractional part to preserve scale.
//
// New returns an error if the scale is negative or greater than [MaxScale].
func New(value int64, scale int) (Decimal, error) {
var coef fint
var neg bool
if value >= 0 {
neg = false
coef = fint(value)
} else {
neg = true
if value == math.MinInt64 {
coef = fint(math.MaxInt64) + 1
} else {
coef = fint(-value)
}
}
return newSafe(neg, coef, scale)
}
// NewFromInt64 converts a pair of integers, representing the whole and
// fractional parts, to a (possibly rounded) decimal equal to whole + frac / 10^scale.
// NewFromInt64 removes all trailing zeros from the fractional part.
// This method is useful for converting amounts from [protobuf] format.
// See also method [Decimal.Int64].
//
// NewFromInt64 returns an error if:
// - the whole and fractional parts have different signs;
// - the scale is negative or greater than [MaxScale];
// - frac / 10^scale is not within the range (-1, 1).
//
// [protobuf]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto
func NewFromInt64(whole, frac int64, scale int) (Decimal, error) {
// Whole
d, err := New(whole, 0)
if err != nil {
return Decimal{}, fmt.Errorf("converting integers: %w", err) // should never happen
}
// Fraction
f, err := New(frac, scale)
if err != nil {
return Decimal{}, fmt.Errorf("converting integers: %w", err)
}
if !f.IsZero() {
if !d.IsZero() && d.Sign() != f.Sign() {
return Decimal{}, fmt.Errorf("converting integers: inconsistent signs")
}
if !f.WithinOne() {
return Decimal{}, fmt.Errorf("converting integers: inconsistent fraction")
}
f = f.Trim(0)
d, err = d.Add(f)
if err != nil {
return Decimal{}, fmt.Errorf("converting integers: %w", err) // should never happen
}
}
return d, nil
}
// Int64 returns a pair of integers representing the whole and
// (possibly rounded) fractional parts of the decimal.
// If given scale is greater than the scale of the decimal, then the fractional part
// is zero-padded to the right.
// If given scale is smaller than the scale of the decimal, then the fractional part
// is rounded using [rounding half to even] (banker's rounding).
// The relationship between the decimal and the returned values can be expressed
// as d = whole + frac / 10^scale.
// This method is useful for converting amounts to [protobuf] format.
// See also constructor [NewFromInt64].
//
// If the result cannot be represented as a pair of int64 values,
// then false is returned.
//
// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even
// [protobuf]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto
func (d Decimal) Int64(scale int) (whole, frac int64, ok bool) {
if scale < MinScale || scale > MaxScale {
return 0, 0, false
}
x := d.coef
y := pow10[d.Scale()]
if scale < d.Scale() {
x = x.rshHalfEven(d.Scale() - scale)
y = pow10[scale]
}
q, r, ok := x.quoRem(y)
if !ok {
return 0, 0, false // Should never happen
}
if scale > d.Scale() {
r, ok = r.lsh(scale - d.Scale())
if !ok {
return 0, 0, false // Should never happen
}
}
if d.IsNeg() {
if q > -math.MinInt64 || r > -math.MinInt64 {
return 0, 0, false
}
//nolint:gosec
return -int64(q), -int64(r), true
}
if q > math.MaxInt64 || r > math.MaxInt64 {
return 0, 0, false
}
//nolint:gosec
return int64(q), int64(r), true
}
// NewFromFloat64 converts a float to a (possibly rounded) decimal.
// See also method [Decimal.Float64].
//
// NewFromFloat64 returns an error if:
// - the float is a special value (NaN or Inf);
// - the integer part of the result has more than [MaxPrec] digits.
func NewFromFloat64(f float64) (Decimal, error) {
// Float
if math.IsNaN(f) || math.IsInf(f, 0) {
return Decimal{}, fmt.Errorf("converting float: special value %v", f)
}
text := make([]byte, 0, 32)
text = strconv.AppendFloat(text, f, 'f', -1, 64)
// Decimal
d, err := parse(text)
if err != nil {
return Decimal{}, fmt.Errorf("converting float: %w", err)
}
return d, nil
}
// Float64 returns the nearest binary floating-point number rounded
// using [rounding half to even] (banker's rounding).
// See also constructor [NewFromFloat64].
//
// This conversion may lose data, as float64 has a smaller precision
// than the decimal type.
//
// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even
func (d Decimal) Float64() (f float64, ok bool) {
s := d.String()
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, false
}
return f, true
}
// MustParse is like [Parse] but panics if the string cannot be parsed.
// It simplifies safe initialization of global variables holding decimals.
func MustParse(s string) Decimal {
d, err := Parse(s)
if err != nil {
panic(fmt.Sprintf("Parse(%q) failed: %v", s, err))
}
return d
}
// Parse converts a string to a (possibly rounded) decimal.
// The input string must be in one of the following formats:
//
// 1.234
// -1234
// +0.000001234
// 1.83e5
// 0.22e-9
//
// The formal EBNF grammar for the supported format is as follows:
//
// sign ::= '+' | '-'
// digits ::= { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' }
// significand ::= digits '.' digits | '.' digits | digits '.' | digits
// exponent ::= ('e' | 'E') [sign] digits
// numeric-string ::= [sign] significand [exponent]
//
// Parse removes leading zeros from the integer part of the input string,
// but tries to maintain trailing zeros in the fractional part to preserve scale.
//
// Parse returns an error if:
// - the string contains any whitespaces;
// - the string is longer than 330 bytes;
// - the exponent is less than -330 or greater than 330;
// - the string does not represent a valid decimal number;
// - the integer part of the result has more than [MaxPrec] digits.
func Parse(s string) (Decimal, error) {
text := unsafe.Slice(unsafe.StringData(s), len(s))
return parseExact(text, 0)
}
func parse(text []byte) (Decimal, error) {
return parseExact(text, 0)
}
// ParseExact is similar to [Parse], but it allows you to specify how many digits
// after the decimal point should be considered significant.
// If any of the significant digits are lost during rounding, the method will return an error.
// This method is useful for parsing monetary amounts, where the scale should be
// equal to or greater than the currency's scale.
func ParseExact(s string, scale int) (Decimal, error) {
text := unsafe.Slice(unsafe.StringData(s), len(s))
return parseExact(text, scale)
}
func parseExact(text []byte, scale int) (Decimal, error) {
if len(text) > 330 {
return Decimal{}, fmt.Errorf("parsing decimal: %w", errInvalidDecimal)
}
if scale < MinScale || scale > MaxScale {
return Decimal{}, fmt.Errorf("parsing decimal: %w", errScaleRange)
}
d, err := parseFint(text, scale)
if err != nil {
d, err = parseBint(text, scale)
if err != nil {
return Decimal{}, fmt.Errorf("parsing decimal: %w", err)
}
}
return d, nil
}
// parseFint parses a decimal string using uint64 arithmetic.
// parseFint does not support exponential notation to make it as fast as possible.
//
//nolint:gocyclo
func parseFint(text []byte, minScale int) (Decimal, error) {
var pos int
width := len(text)
// Sign
var neg bool
switch {
case pos == width:
// skip
case text[pos] == '-':
neg = true
pos++
case text[pos] == '+':
pos++
}
// Coefficient
var coef fint
var scale int
var hasCoef, ok bool
// Integer
for pos < width && text[pos] >= '0' && text[pos] <= '9' {
coef, ok = coef.fsa(1, text[pos]-'0')
if !ok {
return Decimal{}, errDecimalOverflow
}
pos++
hasCoef = true
}
// Fraction
if pos < width && text[pos] == '.' {
pos++
for pos < width && text[pos] >= '0' && text[pos] <= '9' {
coef, ok = coef.fsa(1, text[pos]-'0')
if !ok {
return Decimal{}, errDecimalOverflow
}
pos++
scale++
hasCoef = true
}
}
if pos != width {
return Decimal{}, fmt.Errorf("%w: unexpected character %q", errInvalidDecimal, text[pos])
}
if !hasCoef {
return Decimal{}, fmt.Errorf("%w: no coefficient", errInvalidDecimal)
}
return newFromFint(neg, coef, scale, minScale)
}
// parseBint parses a decimal string using *big.Int arithmetic.
// parseBint supports exponential notation.
//
//nolint:gocyclo
func parseBint(text []byte, minScale int) (Decimal, error) {
var pos int
width := len(text)
// Sign
var neg bool
switch {
case pos == width:
// skip
case text[pos] == '-':
neg = true
pos++
case text[pos] == '+':
pos++
}
// Coefficient
bcoef := getBint()
defer putBint(bcoef)
var fcoef fint
var shift, scale int
var hasCoef, ok bool
bcoef.setFint(0)
// Algorithm:
// 1. Add as many digits as possible to the uint64 coefficient (fast).
// 2. Once the uint64 coefficient has reached its maximum value,
// add it to the *big.Int coefficient (slow).
// 3. Repeat until all digits are processed.
// Integer
for pos < width && text[pos] >= '0' && text[pos] <= '9' {
fcoef, ok = fcoef.fsa(1, text[pos]-'0')
if !ok {
return Decimal{}, errDecimalOverflow // Should never happen
}
pos++
shift++
hasCoef = true
if fcoef.hasPrec(MaxPrec) {
bcoef.fsa(bcoef, shift, fcoef)
fcoef, shift = 0, 0
}
}
// Fraction
if pos < width && text[pos] == '.' {
pos++
for pos < width && text[pos] >= '0' && text[pos] <= '9' {
fcoef, ok = fcoef.fsa(1, text[pos]-'0')
if !ok {
return Decimal{}, errDecimalOverflow // Should never happen
}
pos++
scale++
shift++
hasCoef = true
if fcoef.hasPrec(MaxPrec) {
bcoef.fsa(bcoef, shift, fcoef)
fcoef, shift = 0, 0
}
}
}
if shift > 0 {
bcoef.fsa(bcoef, shift, fcoef)
}
// Exponent
var exp int
var eneg, hasExp, hasE bool
if pos < width && (text[pos] == 'e' || text[pos] == 'E') {
pos++
hasE = true
// Sign
switch {
case pos == width:
// skip
case text[pos] == '-':
eneg = true
pos++
case text[pos] == '+':
pos++
}
// Integer
for pos < width && text[pos] >= '0' && text[pos] <= '9' {
exp = exp*10 + int(text[pos]-'0')
if exp > 330 {
return Decimal{}, errInvalidDecimal
}
pos++
hasExp = true
}
}
if pos != width {
return Decimal{}, fmt.Errorf("%w: unexpected character %q", errInvalidDecimal, text[pos])
}
if !hasCoef {
return Decimal{}, fmt.Errorf("%w: no coefficient", errInvalidDecimal)
}
if hasE && !hasExp {
return Decimal{}, fmt.Errorf("%w: no exponent", errInvalidDecimal)
}
if eneg {
scale = scale + exp
} else {
scale = scale - exp
}
return newFromBint(neg, bcoef, scale, minScale)
}
// String implements the [fmt.Stringer] interface and returns
// a string representation of the decimal.
// The returned string does not use scientific or engineering notation and is
// formatted according to the following formal EBNF grammar:
//
// sign ::= '-'
// digits ::= { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' }
// significand ::= digits '.' digits | digits
// numeric-string ::= [sign] significand
//
// See also method [Decimal.Format].
//
// [fmt.Stringer]: https://pkg.go.dev/fmt#Stringer
func (d Decimal) String() string {
return string(d.bytes())
}
// bytes returns a string representation of the decimal as a byte slice.
func (d Decimal) bytes() []byte {
text := make([]byte, 0, 24)
return d.append(text)
}
// append appends a string representation of the decimal to the byte slice.
func (d Decimal) append(text []byte) []byte {
var buf [24]byte
pos := len(buf) - 1
coef := d.Coef()
scale := d.Scale()
// Coefficient
for {
buf[pos] = byte(coef%10) + '0'
pos--
coef /= 10
if scale > 0 {
scale--
// Decimal point
if scale == 0 {
buf[pos] = '.'
pos--
// Leading 0
if coef == 0 {
buf[pos] = '0'
pos--
}
}
}
if coef == 0 && scale == 0 {
break
}
}
// Sign
if d.IsNeg() {
buf[pos] = '-'
pos--
}
return append(text, buf[pos+1:]...)
}
// UnmarshalJSON implements the [json.Unmarshaler] interface.
// UnmarshalJSON supports the following types: [number] and [numeric string].
// See also constructor [Parse].
//
// [number]: https://datatracker.ietf.org/doc/html/rfc8259#section-6
// [numeric string]: https://datatracker.ietf.org/doc/html/rfc8259#section-7
// [json.Unmarshaler]: https://pkg.go.dev/encoding/json#Unmarshaler
func (d *Decimal) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
if len(data) >= 2 && data[0] == '"' && data[len(data)-1] == '"' {
data = data[1 : len(data)-1]
}
var err error
*d, err = parse(data)
if err != nil {
return fmt.Errorf("unmarshaling %T: %w", Decimal{}, err)
}
return nil
}
// MarshalJSON implements the [json.Marshaler] interface.
// MarshalJSON always returns a [numeric string].
// See also method [Decimal.String].
//
// [numeric string]: https://datatracker.ietf.org/doc/html/rfc8259#section-7
// [json.Marshaler]: https://pkg.go.dev/encoding/json#Marshaler
func (d Decimal) MarshalJSON() ([]byte, error) {
text := make([]byte, 0, 26)
text = append(text, '"')
text = d.append(text)
text = append(text, '"')
return text, nil
}
// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
// UnmarshalText supports only numeric strings.
// See also constructor [Parse].
//
// [encoding.TextUnmarshaler]: https://pkg.go.dev/encoding#TextUnmarshaler
func (d *Decimal) UnmarshalText(text []byte) error {
var err error
*d, err = parse(text)
if err != nil {
return fmt.Errorf("unmarshaling %T: %w", Decimal{}, err)
}
return nil
}
// AppendText implements the [encoding.TextAppender] interface.
// AppendText always appends a numeric string.
// See also method [Decimal.String].
//
// [encoding.TextAppender]: https://pkg.go.dev/encoding#TextAppender
func (d Decimal) AppendText(text []byte) ([]byte, error) {
return d.append(text), nil
}
// MarshalText implements the [encoding.TextMarshaler] interface.
// MarshalText always returns a numeric string.
// See also method [Decimal.String].
//
// [encoding.TextMarshaler]: https://pkg.go.dev/encoding#TextMarshaler
func (d Decimal) MarshalText() ([]byte, error) {
return d.bytes(), nil
}
// UnmarshalBinary implements the [encoding.BinaryUnmarshaler] interface.
// UnmarshalBinary supports only numeric strings.
// See also constructor [Parse].
//
// [encoding.BinaryUnmarshaler]: https://pkg.go.dev/encoding#BinaryUnmarshaler
func (d *Decimal) UnmarshalBinary(data []byte) error {
var err error
*d, err = parse(data)
if err != nil {
return fmt.Errorf("unmarshaling %T: %w", Decimal{}, err)
}
return nil
}
// AppendBinary implements the [encoding.BinaryAppender] interface.
// AppendBinary always appends a numeric string.
// See also method [Decimal.String].
//
// [encoding.BinaryAppender]: https://pkg.go.dev/encoding#BinaryAppender
func (d Decimal) AppendBinary(data []byte) ([]byte, error) {
return d.append(data), nil
}
// MarshalBinary implements the [encoding.BinaryMarshaler] interface.
// MarshalBinary always returns a numeric string.
// See also method [Decimal.String].
//
// [encoding.BinaryMarshaler]: https://pkg.go.dev/encoding#BinaryMarshaler
func (d Decimal) MarshalBinary() ([]byte, error) {
return d.bytes(), nil
}
// UnmarshalBSONValue implements the [v2/bson.ValueUnmarshaler] interface.
// UnmarshalBSONValue supports the following [types]: Double, String, 32-bit Integer, 64-bit Integer, and [Decimal128].
//
// [v2/bson.ValueUnmarshaler]: https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/bson#ValueUnmarshaler
// [types]: https://bsonspec.org/spec.html
// [Decimal128]: https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.md
func (d *Decimal) UnmarshalBSONValue(typ byte, data []byte) error {
// constants are from https://bsonspec.org/spec.html
var err error
switch typ {
case 1:
*d, err = parseBSONFloat64(data)
case 2:
*d, err = parseBSONString(data)
case 10:
// null, do nothing
case 16:
*d, err = parseBSONInt32(data)
case 18:
*d, err = parseBSONInt64(data)
case 19:
*d, err = parseIEEEDecimal128(data)
default:
err = fmt.Errorf("BSON type %d is not supported", typ)
}
if err != nil {
err = fmt.Errorf("converting from BSON type %d to %T: %w", typ, Decimal{}, err)
}
return err
}
// MarshalBSONValue implements the [v2/bson.ValueMarshaler] interface.
// MarshalBSONValue always returns [Decimal128].
//
// [v2/bson.ValueMarshaler]: https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/bson#ValueMarshaler
// [Decimal128]: https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.md
func (d Decimal) MarshalBSONValue() (typ byte, data []byte, err error) {
return 19, d.ieeeDecimal128(), nil
}
// parseBSONInt32 parses a BSON int32 to a decimal.
// The byte order of the input data must be little-endian.
func parseBSONInt32(data []byte) (Decimal, error) {
if len(data) != 4 {
return Decimal{}, fmt.Errorf("%w: invalid data length %v", errInvalidDecimal, len(data))
}
u := uint32(data[0])
u |= uint32(data[1]) << 8
u |= uint32(data[2]) << 16
u |= uint32(data[3]) << 24
i := int64(int32(u)) //nolint:gosec
return New(i, 0)
}
// parseBSONInt64 parses a BSON int64 to a decimal.
// The byte order of the input data must be little-endian.
func parseBSONInt64(data []byte) (Decimal, error) {
if len(data) != 8 {
return Decimal{}, fmt.Errorf("%w: invalid data length %v", errInvalidDecimal, len(data))
}
u := uint64(data[0])
u |= uint64(data[1]) << 8
u |= uint64(data[2]) << 16
u |= uint64(data[3]) << 24
u |= uint64(data[4]) << 32
u |= uint64(data[5]) << 40
u |= uint64(data[6]) << 48
u |= uint64(data[7]) << 56
i := int64(u) //nolint:gosec
return New(i, 0)
}
// parseBSONFloat64 parses a BSON float64 to a (possibly rounded) decimal.
// The byte order of the input data must be little-endian.
func parseBSONFloat64(data []byte) (Decimal, error) {
if len(data) != 8 {
return Decimal{}, fmt.Errorf("%w: invalid data length %v", errInvalidDecimal, len(data))
}
u := uint64(data[0])
u |= uint64(data[1]) << 8
u |= uint64(data[2]) << 16
u |= uint64(data[3]) << 24
u |= uint64(data[4]) << 32
u |= uint64(data[5]) << 40
u |= uint64(data[6]) << 48
u |= uint64(data[7]) << 56
f := math.Float64frombits(u)
return NewFromFloat64(f)
}
// parseBSONString parses a BSON string to a (possibly rounded) decimal.
// The byte order of the input data must be little-endian.
func parseBSONString(data []byte) (Decimal, error) {
if len(data) < 4 {
return Decimal{}, fmt.Errorf("%w: invalid data length %v", errInvalidDecimal, len(data))
}
u := uint32(data[0])
u |= uint32(data[1]) << 8
u |= uint32(data[2]) << 16
u |= uint32(data[3]) << 24
l := int(int32(u)) //nolint:gosec
if l < 1 || l > 330 || len(data) < l+4 {
return Decimal{}, fmt.Errorf("%w: invalid string length %v", errInvalidDecimal, l)
}
if data[l+4-1] != 0 {
return Decimal{}, fmt.Errorf("%w: invalid null terminator %v", errInvalidDecimal, data[l+4-1])
}
s := string(data[4 : l+4-1])
return Parse(s)
}
// parseIEEEDecimal128 converts a 128-bit IEEE 754-2008 decimal
// floating point with binary integer decimal encoding to
// a (possibly rounded) decimal.
// The byte order of the input data must be little-endian.
//
// parseIEEEDecimal128 returns an error if:
// - the data length is not equal to 16 bytes;
// - the decimal a special value (NaN or Inf);
// - the integer part of the result has more than [MaxPrec] digits.
func parseIEEEDecimal128(data []byte) (Decimal, error) {
if len(data) != 16 {
return Decimal{}, fmt.Errorf("%w: invalid data length %v", errInvalidDecimal, len(data))
}
if data[15]&0b0111_1100 == 0b0111_1100 {
return Decimal{}, fmt.Errorf("%w: special value NaN", errInvalidDecimal)
}
if data[15]&0b0111_1100 == 0b0111_1000 {
return Decimal{}, fmt.Errorf("%w: special value Inf", errInvalidDecimal)
}
if data[15]&0b0110_0000 == 0b0110_0000 {
return Decimal{}, fmt.Errorf("%w: unsupported encoding", errInvalidDecimal)
}
// Sign
neg := data[15]&0b1000_0000 == 0b1000_0000
// Scale
var scale int
scale |= int(data[14]) >> 1
scale |= int(data[15]&0b0111_1111) << 7
scale = 6176 - scale
// TODO fint optimization
// Coefficient
coef := getBint()
defer putBint(coef)
buf := make([]byte, 15)
for i := range 15 {
buf[i] = data[14-i]
}
buf[0] &= 0b0000_0001
coef.setBytes(buf)
// Scale normalization
if coef.sign() == 0 {
scale = max(scale, MinScale)
}
return newFromBint(neg, coef, scale, 0)
}
// ieeeDecimal128 returns a 128-bit IEEE 754-2008 decimal
// floating point with binary integer decimal encoding.
// The byte order of the result is little-endian.
func (d Decimal) ieeeDecimal128() []byte {
var buf [16]byte
scale := d.Scale()
coef := d.Coef()
// Sign
if d.IsNeg() {
buf[15] = 0b1000_0000
}
// Scale
scale = 6176 - scale
buf[15] |= byte((scale >> 7) & 0b0111_1111)
buf[14] |= byte((scale << 1) & 0b1111_1110)
// Coefficient
for i := range 8 {
buf[i] = byte(coef & 0b1111_1111)
coef >>= 8
}
return buf[:]
}
// Scan implements the [sql.Scanner] interface.
//
// [sql.Scanner]: https://pkg.go.dev/database/sql#Scanner
func (d *Decimal) Scan(value any) error {
var err error
switch value := value.(type) {
case string:
*d, err = Parse(value)
case int64:
*d, err = New(value, 0)
case float64:
*d, err = NewFromFloat64(value)
case []byte:
// Special case: MySQL driver sends DECIMAL as []byte
*d, err = parse(value)
case float32:
// Special case: MySQL driver sends FLOAT as float32
*d, err = NewFromFloat64(float64(value))
case uint64:
// Special case: ClickHouse driver sends 0 as uint64
*d, err = newSafe(false, fint(value), 0)
case nil:
err = fmt.Errorf("%T does not support null values, use %T or *%T", Decimal{}, NullDecimal{}, Decimal{})
default:
err = fmt.Errorf("type %T is not supported", value)
}
if err != nil {
err = fmt.Errorf("converting from %T to %T: %w", value, Decimal{}, err)
}
return err
}
// Value implements the [driver.Valuer] interface.
//
// [driver.Valuer]: https://pkg.go.dev/database/sql/driver#Valuer
func (d Decimal) Value() (driver.Value, error) {
return d.String(), nil
}
// Format implements the [fmt.Formatter] interface.
// The following [format verbs] are available:
//
// | Verb | Example | Description |
// | ---------- | ------- | -------------- |
// | %f, %s, %v | 5.67 | Decimal |
// | %q | "5.67" | Quoted decimal |
// | %k | 567% | Percentage |
//
// The following format flags can be used with all verbs: '+', ' ', '0', '-'.
//
// Precision is only supported for %f and %k verbs.
// For %f verb, the default precision is equal to the actual scale of the decimal,
// whereas, for verb %k the default precision is the actual scale of the decimal minus 2.
//
// [format verbs]: https://pkg.go.dev/fmt#hdr-Printing
// [fmt.Formatter]: https://pkg.go.dev/fmt#Formatter
//
//nolint:gocyclo
func (d Decimal) Format(state fmt.State, verb rune) {
var err error
// Percentage multiplier
if verb == 'k' || verb == 'K' {
d, err = d.Mul(Hundred)
if err != nil {
// This panic is handled inside the fmt package.
panic(fmt.Errorf("formatting percent: %w", err))
}
}
// Rescaling
var tzeros int
if verb == 'f' || verb == 'F' || verb == 'k' || verb == 'K' {
var scale int
switch p, ok := state.Precision(); {
case ok:
scale = p
case verb == 'k' || verb == 'K':
scale = d.Scale() - 2
case verb == 'f' || verb == 'F':
scale = d.Scale()
}
scale = max(scale, MinScale)
switch {
case scale < d.Scale():
d = d.Round(scale)
case scale > d.Scale():
tzeros = scale - d.Scale()
}
}
// Integer and fractional digits
var intdigs int
fracdigs := d.Scale()
if dprec := d.Prec(); dprec > fracdigs {
intdigs = dprec - fracdigs
}
if d.WithinOne() {
intdigs++ // leading 0
}
// Decimal point
var dpoint int
if fracdigs > 0 || tzeros > 0 {
dpoint = 1
}
// Arithmetic sign
var rsign int
if d.IsNeg() || state.Flag('+') || state.Flag(' ') {
rsign = 1