mirror of
https://github.com/luxfi/math.git
synced 2026-07-27 03:38:49 +00:00
Reorganize math package into subpackages
- Create math/big for big.Int utilities (HexOrDecimal256, U256, parsing) - Create math/safe for overflow-safe arithmetic (SafeAdd, SafeMul, etc.) - Move averager files to root package level - Add re-exports in root package for backwards compatibility - Update README with new package structure documentation - Remove old math/meter directory (consolidated elsewhere) - Remove redundant math/ subdirectory structure
This commit is contained in:
@@ -59,3 +59,23 @@ func Mul[T constraints.Unsigned](a, b T) (T, error) {
|
||||
func AbsDiff[T constraints.Unsigned](a, b T) T {
|
||||
return max(a, b) - min(a, b)
|
||||
}
|
||||
|
||||
// SafeAdd returns x+y and whether overflow occurred.
|
||||
func SafeAdd(x, y uint64) (uint64, bool) {
|
||||
sum := x + y
|
||||
return sum, sum < x
|
||||
}
|
||||
|
||||
// SafeSub returns x-y and whether underflow occurred.
|
||||
func SafeSub(x, y uint64) (uint64, bool) {
|
||||
return x - y, x < y
|
||||
}
|
||||
|
||||
// SafeMul returns x*y and whether overflow occurred.
|
||||
func SafeMul(x, y uint64) (uint64, bool) {
|
||||
if x == 0 || y == 0 {
|
||||
return 0, false
|
||||
}
|
||||
result := x * y
|
||||
return result, result/y != x
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user