Add binary (un)marshalling support

Implement encoding.BinaryMarshaler and Binary.Unmarshaller. Add tests
to verify.
This commit is contained in:
klokare 2016-11-04 14:31:19 +01:00
parent d6f52241f3
commit 5b7aa6a9cf
2 changed files with 67 additions and 0 deletions

View file

@ -548,6 +548,18 @@ func (d Decimal) MarshalText() (text []byte, err error) {
return []byte(d.String()), nil
}
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation
// is already used when encoding to text, this method stores that string as []byte
func (d *Decimal) UnmarshalBinary(data []byte) error {
return d.UnmarshalText(data)
}
// MarshalBinary implements the encoding.BinaryMarshaler interface. As a string representation
// is already used when encoding to text, this method restores that []byte-encoded string.
func (d Decimal) MarshalBinary() (data []byte, err error) {
return d.MarshalText()
}
// NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.
// StringScaled first scales the decimal then calls .String() on it.
func (d Decimal) StringScaled(exp int32) string {

View file

@ -1,6 +1,8 @@
package decimal
import (
"bytes"
"encoding/gob"
"encoding/json"
"encoding/xml"
"math"
@ -300,6 +302,59 @@ func TestBadXML(t *testing.T) {
}
}
func TestBinary(t *testing.T) {
for x, _ := range testTable {
// Create the decimal
d1 := NewFromFloat(x)
// Encode to binary
b, err := d1.MarshalBinary()
if err != nil {
t.Errorf("error marshalling %v to binary: %v", d1, err)
}
// Restore from binary
var d2 Decimal
err = (&d2).UnmarshalBinary(b)
if err != nil {
t.Errorf("error unmarshalling from binary: %v", err)
}
// The restored decimal should equal the original
if !d1.Equals(d2) {
t.Errorf("expected %v when restoring, got %v", d1, d2)
}
}
}
func TestGOB(t *testing.T) {
for x, _ := range testTable {
// Create the decimal
d1 := NewFromFloat(x)
// Encode using GOB
b := new(bytes.Buffer)
err := gob.NewEncoder(b).Encode(d1)
if err != nil {
t.Errorf("error GOB encoding %v to binary: %v", d1, err)
}
// Restore from GOB
var d2 Decimal
err = gob.NewDecoder(bytes.NewBuffer(b.Bytes())).Decode(&d2)
if err != nil {
t.Errorf("error GOB decoding: %v", err)
}
// The restored decimal should equal the original
if !d1.Equals(d2) {
t.Errorf("expected %v when restoring, got %v", d1, d2)
}
}
}
func TestDecimal_rescale(t *testing.T) {
type Inp struct {
int int64