-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathid.go
108 lines (92 loc) · 1.84 KB
/
id.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
package hazy
import (
"math/big"
"sync"
)
type ID uint64
const IDLength = 13
var Prime *big.Int
var Coprime *big.Int
var Pepper uint64
var uint64Max = new(big.Int).SetUint64(18446744073709551615)
var Zero ID
var pool = sync.Pool{
New: func() interface{} {
return new(big.Int)
},
}
func Initialize(prime uint64, coprime uint64, pepper uint64) error {
Prime = new(big.Int).SetUint64(prime)
if !Prime.ProbablyPrime(40) {
return ErrInvalidPrime
}
Coprime = new(big.Int).SetUint64(coprime)
Pepper = pepper
Zero = ID(obscure(0))
return nil
}
func (id ID) Clear() uint64 {
if id.IsZero() {
return 0
}
return reveal(uint64(id))
}
func (id ID) IsZero() bool {
return id == 0 || id.Equal(Zero)
}
func (id ID) Equal(other ID) bool {
return id == other
}
func (id ID) String() string {
return string(Base32Encode(uint64(id)))
}
func Obscure(id uint64) ID {
return ID(obscure(id))
}
func Reveal(id uint64) ID {
return ID(id)
}
func obscure(id uint64) uint64 {
i := pool.Get().(*big.Int)
i.SetUint64(id ^ Pepper)
i.Mul(i, Prime)
i.And(i, uint64Max)
id = i.Uint64()
pool.Put(i)
return id
}
func reveal(id uint64) uint64 {
i := pool.Get().(*big.Int)
i.SetUint64(id)
i.Mul(i, Coprime)
i.And(i, uint64Max)
id = i.Uint64() ^ Pepper
pool.Put(i)
return id
}
func ObscureWithPrime(id uint64, prime uint64, pepper uint64) (uint64, error) {
i := pool.Get().(*big.Int)
i.SetUint64(id ^ pepper)
p := pool.Get().(*big.Int)
p.SetUint64(prime)
if !p.ProbablyPrime(40) {
return 0, ErrInvalidPrime
}
i.Mul(i, p)
i.And(i, uint64Max)
id = i.Uint64()
pool.Put(i)
pool.Put(p)
return id, nil
}
func RevealWithCoprime(id uint64, coprime uint64, pepper uint64) uint64 {
i := pool.Get().(*big.Int)
i.SetUint64(id)
cp := pool.Get().(*big.Int)
cp.SetUint64(coprime)
i.Mul(i, cp)
i.And(i, uint64Max)
id = i.Uint64() ^ pepper
pool.Put(i)
return id
}