Debian Codegraph @

decimal.go

raw symbols SCIP
1 package mssql
2
3 import (
4 "encoding/binary"
5 "errors"
6 "math"
7 "math/big"
8 )
9
10 // http://msdn.microsoft.com/en-us/library/ee780893.aspx
11 type Decimal struct {
12 integer [4]uint32
13 positive bool
14 prec uint8
15 scale uint8
16 }
17
18 var scaletblflt64 [39]float64
19
20 func (d Decimal) ToFloat64() float64 {
21 val := float64(0)
22 for i := 3; i >= 0; i-- {
23 val *= 0x100000000
24 val += float64(d.integer[i])
25 }
26 if !d.positive {
27 val = -val
28 }
29 if d.scale != 0 {
30 val /= scaletblflt64[d.scale]
31 }
32 return val
33 }
34
35 func Float64ToDecimal(f float64) (Decimal, error) {
36 var dec Decimal
37 if math.IsNaN(f) {
38 return dec, errors.New("NaN")
39 }
40 if math.IsInf(f, 0) {
41 return dec, errors.New("Infinity can't be converted to decimal")
42 }
43 dec.positive = f >= 0
44 if !dec.positive {
45 f = math.Abs(f)
46 }
47 if f > 3.402823669209385e+38 {
48 return dec, errors.New("Float value is out of range")
49 }
50 dec.prec = 20
51 var integer float64
52 for dec.scale = 0; dec.scale <= 20; dec.scale++ {
53 integer = f * scaletblflt64[dec.scale]
54 _, frac := math.Modf(integer)
55 if frac == 0 {
56 break
57 }
58 }
59 for i := 0; i < 4; i++ {
60 mod := math.Mod(integer, 0x100000000)
61 integer -= mod
62 integer /= 0x100000000
63 dec.integer[i] = uint32(mod)
64 }
65 return dec, nil
66 }
67
68 func init() {
69 var acc float64 = 1
70 for i := 0; i <= 38; i++ {
71 scaletblflt64[i] = acc
72 acc *= 10
73 }
74 }
75
76 func (d Decimal) Bytes() []byte {
77 bytes := make([]byte, 16)
78 binary.BigEndian.PutUint32(bytes[0:4], d.integer[3])
79 binary.BigEndian.PutUint32(bytes[4:8], d.integer[2])
80 binary.BigEndian.PutUint32(bytes[8:12], d.integer[1])
81 binary.BigEndian.PutUint32(bytes[12:16], d.integer[0])
82 var x big.Int
83 x.SetBytes(bytes)
84 if !d.positive {
85 x.Neg(&x)
86 }
87 return scaleBytes(x.String(), d.scale)
88 }
89
90 func scaleBytes(s string, scale uint8) []byte {
91 z := make([]byte, 0, len(s)+1)
92 if s[0] == '-' || s[0] == '+' {
93 z = append(z, byte(s[0]))
94 s = s[1:]
95 }
96 pos := len(s) - int(scale)
97 if pos <= 0 {
98 z = append(z, byte('0'))
99 } else if pos > 0 {
100 z = append(z, []byte(s[:pos])...)
101 }
102 if scale > 0 {
103 z = append(z, byte('.'))
104 for pos < 0 {
105 z = append(z, byte('0'))
106 pos++
107 }
108 z = append(z, []byte(s[pos:])...)
109 }
110 return z
111 }
112
113 func (d Decimal) String() string {
114 return string(d.Bytes())
115 }