Source file
src/math/big/floatmarsh.go
1
2
3
4
5
6
7 package big
8
9 import (
10 "encoding/binary"
11 "fmt"
12 )
13
14
15 const floatGobVersion byte = 1
16
17
18
19
20 func (x *Float) GobEncode() ([]byte, error) {
21 if x == nil {
22 return nil, nil
23 }
24
25
26 sz := 1 + 1 + 4
27 n := 0
28 if x.form == finite {
29
30 n = int((x.prec + (_W - 1)) / _W)
31
32
33
34
35
36 if len(x.mant) < n {
37 n = len(x.mant)
38 }
39
40 sz += 4 + n*_S
41 }
42 buf := make([]byte, sz)
43
44 buf[0] = floatGobVersion
45 b := byte(x.mode&7)<<5 | byte((x.acc+1)&3)<<3 | byte(x.form&3)<<1
46 if x.neg {
47 b |= 1
48 }
49 buf[1] = b
50 binary.BigEndian.PutUint32(buf[2:], x.prec)
51
52 if x.form == finite {
53 binary.BigEndian.PutUint32(buf[6:], uint32(x.exp))
54 x.mant[len(x.mant)-n:].bytes(buf[10:])
55 }
56
57 return buf, nil
58 }
59
60
61
62
63
64 func (z *Float) GobDecode(buf []byte) error {
65 if len(buf) == 0 {
66
67 *z = Float{}
68 return nil
69 }
70
71 if buf[0] != floatGobVersion {
72 return fmt.Errorf("Float.GobDecode: encoding version %d not supported", buf[0])
73 }
74
75 oldPrec := z.prec
76 oldMode := z.mode
77
78 b := buf[1]
79 z.mode = RoundingMode((b >> 5) & 7)
80 z.acc = Accuracy((b>>3)&3) - 1
81 z.form = form((b >> 1) & 3)
82 z.neg = b&1 != 0
83 z.prec = binary.BigEndian.Uint32(buf[2:])
84
85 if z.form == finite {
86 z.exp = int32(binary.BigEndian.Uint32(buf[6:]))
87 z.mant = z.mant.setBytes(buf[10:])
88 }
89
90 if oldPrec != 0 {
91 z.mode = oldMode
92 z.SetPrec(uint(oldPrec))
93 }
94
95 return nil
96 }
97
98
99
100
101 func (x *Float) MarshalText() (text []byte, err error) {
102 if x == nil {
103 return []byte("<nil>"), nil
104 }
105 var buf []byte
106 return x.Append(buf, 'g', -1), nil
107 }
108
109
110
111
112
113 func (z *Float) UnmarshalText(text []byte) error {
114
115 _, _, err := z.Parse(string(text), 0)
116 if err != nil {
117 err = fmt.Errorf("math/big: cannot unmarshal %q into a *big.Float (%v)", text, err)
118 }
119 return err
120 }
121
View as plain text