...
Source file
src/math/big/ratmarsh.go
1
2
3
4
5
6
7 package big
8
9 import (
10 "encoding/binary"
11 "errors"
12 "fmt"
13 )
14
15
16 const ratGobVersion byte = 1
17
18
19 func (x *Rat) GobEncode() ([]byte, error) {
20 if x == nil {
21 return nil, nil
22 }
23 buf := make([]byte, 1+4+(len(x.a.abs)+len(x.b.abs))*_S)
24 i := x.b.abs.bytes(buf)
25 j := x.a.abs.bytes(buf[:i])
26 n := i - j
27 if int(uint32(n)) != n {
28
29 return nil, errors.New("Rat.GobEncode: numerator too large")
30 }
31 binary.BigEndian.PutUint32(buf[j-4:j], uint32(n))
32 j -= 1 + 4
33 b := ratGobVersion << 1
34 if x.a.neg {
35 b |= 1
36 }
37 buf[j] = b
38 return buf[j:], nil
39 }
40
41
42 func (z *Rat) GobDecode(buf []byte) error {
43 if len(buf) == 0 {
44
45 *z = Rat{}
46 return nil
47 }
48 if len(buf) < 5 {
49 return errors.New("Rat.GobDecode: buffer too small")
50 }
51 b := buf[0]
52 if b>>1 != ratGobVersion {
53 return fmt.Errorf("Rat.GobDecode: encoding version %d not supported", b>>1)
54 }
55 const j = 1 + 4
56 i := j + binary.BigEndian.Uint32(buf[j-4:j])
57 if len(buf) < int(i) {
58 return errors.New("Rat.GobDecode: buffer too small")
59 }
60 z.a.neg = b&1 != 0
61 z.a.abs = z.a.abs.setBytes(buf[j:i])
62 z.b.abs = z.b.abs.setBytes(buf[i:])
63 return nil
64 }
65
66
67 func (x *Rat) MarshalText() (text []byte, err error) {
68 if x.IsInt() {
69 return x.a.MarshalText()
70 }
71 return x.marshal(), nil
72 }
73
74
75 func (z *Rat) UnmarshalText(text []byte) error {
76
77 if _, ok := z.SetString(string(text)); !ok {
78 return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Rat", text)
79 }
80 return nil
81 }
82
View as plain text