Source file src/math/big/ratmarsh.go

     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 Rats.
     6  
     7  package big
     8  
     9  import (
    10  	"encoding/binary"
    11  	"errors"
    12  	"fmt"
    13  )
    14  
    15  // Gob codec version. Permits backward-compatible changes to the encoding.
    16  const ratGobVersion byte = 1
    17  
    18  // GobEncode implements the gob.GobEncoder interface.
    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) // extra bytes for version and sign bit (1), and numerator length (4)
    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  		// this should never happen
    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 // make space for sign bit
    34  	if x.a.neg {
    35  		b |= 1
    36  	}
    37  	buf[j] = b
    38  	return buf[j:], nil
    39  }
    40  
    41  // GobDecode implements the gob.GobDecoder interface.
    42  func (z *Rat) GobDecode(buf []byte) error {
    43  	if len(buf) == 0 {
    44  		// Other side sent a nil or default value.
    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  // MarshalText implements the encoding.TextMarshaler interface.
    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  // UnmarshalText implements the encoding.TextUnmarshaler interface.
    75  func (z *Rat) UnmarshalText(text []byte) error {
    76  	// TODO(gri): get rid of the []byte/string conversion
    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