mirror of
https://github.com/shopspring/decimal.git
synced 2024-11-22 12:30:49 +01:00
Add MsgPack Marshal and Unmarshal Test Case
This commit is contained in:
parent
6ed1468fb5
commit
879e52d70a
2 changed files with 63 additions and 7 deletions
55
decimal_magpack_test.go
Normal file
55
decimal_magpack_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -9,17 +9,18 @@ var (
|
|||
)
|
||||
|
||||
// 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) {
|
||||
o = require(b, d.Msgsize())
|
||||
str := d.String()
|
||||
sz := len(str)
|
||||
// limit to 30 digits
|
||||
// note, if d.IntPart size large than 30, will be lose.
|
||||
if sz > 30 {
|
||||
sz = 30
|
||||
// if last char is '.' then limit to 20 digits
|
||||
if str[29] == '.' {
|
||||
sz = 29
|
||||
// limit to 31 digits
|
||||
// note, if d.IntPart size large than 31, will be lose.
|
||||
if sz > 31 {
|
||||
sz = 31
|
||||
// if last char is '.' then limit to 30 digits
|
||||
if str[30] == '.' {
|
||||
sz = 30
|
||||
}
|
||||
|
||||
str = str[:sz]
|
||||
|
|
Loading…
Reference in a new issue