mirror of
https://github.com/shopspring/decimal.git
synced 2024-11-22 20:40:48 +01:00
Add GobEncode and GobDecode, fixes the issue raised in #23 but with Marshal/UnmarshalBinary
This commit is contained in:
parent
15474de08e
commit
ed31524af4
2 changed files with 57 additions and 0 deletions
10
decimal.go
10
decimal.go
|
@ -678,6 +678,16 @@ func (d Decimal) MarshalText() (text []byte, err error) {
|
||||||
return []byte(d.String()), nil
|
return []byte(d.String()), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GobEncode implements the gob.GobEncoder interface for gob serialization.
|
||||||
|
func (d Decimal) GobEncode() ([]byte, error) {
|
||||||
|
return d.MarshalBinary()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GobDecode implements the gob.GobDecoder interface for gob serialization.
|
||||||
|
func (d Decimal) GobDecode(data []byte) error {
|
||||||
|
return d.UnmarshalBinary(data)
|
||||||
|
}
|
||||||
|
|
||||||
// StringScaled first scales the decimal then calls .String() on it.
|
// StringScaled first scales the decimal then calls .String() on it.
|
||||||
// NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.
|
// NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.
|
||||||
func (d Decimal) StringScaled(exp int32) string {
|
func (d Decimal) StringScaled(exp int32) string {
|
||||||
|
|
|
@ -1545,3 +1545,50 @@ func TestBinary(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func slicesEqual(a, b []byte) bool {
|
||||||
|
for i, val := range a {
|
||||||
|
if b[i] != val {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGobEncode(t *testing.T) {
|
||||||
|
for x, _ := range testTable {
|
||||||
|
d1 := NewFromFloat(x)
|
||||||
|
|
||||||
|
b1, err := d1.GobEncode()
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("error encoding %v to binary: %v", d1, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
d2 := NewFromFloat(x)
|
||||||
|
|
||||||
|
b2, err := d2.GobEncode()
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("error encoding %v to binary: %v", d2, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !slicesEqual(b1, b2) {
|
||||||
|
t.Errorf("something about the gobencode is not working properly \n%v\n%v", b1, b2)
|
||||||
|
}
|
||||||
|
|
||||||
|
var d3 Decimal
|
||||||
|
err = d3.GobDecode(b1)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Error gobdecoding %v, got %v", b1, d3)
|
||||||
|
}
|
||||||
|
var d4 Decimal
|
||||||
|
err = d4.GobDecode(b2)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Error gobdecoding %v, got %v", b2, d4)
|
||||||
|
}
|
||||||
|
|
||||||
|
eq := d3.Equal(d4)
|
||||||
|
if eq != true {
|
||||||
|
t.Errorf("Encoding then decoding mutated Decimal")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue