internal/radix51: refactor ToBig and FromBig

This commit is contained in:
Filippo Valsorda 2019-03-02 22:50:13 -05:00 committed by George Tankersley
parent 2a0f4ba3cc
commit 22cdf749a2
1 changed files with 20 additions and 27 deletions

View File

@ -327,49 +327,42 @@ func sliceForAppend(in []byte, n int) (head, tail []byte) {
return return
} }
func (v *FieldElement) FromBig(num *big.Int) *FieldElement { // FromBig sets v = n and returns v. The bit length of n must not exceed 256.
var buf [32]byte func (v *FieldElement) FromBig(n *big.Int) *FieldElement {
if n.BitLen() > 32*8 {
panic("ed25519: invalid field element input size")
}
offset := 0 buf := make([]byte, 0, 32)
words := num.Bits() for _, word := range n.Bits() {
numWords := len(words) for i := 0; i < bits.UintSize; i += 8 {
if len(buf) >= cap(buf) {
for n := 0; n < numWords; n++ {
word := words[n]
for i := 0; i < bits.UintSize/8; i++ {
if offset >= len(buf) {
break break
} }
buf[offset] = byte(word >> uint((i << 3))) buf = append(buf, byte(word))
offset++ word >>= 8
} }
} }
return v.FromBytes(buf[:]) return v.FromBytes(buf[:32])
} }
// ToBig returns v as a big.Int.
func (v *FieldElement) ToBig() *big.Int { func (v *FieldElement) ToBig() *big.Int {
buf := v.AppendBytes(nil) buf := v.AppendBytes(nil)
numWords := 256 / bits.UintSize words := make([]big.Word, 32*8/bits.UintSize)
words := make([]big.Word, numWords) for n := range words {
for i := 0; i < bits.UintSize; i += 8 {
offset := 0 if len(buf) == 0 {
byteSize := uint(bits.UintSize >> 3)
for n := 0; n < numWords; n++ {
word := uint(0)
for i := uint(0); i < byteSize; i++ {
if offset >= len(buf) {
break break
} }
word |= uint(buf[offset]) << (i << 3) words[n] |= big.Word(buf[0]) << big.Word(i)
offset++ buf = buf[1:]
} }
words[n] = big.Word(word)
} }
out := new(big.Int) return new(big.Int).SetBits(words)
return out.SetBits(words)
} }
// Equal returns 1 if v and u are equal, and 0 otherwise. // Equal returns 1 if v and u are equal, and 0 otherwise.