Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

math.gno

0.72 Kb · 29 lines
 1package mimir
 2
 3import "math/bits"
 4
 5// MulDiv returns floor(a*b/d) without overflowing the 128-bit product.
 6// It panics on negative inputs, a zero divisor or a result above int64.
 7func MulDiv(a, b, d int64) int64 {
 8	if a < 0 || b < 0 || d <= 0 {
 9		panic("mimir: MulDiv needs a, b >= 0 and d > 0")
10	}
11	hi, lo := bits.Mul64(uint64(a), uint64(b))
12	if hi >= uint64(d) {
13		panic("mimir: MulDiv overflow")
14	}
15	q, _ := bits.Div64(hi, lo, uint64(d))
16	if q > uint64(1<<63-1) {
17		panic("mimir: MulDiv overflow")
18	}
19	return int64(q)
20}
21
22// Add returns a+b, panicking on overflow, so a sum of stakes can never wrap.
23func Add(a, b int64) int64 {
24	c := a + b
25	if (b > 0 && c < a) || (b < 0 && c > a) {
26		panic("mimir: add overflow")
27	}
28	return c
29}