Add MsgPack Marshal and Unmarshal Test Case

This commit is contained in:
13981712066 2021-12-06 09:09:53 +08:00
parent 6ed1468fb5
commit 879e52d70a
2 changed files with 63 additions and 7 deletions

55
decimal_magpack_test.go Normal file
View file

@ -0,0 +1,55 @@
package decimal
import (
"testing"
)
func TestMsgPack(t *testing.T) {
for _, x := range testTable {
s := x.short
// limit to 31 digits
if len(s) > 31 {
s = s[:31]
if s[30] == '.' {
s = s[:30]
}
}
// Prepare Test Decimal Data
amount, err := NewFromString(s)
if err != nil{
t.Error(err)
}
s = amount.String()
// MarshalMsg
var b []byte
out, err := amount.MarshalMsg(b)
if err != nil{
t.Errorf("error marshalMsg %s: %v", s, err)
}
// check msg type
typ := out[0] & 0xe0
if typ != 0xa0 {
t.Errorf("error marshalMsg, expected type = %b, got %b", 0xa0, typ)
}
// check msg len
sz := int(out[0] & 0x1f)
if sz != len(s) {
t.Errorf("error marshalMsg, expected size = %d, got %d", len(s), sz)
}
// UnmarshalMsg
var unmarshalAmount Decimal
_, err = unmarshalAmount.UnmarshalMsg(out)
if err != nil{
t.Errorf("error unmarshalMsg %s: %v", s, err)
}else if !unmarshalAmount.Equal(amount) {
t.Errorf("expected %s, got %s (%s, %d)",
amount.String(), unmarshalAmount.String(),
unmarshalAmount.value.String(), unmarshalAmount.exp)
}
}
}

View file

@ -9,17 +9,18 @@ var (
) )
// MarshalMsg implements msgp.Marshaler // MarshalMsg implements msgp.Marshaler
// Note: limit to 31 digits, if d.IntPart size large than 31, will be lose.
func (d Decimal) MarshalMsg(b []byte) (o []byte, err error) { func (d Decimal) MarshalMsg(b []byte) (o []byte, err error) {
o = require(b, d.Msgsize()) o = require(b, d.Msgsize())
str := d.String() str := d.String()
sz := len(str) sz := len(str)
// limit to 30 digits // limit to 31 digits
// note, if d.IntPart size large than 30, will be lose. // note, if d.IntPart size large than 31, will be lose.
if sz > 30 { if sz > 31 {
sz = 30 sz = 31
// if last char is '.' then limit to 20 digits // if last char is '.' then limit to 30 digits
if str[29] == '.' { if str[30] == '.' {
sz = 29 sz = 30
} }
str = str[:sz] str = str[:sz]