Fix numeric EncodeBinary bug

pull/304/head
Wei Congrui 2017-08-18 15:20:39 +08:00
parent 83f4d76e68
commit ce654ad1e1
2 changed files with 43 additions and 3 deletions

View File

@ -16,6 +16,7 @@ import (
const nbase = 10000
var big0 *big.Int = big.NewInt(0)
var big1 *big.Int = big.NewInt(1)
var big10 *big.Int = big.NewInt(10)
var big100 *big.Int = big.NewInt(100)
var big1000 *big.Int = big.NewInt(1000)
@ -507,6 +508,7 @@ func (src *Numeric) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
divisor := &big.Int{}
divisor.Exp(big10, big.NewInt(int64(-exp)), nil)
wholePart.DivMod(absInt, divisor, fracPart)
fracPart.Add(fracPart, divisor)
} else {
wholePart = absInt
}
@ -518,9 +520,11 @@ func (src *Numeric) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
wholeDigits = append(wholeDigits, int16(remainder.Int64()))
}
for fracPart.Cmp(big0) != 0 {
fracPart.DivMod(fracPart, bigNBase, remainder)
fracDigits = append(fracDigits, int16(remainder.Int64()))
if fracPart.Cmp(big0) != 0 {
for fracPart.Cmp(big1) != 0 {
fracPart.DivMod(fracPart, bigNBase, remainder)
fracDigits = append(fracDigits, int16(remainder.Int64()))
}
}
buf = pgio.AppendInt16(buf, int16(len(wholeDigits)+len(fracDigits)))

View File

@ -317,3 +317,39 @@ func TestNumericAssignTo(t *testing.T) {
}
}
}
func TestNumericEncodeDecodeBinary(t *testing.T) {
ci := pgtype.NewConnInfo()
tests := []interface{}{
123,
0.000012345,
1.00002345,
}
for i, tt := range tests {
toString := func(n *pgtype.Numeric) string {
ci := pgtype.NewConnInfo()
text, err := n.EncodeText(ci, nil)
if err != nil {
t.Errorf("%d: %v", i, err)
}
return string(text)
}
numeric := &pgtype.Numeric{}
numeric.Set(tt)
encoded, err := numeric.EncodeBinary(ci, nil)
if err != nil {
t.Errorf("%d: %v", i, err)
}
decoded := &pgtype.Numeric{}
decoded.DecodeBinary(ci, encoded)
text0 := toString(numeric)
text1 := toString(decoded)
if text0 != text1 {
t.Errorf("%d: expected %v to equal to %v, but doesn't", i, text0, text1)
}
}
}