github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/common/math/big.go (about)

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