-
Notifications
You must be signed in to change notification settings - Fork 95
/
uint256.go
85 lines (77 loc) · 2.04 KB
/
uint256.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
76
77
78
79
80
81
82
83
84
85
package curl
// uint256 is a simple 256-bit uint modelled as an array of uint64.
type uint256 [4]uint64
// bit returns the value of the i-th bit of z.
// If i ≥ 256 the bit a position i % 256 is considered.
func (z *uint256) bit(i uint) uint {
return uint((z[(i/64)%4] >> (i % 64)) & 1)
}
// setBit sets the i-th bit in z to 1 and returns z.
// If i ≥ 256 the bit a position i % 256 is considered.
func (z *uint256) setBit(i uint) *uint256 {
z[(i/64)%4] |= uint64(1) << (i % 64)
return z
}
// shrInto sets z = z | x >> s and returns z.
func (z *uint256) shrInto(x *uint256, s uint) *uint256 {
offset, r := s/64, s%64
if r == 0 { // no shifting is needed
for i := offset; i < 4; i++ {
z[(i-offset)%4] |= x[i] // the modulus is a hint to the compiler that no bound checks are needed
}
return z
}
l := 64 - r
l &= 63 // hint to the compiler that shifts by l don't need guard code
switch offset {
case 0:
z[0] |= x[0]>>r | x[1]<<l
z[1] |= x[1]>>r | x[2]<<l
z[2] |= x[2]>>r | x[3]<<l
z[3] |= x[3] >> r
case 1:
z[0] |= x[1]>>r | x[2]<<l
z[1] |= x[2]>>r | x[3]<<l
z[2] |= x[3] >> r
case 2:
z[0] |= x[2]>>r | x[3]<<l
z[1] |= x[3] >> r
case 3:
z[0] |= x[3] >> r
}
return z
}
// shlInto sets z = z | x << s and returns z.
func (z *uint256) shlInto(x *uint256, s uint) *uint256 {
offset, l := s/64, s%64
if l == 0 { // no shifting is needed
for i := offset; i < 4; i++ {
z[i] |= x[(i-offset)%4] // the modulus is a hint to the compiler that no bound checks are needed
}
return z
}
r := 64 - l
r &= 63 // hint to the compiler that shifts by r don't need guard code
switch offset {
case 0:
z[3] |= x[3]<<l | x[2]>>r
z[2] |= x[2]<<l | x[1]>>r
z[1] |= x[1]<<l | x[0]>>r
z[0] |= x[0] << l
case 1:
z[3] |= x[2]<<l | x[1]>>r
z[2] |= x[1]<<l | x[0]>>r
z[1] |= x[0] << l
case 2:
z[3] |= x[1]<<l | x[0]>>r
z[2] |= x[0] << l
case 3:
z[3] |= x[0] << l
}
return z
}
// norm243 clears the bits higher than 243 in z and returns z.
func (z *uint256) norm243() *uint256 {
z[3] &= 1<<(64-(256-243)) - 1
return z
}