1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package inf
24
25
26
27
28 import (
29 "fmt"
30 "io"
31 "math/big"
32 "strings"
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 type Dec struct {
84 unscaled big.Int
85 scale Scale
86 }
87
88
89 type Scale int32
90
91 const scaleSize = 4
92
93
94
95 type scaler interface {
96 Scale(x *Dec, y *Dec) Scale
97 }
98
99 var bigInt = [...]*big.Int{
100 big.NewInt(0), big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(4),
101 big.NewInt(5), big.NewInt(6), big.NewInt(7), big.NewInt(8), big.NewInt(9),
102 big.NewInt(10),
103 }
104
105 var exp10cache [64]big.Int = func() [64]big.Int {
106 e10, e10i := [64]big.Int{}, bigInt[1]
107 for i := range e10 {
108 e10[i].Set(e10i)
109 e10i = new(big.Int).Mul(e10i, bigInt[10])
110 }
111 return e10
112 }()
113
114
115
116 func NewDec(unscaled int64, scale Scale) *Dec {
117 return new(Dec).SetUnscaled(unscaled).SetScale(scale)
118 }
119
120
121
122 func NewDecBig(unscaled *big.Int, scale Scale) *Dec {
123 return new(Dec).SetUnscaledBig(unscaled).SetScale(scale)
124 }
125
126
127 func (x *Dec) Scale() Scale {
128 return x.scale
129 }
130
131
132
133
134
135 func (x *Dec) Unscaled() (u int64, ok bool) {
136 u = x.unscaled.Int64()
137 var i big.Int
138 ok = i.SetInt64(u).Cmp(&x.unscaled) == 0
139 return
140 }
141
142
143 func (x *Dec) UnscaledBig() *big.Int {
144 return &x.unscaled
145 }
146
147
148
149
150
151 func (z *Dec) SetScale(scale Scale) *Dec {
152 z.scale = scale
153 return z
154 }
155
156
157
158 func (z *Dec) SetUnscaled(unscaled int64) *Dec {
159 z.unscaled.SetInt64(unscaled)
160 return z
161 }
162
163
164
165 func (z *Dec) SetUnscaledBig(unscaled *big.Int) *Dec {
166 z.unscaled.Set(unscaled)
167 return z
168 }
169
170
171
172 func (z *Dec) Set(x *Dec) *Dec {
173 if z != x {
174 z.SetUnscaledBig(x.UnscaledBig())
175 z.SetScale(x.Scale())
176 }
177 return z
178 }
179
180
181
182
183
184
185
186 func (x *Dec) Sign() int {
187 return x.UnscaledBig().Sign()
188 }
189
190
191 func (z *Dec) Neg(x *Dec) *Dec {
192 z.SetScale(x.Scale())
193 z.UnscaledBig().Neg(x.UnscaledBig())
194 return z
195 }
196
197
198
199
200
201
202
203 func (x *Dec) Cmp(y *Dec) int {
204 xx, yy := upscale(x, y)
205 return xx.UnscaledBig().Cmp(yy.UnscaledBig())
206 }
207
208
209 func (z *Dec) Abs(x *Dec) *Dec {
210 z.SetScale(x.Scale())
211 z.UnscaledBig().Abs(x.UnscaledBig())
212 return z
213 }
214
215
216
217 func (z *Dec) Add(x, y *Dec) *Dec {
218 xx, yy := upscale(x, y)
219 z.SetScale(xx.Scale())
220 z.UnscaledBig().Add(xx.UnscaledBig(), yy.UnscaledBig())
221 return z
222 }
223
224
225
226 func (z *Dec) Sub(x, y *Dec) *Dec {
227 xx, yy := upscale(x, y)
228 z.SetScale(xx.Scale())
229 z.UnscaledBig().Sub(xx.UnscaledBig(), yy.UnscaledBig())
230 return z
231 }
232
233
234
235 func (z *Dec) Mul(x, y *Dec) *Dec {
236 z.SetScale(x.Scale() + y.Scale())
237 z.UnscaledBig().Mul(x.UnscaledBig(), y.UnscaledBig())
238 return z
239 }
240
241
242
243 func (z *Dec) Round(x *Dec, s Scale, r Rounder) *Dec {
244 return z.QuoRound(x, NewDec(1, 0), s, r)
245 }
246
247
248
249
250
251
252
253
254
255
256 func (z *Dec) QuoRound(x, y *Dec, s Scale, r Rounder) *Dec {
257 return z.quo(x, y, sclr{s}, r)
258 }
259
260 func (z *Dec) quo(x, y *Dec, s scaler, r Rounder) *Dec {
261 scl := s.Scale(x, y)
262 var zzz *Dec
263 if r.UseRemainder() {
264 zz, rA, rB := new(Dec).quoRem(x, y, scl, true, new(big.Int), new(big.Int))
265 zzz = r.Round(new(Dec), zz, rA, rB)
266 } else {
267 zz, _, _ := new(Dec).quoRem(x, y, scl, false, nil, nil)
268 zzz = r.Round(new(Dec), zz, nil, nil)
269 }
270 if zzz == nil {
271 return nil
272 }
273 return z.Set(zzz)
274 }
275
276
277
278
279
280
281
282 func (z *Dec) QuoExact(x, y *Dec) *Dec {
283 return z.quo(x, y, scaleQuoExact{}, RoundExact)
284 }
285
286
287
288
289
290
291
292
293
294
295
296
297 func (z *Dec) quoRem(x, y *Dec, s Scale, useRem bool,
298 remNum, remDen *big.Int) (*Dec, *big.Int, *big.Int) {
299
300 shift := s - (x.Scale() - y.Scale())
301
302 var ix, iy *big.Int
303 switch {
304 case shift > 0:
305
306 ix = new(big.Int).Mul(x.UnscaledBig(), exp10(shift))
307 iy = y.UnscaledBig()
308 case shift < 0:
309
310 ix = x.UnscaledBig()
311 iy = new(big.Int).Mul(y.UnscaledBig(), exp10(-shift))
312 default:
313 ix = x.UnscaledBig()
314 iy = y.UnscaledBig()
315 }
316
317 iy2 := iy
318 if iy == z.UnscaledBig() {
319 iy2 = new(big.Int).Set(iy)
320 }
321
322 z.SetScale(s)
323
324 if useRem {
325
326 _, intr := z.UnscaledBig().QuoRem(ix, iy, new(big.Int))
327
328 remNum.Set(intr)
329 remDen.Set(iy2)
330 } else {
331 z.UnscaledBig().Quo(ix, iy)
332 }
333 return z, remNum, remDen
334 }
335
336 type sclr struct{ s Scale }
337
338 func (s sclr) Scale(x, y *Dec) Scale {
339 return s.s
340 }
341
342 type scaleQuoExact struct{}
343
344 func (sqe scaleQuoExact) Scale(x, y *Dec) Scale {
345 rem := new(big.Rat).SetFrac(x.UnscaledBig(), y.UnscaledBig())
346 f2, f5 := factor2(rem.Denom()), factor(rem.Denom(), bigInt[5])
347 var f10 Scale
348 if f2 > f5 {
349 f10 = Scale(f2)
350 } else {
351 f10 = Scale(f5)
352 }
353 return x.Scale() - y.Scale() + f10
354 }
355
356 func factor(n *big.Int, p *big.Int) int {
357
358 d, f := n, 0
359 for {
360 dd, dm := new(big.Int).DivMod(d, p, new(big.Int))
361 if dm.Sign() == 0 {
362 f++
363 d = dd
364 } else {
365 break
366 }
367 }
368 return f
369 }
370
371 func factor2(n *big.Int) int {
372
373 f := 0
374 for ; n.Bit(f) == 0; f++ {
375 }
376 return f
377 }
378
379 func upscale(a, b *Dec) (*Dec, *Dec) {
380 if a.Scale() == b.Scale() {
381 return a, b
382 }
383 if a.Scale() > b.Scale() {
384 bb := b.rescale(a.Scale())
385 return a, bb
386 }
387 aa := a.rescale(b.Scale())
388 return aa, b
389 }
390
391 func exp10(x Scale) *big.Int {
392 if int(x) < len(exp10cache) {
393 return &exp10cache[int(x)]
394 }
395 return new(big.Int).Exp(bigInt[10], big.NewInt(int64(x)), nil)
396 }
397
398 func (x *Dec) rescale(newScale Scale) *Dec {
399 shift := newScale - x.Scale()
400 switch {
401 case shift < 0:
402 e := exp10(-shift)
403 return NewDecBig(new(big.Int).Quo(x.UnscaledBig(), e), newScale)
404 case shift > 0:
405 e := exp10(shift)
406 return NewDecBig(new(big.Int).Mul(x.UnscaledBig(), e), newScale)
407 }
408 return x
409 }
410
411 var zeros = []byte("00000000000000000000000000000000" +
412 "00000000000000000000000000000000")
413 var lzeros = Scale(len(zeros))
414
415 func appendZeros(s []byte, n Scale) []byte {
416 for i := Scale(0); i < n; i += lzeros {
417 if n > i+lzeros {
418 s = append(s, zeros...)
419 } else {
420 s = append(s, zeros[0:n-i]...)
421 }
422 }
423 return s
424 }
425
426 func (x *Dec) String() string {
427 if x == nil {
428 return "<nil>"
429 }
430 scale := x.Scale()
431 s := []byte(x.UnscaledBig().String())
432 if scale <= 0 {
433 if scale != 0 && x.unscaled.Sign() != 0 {
434 s = appendZeros(s, -scale)
435 }
436 return string(s)
437 }
438 negbit := Scale(-((x.Sign() - 1) / 2))
439
440 lens := Scale(len(s))
441 if lens-negbit <= scale {
442 ss := make([]byte, 0, scale+2)
443 if negbit == 1 {
444 ss = append(ss, '-')
445 }
446 ss = append(ss, '0', '.')
447 ss = appendZeros(ss, scale-lens+negbit)
448 ss = append(ss, s[negbit:]...)
449 return string(ss)
450 }
451
452 ss := make([]byte, 0, lens+1)
453 ss = append(ss, s[:lens-scale]...)
454 ss = append(ss, '.')
455 ss = append(ss, s[lens-scale:]...)
456 return string(ss)
457 }
458
459
460
461
462 func (x *Dec) Format(s fmt.State, ch rune) {
463 if ch != 'd' && ch != 'f' && ch != 'v' && ch != 's' {
464 fmt.Fprintf(s, "%%!%c(dec.Dec=%s)", ch, x.String())
465 return
466 }
467 fmt.Fprintf(s, x.String())
468 }
469
470 func (z *Dec) scan(r io.RuneScanner) (*Dec, error) {
471 unscaled := make([]byte, 0, 256)
472 dp, dg := -1, -1
473 loop:
474 for {
475 ch, _, err := r.ReadRune()
476 if err == io.EOF {
477 break loop
478 }
479 if err != nil {
480 return nil, err
481 }
482 switch {
483 case ch == '+' || ch == '-':
484 if len(unscaled) > 0 || dp >= 0 {
485 r.UnreadRune()
486 break loop
487 }
488 case ch == '.':
489 if dp >= 0 {
490 r.UnreadRune()
491 break loop
492 }
493 dp = len(unscaled)
494 continue
495 case ch >= '0' && ch <= '9':
496 if dg == -1 {
497 dg = len(unscaled)
498 }
499 default:
500 r.UnreadRune()
501 break loop
502 }
503 unscaled = append(unscaled, byte(ch))
504 }
505 if dg == -1 {
506 return nil, fmt.Errorf("no digits read")
507 }
508 if dp >= 0 {
509 z.SetScale(Scale(len(unscaled) - dp))
510 } else {
511 z.SetScale(0)
512 }
513 _, ok := z.UnscaledBig().SetString(string(unscaled), 10)
514 if !ok {
515 return nil, fmt.Errorf("invalid decimal: %s", string(unscaled))
516 }
517 return z, nil
518 }
519
520
521
522
523
524
525 func (z *Dec) SetString(s string) (*Dec, bool) {
526 r := strings.NewReader(s)
527 _, err := z.scan(r)
528 if err != nil {
529 return nil, false
530 }
531 _, _, err = r.ReadRune()
532 if err != io.EOF {
533 return nil, false
534 }
535
536 return z, true
537 }
538
539
540
541
542
543
544 func (z *Dec) Scan(s fmt.ScanState, ch rune) error {
545 if ch != 'd' && ch != 'f' && ch != 's' && ch != 'v' {
546 return fmt.Errorf("Dec.Scan: invalid verb '%c'", ch)
547 }
548 s.SkipSpace()
549 _, err := z.scan(s)
550 return err
551 }
552
553
554 const decGobVersion byte = 1
555
556 func scaleBytes(s Scale) []byte {
557 buf := make([]byte, scaleSize)
558 i := scaleSize
559 for j := 0; j < scaleSize; j++ {
560 i--
561 buf[i] = byte(s)
562 s >>= 8
563 }
564 return buf
565 }
566
567 func scale(b []byte) (s Scale) {
568 for j := 0; j < scaleSize; j++ {
569 s <<= 8
570 s |= Scale(b[j])
571 }
572 return
573 }
574
575
576 func (x *Dec) GobEncode() ([]byte, error) {
577 buf, err := x.UnscaledBig().GobEncode()
578 if err != nil {
579 return nil, err
580 }
581 buf = append(append(buf, scaleBytes(x.Scale())...), decGobVersion)
582 return buf, nil
583 }
584
585
586 func (z *Dec) GobDecode(buf []byte) error {
587 if len(buf) == 0 {
588 return fmt.Errorf("Dec.GobDecode: no data")
589 }
590 b := buf[len(buf)-1]
591 if b != decGobVersion {
592 return fmt.Errorf("Dec.GobDecode: encoding version %d not supported", b)
593 }
594 l := len(buf) - scaleSize - 1
595 err := z.UnscaledBig().GobDecode(buf[:l])
596 if err != nil {
597 return err
598 }
599 z.SetScale(scale(buf[l : l+scaleSize]))
600 return nil
601 }
602
603
604 func (x *Dec) MarshalText() ([]byte, error) {
605 return []byte(x.String()), nil
606 }
607
608
609 func (z *Dec) UnmarshalText(data []byte) error {
610 _, ok := z.SetString(string(data))
611 if !ok {
612 return fmt.Errorf("invalid inf.Dec")
613 }
614 return nil
615 }
616
View as plain text