forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
safe_math.go
60 lines (51 loc) · 1.33 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
// Copyright (C) 2019-2024, 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/MetalBlockchain/metalgo/utils"
)
var (
ErrOverflow = errors.New("overflow")
ErrUnderflow = errors.New("underflow")
)
// 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](), ErrUnderflow
}
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)
}