-
Notifications
You must be signed in to change notification settings - Fork 649
/
safe_math.go
75 lines (64 loc) · 1.55 KB
/
safe_math.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package math
import (
"errors"
"math"
"golang.org/x/exp/constraints"
"github.com/ava-labs/avalanchego/utils"
)
var errOverflow = errors.New("overflow occurred")
func Max[T constraints.Ordered](max T, nums ...T) T {
for _, num := range nums {
if num > max {
max = num
}
}
return max
}
func Min[T constraints.Ordered](min T, nums ...T) T {
for _, num := range nums {
if num < min {
min = num
}
}
return min
}
// Add64 returns:
// 1) a + b
// 2) If there is overflow, an error
//
// Note that we don't have a generic Add function because checking for
// an overflow requires knowing the max size of a given type, which we
// don't know if we're adding generic types.
func Add64(a, b uint64) (uint64, error) {
if a > math.MaxUint64-b {
return 0, errOverflow
}
return a + b, nil
}
// Sub returns:
// 1) a - b
// 2) If there is underflow, an error
func Sub[T constraints.Unsigned](a, b T) (T, error) {
if a < b {
return utils.Zero[T](), errOverflow
}
return a - b, nil
}
// Mul64 returns:
// 1) a * b
// 2) If there is overflow, an error
//
// Note that we don't have a generic Mul function because checking for
// an overflow requires knowing the max size of a given type, which we
// don't know if we're adding generic types.
func Mul64(a, b uint64) (uint64, error) {
if b != 0 && a > math.MaxUint64/b {
return 0, errOverflow
}
return a * b, nil
}
func AbsDiff[T constraints.Unsigned](a, b T) T {
return Max(a, b) - Min(a, b)
}