Skip to content

Commit e9f4210

Browse files
committed
Extend int256 lib
1 parent c995787 commit e9f4210

File tree

1 file changed

+60
-5
lines changed

1 file changed

+60
-5
lines changed

protocol/lib/int256/int256.go

+60-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package int256
22

33
import (
4+
"math"
45
"math/big"
56

67
"github.com/holiman/uint256"
@@ -14,9 +15,14 @@ import (
1415
type Int uint256.Int
1516

1617
var (
17-
OneInt256 = NewInt(1)
18-
TenInt256 = NewInt(10)
19-
OneMillionInt256 = NewInt(1_000_000)
18+
One = NewInt(1)
19+
Ten = NewInt(10)
20+
OneMillion = NewInt(1_000_000)
21+
22+
MaxInt32 = NewInt(math.MaxInt32)
23+
MaxUint32 = NewInt(math.MaxUint32)
24+
MaxInt64 = NewInt(math.MaxInt64)
25+
MaxUint64 = NewInt(math.MaxUint32)
2026

2127
exp10Lookup = createExp10Lookup()
2228
)
@@ -159,7 +165,7 @@ func createExp10Lookup() map[uint64]uint256.Int {
159165
value := uint256.NewInt(1)
160166
for i := 0; i < 100; i++ {
161167
lookup[uint64(i)] = *new(uint256.Int).Set(value)
162-
value.Mul(value, (*uint256.Int)(TenInt256))
168+
value.Mul(value, (*uint256.Int)(Ten))
163169
}
164170
return lookup
165171
}
@@ -176,7 +182,7 @@ func mulExp10(z *uint256.Int, x *uint256.Int, y int64) *uint256.Int {
176182
if ok {
177183
exp10 = &lookup
178184
} else {
179-
exp10.Exp((*uint256.Int)(TenInt256), uint256.NewInt(abs))
185+
exp10.Exp((*uint256.Int)(Ten), uint256.NewInt(abs))
180186
}
181187
if y < 0 {
182188
return z.Div(x, exp10)
@@ -192,3 +198,52 @@ func (z *Int) MulExp10(x *Int, y int64) *Int {
192198
}
193199
return z.Neg((*Int)(mulExp10((*uint256.Int)(z), (*uint256.Int)(z.Neg(x)), y)))
194200
}
201+
202+
// --------------
203+
204+
func (z *Int) DivRoundUp(x *Int, y *Int) *Int {
205+
_, m := (*uint256.Int)(z).DivMod(
206+
(*uint256.Int)(x),
207+
(*uint256.Int)(y),
208+
new(uint256.Int),
209+
)
210+
if !m.IsZero() {
211+
z.Add(z, One)
212+
}
213+
return z
214+
}
215+
216+
func (z *Int) MulPpm(x *Int, ppm uint32) *Int {
217+
result := z.Mul(x, NewUnsignedInt(uint64(ppm)))
218+
return result.Div(result, OneMillion)
219+
}
220+
221+
func (z *Int) MulPpmRoundUp(x *Int, ppm uint32) *Int {
222+
z.Mul(x, NewUnsignedInt(uint64(ppm)))
223+
return z.DivRoundUp(z, OneMillion)
224+
}
225+
226+
func (z *Int) Uint64() uint64 {
227+
return (*uint256.Int)(z).Uint64()
228+
}
229+
230+
func (z *Int) Int64() int64 {
231+
if z.Sign() > 0 {
232+
return (int64)(z.Uint64())
233+
}
234+
return -(int64)(new(Int).Neg(z).Uint64())
235+
}
236+
237+
func (z *Int) Clamp(x, y *Int) *Int {
238+
if z.Cmp(x) < 0 {
239+
return z.Set(x)
240+
}
241+
if z.Cmp(y) > 0 {
242+
return z.Set(y)
243+
}
244+
return z
245+
}
246+
247+
func (z *Int) CmpAbs(x *Int) int {
248+
return new(Int).Abs(z).Cmp(new(Int).Abs(x))
249+
}

0 commit comments

Comments
 (0)