/
math_integer.go
56 lines (48 loc) · 998 Bytes
/
math_integer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* Copyright (c) 2019 QLC Chain Team
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
package util
// SafeMul returns multiplication result and whether overflow occurred.
func SafeMul(x, y uint64) (uint64, bool) {
if x == 0 || y == 0 {
return 0, false
}
return x * y, y > MaxUint64/x
}
// SafeAdd returns the result and whether overflow occurred.
func SafeAdd(x, y uint64) (uint64, bool) {
return x + y, y > MaxUint64-x
}
// SafeSub returns subtraction result and whether overflow occurred.
func SafeSub(x, y uint64) (uint64, bool) {
return x - y, x < y
}
func Min(x, y uint64) uint64 {
if x < y {
return x
}
return y
}
func Max(x, y uint64) uint64 {
if x > y {
return x
}
return y
}
// UInt32Max returns the larger of x or y.
func UInt32Max(x, y uint32) uint32 {
if x < y {
return y
}
return x
}
// UInt32Max returns the smaller of x or y.
func UInt32Min(a, b uint32) uint32 {
if a < b {
return a
}
return b
}