// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file implements encoding/decoding of Rats.

package big

import (
	
	
	
	
)

// Gob codec version. Permits backward-compatible changes to the encoding.
const ratGobVersion byte = 1

// GobEncode implements the [encoding/gob.GobEncoder] interface.
func ( *Rat) () ([]byte, error) {
	if  == nil {
		return nil, nil
	}
	 := make([]byte, 1+4+(len(.a.abs)+len(.b.abs))*_S) // extra bytes for version and sign bit (1), and numerator length (4)
	 := .b.abs.bytes()
	 := .a.abs.bytes([:])
	 :=  - 
	if int(uint32()) !=  {
		// this should never happen
		return nil, errors.New("Rat.GobEncode: numerator too large")
	}
	byteorder.BePutUint32([-4:], uint32())
	 -= 1 + 4
	 := ratGobVersion << 1 // make space for sign bit
	if .a.neg {
		 |= 1
	}
	[] = 
	return [:], nil
}

// GobDecode implements the [encoding/gob.GobDecoder] interface.
func ( *Rat) ( []byte) error {
	if len() == 0 {
		// Other side sent a nil or default value.
		* = Rat{}
		return nil
	}
	if len() < 5 {
		return errors.New("Rat.GobDecode: buffer too small")
	}
	 := [0]
	if >>1 != ratGobVersion {
		return fmt.Errorf("Rat.GobDecode: encoding version %d not supported", >>1)
	}
	const  = 1 + 4
	 := byteorder.BeUint32([-4 : ])
	if uint64() > math.MaxInt- {
		return errors.New("Rat.GobDecode: invalid length")
	}
	 :=  + int()
	if len() <  {
		return errors.New("Rat.GobDecode: buffer too small")
	}
	.a.neg = &1 != 0
	.a.abs = .a.abs.setBytes([:])
	.b.abs = .b.abs.setBytes([:])
	return nil
}

// MarshalText implements the [encoding.TextMarshaler] interface.
func ( *Rat) () ( []byte,  error) {
	if .IsInt() {
		return .a.MarshalText()
	}
	return .marshal(), nil
}

// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
func ( *Rat) ( []byte) error {
	// TODO(gri): get rid of the []byte/string conversion
	if ,  := .SetString(string()); ! {
		return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Rat", )
	}
	return nil
}