github.com/avence12/go-ethereum@v1.5.10-0.20170320123548-1dfd65f6d047/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  	"math/big"
    22  )
    23  
    24  var (
    25  	tt255     = BigPow(2, 255)
    26  	tt256     = BigPow(2, 256)
    27  	tt256m1   = new(big.Int).Sub(tt256, big.NewInt(1))
    28  	MaxBig256 = new(big.Int).Set(tt256m1)
    29  )
    30  
    31  const (
    32  	// number of bits in a big.Word
    33  	wordBits = 32 << (uint64(^big.Word(0)) >> 63)
    34  	// number of bytes in a big.Word
    35  	wordBytes = wordBits / 8
    36  )
    37  
    38  // ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax.
    39  // Leading zeros are accepted. The empty string parses as zero.
    40  func ParseBig256(s string) (*big.Int, bool) {
    41  	if s == "" {
    42  		return new(big.Int), true
    43  	}
    44  	var bigint *big.Int
    45  	var ok bool
    46  	if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") {
    47  		bigint, ok = new(big.Int).SetString(s[2:], 16)
    48  	} else {
    49  		bigint, ok = new(big.Int).SetString(s, 10)
    50  	}
    51  	if ok && bigint.BitLen() > 256 {
    52  		bigint, ok = nil, false
    53  	}
    54  	return bigint, ok
    55  }
    56  
    57  // MustParseBig parses s as a 256 bit big integer and panics if the string is invalid.
    58  func MustParseBig256(s string) *big.Int {
    59  	v, ok := ParseBig256(s)
    60  	if !ok {
    61  		panic("invalid 256 bit integer: " + s)
    62  	}
    63  	return v
    64  }
    65  
    66  // BigPow returns a ** b as a big integer.
    67  func BigPow(a, b int64) *big.Int {
    68  	r := big.NewInt(a)
    69  	return r.Exp(r, big.NewInt(b), nil)
    70  }
    71  
    72  // BigMax returns the larger of x or y.
    73  func BigMax(x, y *big.Int) *big.Int {
    74  	if x.Cmp(y) < 0 {
    75  		return y
    76  	}
    77  	return x
    78  }
    79  
    80  // BigMin returns the smaller of x or y.
    81  func BigMin(x, y *big.Int) *big.Int {
    82  	if x.Cmp(y) > 0 {
    83  		return y
    84  	}
    85  	return x
    86  }
    87  
    88  // FirstBitSet returns the index of the first 1 bit in v, counting from LSB.
    89  func FirstBitSet(v *big.Int) int {
    90  	for i := 0; i < v.BitLen(); i++ {
    91  		if v.Bit(i) > 0 {
    92  			return i
    93  		}
    94  	}
    95  	return v.BitLen()
    96  }
    97  
    98  // PaddedBigBytes encodes a big integer as a big-endian byte slice. The length
    99  // of the slice is at least n bytes.
   100  func PaddedBigBytes(bigint *big.Int, n int) []byte {
   101  	if bigint.BitLen()/8 >= n {
   102  		return bigint.Bytes()
   103  	}
   104  	ret := make([]byte, n)
   105  	ReadBits(bigint, ret)
   106  	return ret
   107  }
   108  
   109  // ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure
   110  // that buf has enough space. If buf is too short the result will be incomplete.
   111  func ReadBits(bigint *big.Int, buf []byte) {
   112  	i := len(buf)
   113  	for _, d := range bigint.Bits() {
   114  		for j := 0; j < wordBytes && i > 0; j++ {
   115  			i--
   116  			buf[i] = byte(d)
   117  			d >>= 8
   118  		}
   119  	}
   120  }
   121  
   122  // U256 encodes as a 256 bit two's complement number. This operation is destructive.
   123  func U256(x *big.Int) *big.Int {
   124  	return x.And(x, tt256m1)
   125  }
   126  
   127  // S256 interprets x as a two's complement number.
   128  // x must not exceed 256 bits (the result is undefined if it does) and is not modified.
   129  //
   130  //   S256(0)        = 0
   131  //   S256(1)        = 1
   132  //   S256(2**255)   = -2**255
   133  //   S256(2**256-1) = -1
   134  func S256(x *big.Int) *big.Int {
   135  	if x.Cmp(tt255) < 0 {
   136  		return x
   137  	} else {
   138  		return new(big.Int).Sub(x, tt256)
   139  	}
   140  }
   141  
   142  // Exp implements exponentiation by squaring.
   143  // Exp returns a newly-allocated big integer and does not change
   144  // base or exponent. The result is truncated to 256 bits.
   145  //
   146  // Courtesy @karalabe and @chfast
   147  func Exp(base, exponent *big.Int) *big.Int {
   148  	result := big.NewInt(1)
   149  
   150  	for _, word := range exponent.Bits() {
   151  		for i := 0; i < wordBits; i++ {
   152  			if word&1 == 1 {
   153  				U256(result.Mul(result, base))
   154  			}
   155  			U256(base.Mul(base, base))
   156  			word >>= 1
   157  		}
   158  	}
   159  	return result
   160  }