github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/common/math/integer.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 13 14 import ( 15 "fmt" 16 "strconv" 17 ) 18 19 const ( 20 // Integer limit values. 21 MaxInt8 = 1<<7 - 1 22 MinInt8 = -1 << 7 23 MaxInt16 = 1<<15 - 1 24 MinInt16 = -1 << 15 25 MaxInt32 = 1<<31 - 1 26 MinInt32 = -1 << 31 27 MaxInt64 = 1<<63 - 1 28 MinInt64 = -1 << 63 29 MaxUint8 = 1<<8 - 1 30 MaxUint16 = 1<<16 - 1 31 MaxUint32 = 1<<32 - 1 32 MaxUint64 = 1<<64 - 1 33 ) 34 35 // HexOrDecimal64 marshals uint64 as hex or decimal. 36 type HexOrDecimal64 uint64 37 38 // UnmarshalText implements encoding.TextUnmarshaler. 39 func (i *HexOrDecimal64) UnmarshalText(input []byte) error { 40 int, ok := ParseUint64(string(input)) 41 if !ok { 42 return fmt.Errorf("invalid hex or decimal integer %q", input) 43 } 44 *i = HexOrDecimal64(int) 45 return nil 46 } 47 48 // MarshalText implements encoding.TextMarshaler. 49 func (i HexOrDecimal64) MarshalText() ([]byte, error) { 50 return []byte(fmt.Sprintf("%#x", uint64(i))), nil 51 } 52 53 // ParseUint64 parses s as an integer in decimal or hexadecimal syntax. 54 // Leading zeros are accepted. The empty string parses as zero. 55 func ParseUint64(s string) (uint64, bool) { 56 if s == "" { 57 return 0, true 58 } 59 if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") { 60 v, err := strconv.ParseUint(s[2:], 16, 64) 61 return v, err == nil 62 } 63 v, err := strconv.ParseUint(s, 10, 64) 64 return v, err == nil 65 } 66 67 // MustParseUint64 parses s as an integer and panics if the string is invalid. 68 func MustParseUint64(s string) uint64 { 69 v, ok := ParseUint64(s) 70 if !ok { 71 panic("invalid unsigned 64 bit integer: " + s) 72 } 73 return v 74 } 75 76 // NOTE: The following methods need to be optimised using either bit checking or asm 77 78 // SafeSub returns subtraction result and whether overflow occurred. 79 func SafeSub(x, y uint64) (uint64, bool) { 80 return x - y, x < y 81 } 82 83 // SafeAdd returns the result and whether overflow occurred. 84 func SafeAdd(x, y uint64) (uint64, bool) { 85 return x + y, y > MaxUint64-x 86 } 87 88 // SafeMul returns multiplication result and whether overflow occurred. 89 func SafeMul(x, y uint64) (uint64, bool) { 90 if x == 0 || y == 0 { 91 return 0, false 92 } 93 return x * y, y > MaxUint64/x 94 }