github.com/ylsGit/go-ethereum@v1.6.5/common/math/big.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package math provides integer math utilities.
    18  package math
    19  
    20  import (
    21  	"fmt"
    22  	"math/big"
    23  )
    24  
    25  var (
    26  	tt255     = BigPow(2, 255)
    27  	tt256     = BigPow(2, 256)
    28  	tt256m1   = new(big.Int).Sub(tt256, big.NewInt(1))
    29  	MaxBig256 = new(big.Int).Set(tt256m1)
    30  	tt63      = BigPow(2, 63)
    31  	MaxBig63  = new(big.Int).Sub(tt63, big.NewInt(1))
    32  )
    33  
    34  const (
    35  	// number of bits in a big.Word
    36  	wordBits = 32 << (uint64(^big.Word(0)) >> 63)
    37  	// number of bytes in a big.Word
    38  	wordBytes = wordBits / 8
    39  )
    40  
    41  // HexOrDecimal256 marshals big.Int as hex or decimal.
    42  type HexOrDecimal256 big.Int
    43  
    44  // UnmarshalText implements encoding.TextUnmarshaler.
    45  func (i *HexOrDecimal256) UnmarshalText(input []byte) error {
    46  	bigint, ok := ParseBig256(string(input))
    47  	if !ok {
    48  		return fmt.Errorf("invalid hex or decimal integer %q", input)
    49  	}
    50  	*i = HexOrDecimal256(*bigint)
    51  	return nil
    52  }
    53  
    54  // MarshalText implements encoding.TextMarshaler.
    55  func (i *HexOrDecimal256) MarshalText() ([]byte, error) {
    56  	if i == nil {
    57  		return []byte("0x0"), nil
    58  	}
    59  	return []byte(fmt.Sprintf("%#x", (*big.Int)(i))), nil
    60  }
    61  
    62  // ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax.
    63  // Leading zeros are accepted. The empty string parses as zero.
    64  func ParseBig256(s string) (*big.Int, bool) {
    65  	if s == "" {
    66  		return new(big.Int), true
    67  	}
    68  	var bigint *big.Int
    69  	var ok bool
    70  	if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") {
    71  		bigint, ok = new(big.Int).SetString(s[2:], 16)
    72  	} else {
    73  		bigint, ok = new(big.Int).SetString(s, 10)
    74  	}
    75  	if ok && bigint.BitLen() > 256 {
    76  		bigint, ok = nil, false
    77  	}
    78  	return bigint, ok
    79  }
    80  
    81  // MustParseBig parses s as a 256 bit big integer and panics if the string is invalid.
    82  func MustParseBig256(s string) *big.Int {
    83  	v, ok := ParseBig256(s)
    84  	if !ok {
    85  		panic("invalid 256 bit integer: " + s)
    86  	}
    87  	return v
    88  }
    89  
    90  // BigPow returns a ** b as a big integer.
    91  func BigPow(a, b int64) *big.Int {
    92  	r := big.NewInt(a)
    93  	return r.Exp(r, big.NewInt(b), nil)
    94  }
    95  
    96  // BigMax returns the larger of x or y.
    97  func BigMax(x, y *big.Int) *big.Int {
    98  	if x.Cmp(y) < 0 {
    99  		return y
   100  	}
   101  	return x
   102  }
   103  
   104  // BigMin returns the smaller of x or y.
   105  func BigMin(x, y *big.Int) *big.Int {
   106  	if x.Cmp(y) > 0 {
   107  		return y
   108  	}
   109  	return x
   110  }
   111  
   112  // FirstBitSet returns the index of the first 1 bit in v, counting from LSB.
   113  func FirstBitSet(v *big.Int) int {
   114  	for i := 0; i < v.BitLen(); i++ {
   115  		if v.Bit(i) > 0 {
   116  			return i
   117  		}
   118  	}
   119  	return v.BitLen()
   120  }
   121  
   122  // PaddedBigBytes encodes a big integer as a big-endian byte slice. The length
   123  // of the slice is at least n bytes.
   124  func PaddedBigBytes(bigint *big.Int, n int) []byte {
   125  	if bigint.BitLen()/8 >= n {
   126  		return bigint.Bytes()
   127  	}
   128  	ret := make([]byte, n)
   129  	ReadBits(bigint, ret)
   130  	return ret
   131  }
   132  
   133  // ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure
   134  // that buf has enough space. If buf is too short the result will be incomplete.
   135  func ReadBits(bigint *big.Int, buf []byte) {
   136  	i := len(buf)
   137  	for _, d := range bigint.Bits() {
   138  		for j := 0; j < wordBytes && i > 0; j++ {
   139  			i--
   140  			buf[i] = byte(d)
   141  			d >>= 8
   142  		}
   143  	}
   144  }
   145  
   146  // U256 encodes as a 256 bit two's complement number. This operation is destructive.
   147  func U256(x *big.Int) *big.Int {
   148  	return x.And(x, tt256m1)
   149  }
   150  
   151  // S256 interprets x as a two's complement number.
   152  // x must not exceed 256 bits (the result is undefined if it does) and is not modified.
   153  //
   154  //   S256(0)        = 0
   155  //   S256(1)        = 1
   156  //   S256(2**255)   = -2**255
   157  //   S256(2**256-1) = -1
   158  func S256(x *big.Int) *big.Int {
   159  	if x.Cmp(tt255) < 0 {
   160  		return x
   161  	} else {
   162  		return new(big.Int).Sub(x, tt256)
   163  	}
   164  }
   165  
   166  // Exp implements exponentiation by squaring.
   167  // Exp returns a newly-allocated big integer and does not change
   168  // base or exponent. The result is truncated to 256 bits.
   169  //
   170  // Courtesy @karalabe and @chfast
   171  func Exp(base, exponent *big.Int) *big.Int {
   172  	result := big.NewInt(1)
   173  
   174  	for _, word := range exponent.Bits() {
   175  		for i := 0; i < wordBits; i++ {
   176  			if word&1 == 1 {
   177  				U256(result.Mul(result, base))
   178  			}
   179  			U256(base.Mul(base, base))
   180  			word >>= 1
   181  		}
   182  	}
   183  	return result
   184  }