-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
118 lines (103 loc) · 2.03 KB
/
util.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package ecc
import (
"math/big"
"sync"
)
func BigFromDecimal(s string) *big.Int {
b, ok := new(big.Int).SetString(s, 10)
if !ok {
panic("ecc: internal error: invalid encoding")
}
return b
}
func BigFromHex(s string) *big.Int {
b, ok := new(big.Int).SetString(s, 16)
if !ok {
panic("ecc: internal error: invalid encoding")
}
return b
}
func NextPrime(n *big.Int) *big.Int {
if n.Cmp(big.NewInt(1)) <= 0 {
return big.NewInt(2)
}
if n.Cmp(big.NewInt(2)) == 0 {
return big.NewInt(3)
}
p := new(big.Int).Set(n)
if p.Bits()[0]&0x1 == 0 {
p.Add(p, big.NewInt(1))
if p.ProbablyPrime(20) {
return p
}
}
for {
p.Add(p, big.NewInt(2))
if p.ProbablyPrime(20) {
break
}
}
return p
}
// CRT Chinese remainder theorem
func CRT(a, n []*big.Int) *big.Int {
if a == nil || n == nil {
return nil
}
p := big.NewInt(1)
for _, x := range n {
p.Mul(p, x)
}
var c, q, s, z big.Int
for i, x := range n {
q.Div(p, x)
z.GCD(nil, &s, x, &q)
if z.Int64() != 1 {
return nil
}
c.Add(&c, s.Mul(a[i], s.Mul(&s, &q)))
}
return c.Mod(&c, p)
}
// FermatInverse calculates the inverse of k in GF(P) using Fermat's method
// (exponentiation modulo P - 2, per Euler's theorem).
func FermatInverse(k, N *big.Int) *big.Int {
return new(big.Int).Exp(k, new(big.Int).Sub(N, big.NewInt(2)), N)
}
func FanIn(done <-chan interface{}, channels ...<-chan interface{}) <-chan interface{} {
var wg sync.WaitGroup
multiplexedStream := make(chan interface{})
multiplex := func(c <-chan interface{}) {
defer wg.Done()
for s := range c {
select {
case <-done:
return
case multiplexedStream <- s:
}
}
}
wg.Add(len(channels))
for _, c := range channels {
go multiplex(c)
}
go func() {
wg.Wait()
close(multiplexedStream)
}()
return multiplexedStream
}
func ToTrace(done <-chan interface{}, stream <-chan interface{}) <-chan *Trace {
ch := make(chan *Trace)
go func() {
defer close(ch)
for v := range stream {
select {
case <-done:
return
case ch <- v.(*Trace):
}
}
}()
return ch
}