github.com/flyinox/gosm@v0.0.0-20171117061539-16768cb62077/src/math/big/intmarsh.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // This file implements encoding/decoding of Ints. 6 7 package big 8 9 import "fmt" 10 11 // Gob codec version. Permits backward-compatible changes to the encoding. 12 const intGobVersion byte = 1 13 14 // GobEncode implements the gob.GobEncoder interface. 15 func (x *Int) GobEncode() ([]byte, error) { 16 if x == nil { 17 return nil, nil 18 } 19 buf := make([]byte, 1+len(x.abs)*_S) // extra byte for version and sign bit 20 i := x.abs.bytes(buf) - 1 // i >= 0 21 b := intGobVersion << 1 // make space for sign bit 22 if x.neg { 23 b |= 1 24 } 25 buf[i] = b 26 return buf[i:], nil 27 } 28 29 // GobDecode implements the gob.GobDecoder interface. 30 func (z *Int) GobDecode(buf []byte) error { 31 if len(buf) == 0 { 32 // Other side sent a nil or default value. 33 *z = Int{} 34 return nil 35 } 36 b := buf[0] 37 if b>>1 != intGobVersion { 38 return fmt.Errorf("Int.GobDecode: encoding version %d not supported", b>>1) 39 } 40 z.neg = b&1 != 0 41 z.abs = z.abs.setBytes(buf[1:]) 42 return nil 43 } 44 45 // MarshalText implements the encoding.TextMarshaler interface. 46 func (x *Int) MarshalText() (text []byte, err error) { 47 if x == nil { 48 return []byte("<nil>"), nil 49 } 50 return x.abs.itoa(x.neg, 10), nil 51 } 52 53 // UnmarshalText implements the encoding.TextUnmarshaler interface. 54 func (z *Int) UnmarshalText(text []byte) error { 55 // TODO(gri): get rid of the []byte/string conversion 56 if _, ok := z.SetString(string(text), 0); !ok { 57 return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Int", text) 58 } 59 return nil 60 } 61 62 // The JSON marshalers are only here for API backward compatibility 63 // (programs that explicitly look for these two methods). JSON works 64 // fine with the TextMarshaler only. 65 66 // MarshalJSON implements the json.Marshaler interface. 67 func (x *Int) MarshalJSON() ([]byte, error) { 68 return x.MarshalText() 69 } 70 71 // UnmarshalJSON implements the json.Unmarshaler interface. 72 func (z *Int) UnmarshalJSON(text []byte) error { 73 // Ignore null, like in the main JSON package. 74 if string(text) == "null" { 75 return nil 76 } 77 return z.UnmarshalText(text) 78 }