diff --git a/decimal.go b/decimal.go index 91f9f6c..eee67b5 100644 --- a/decimal.go +++ b/decimal.go @@ -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 { diff --git a/decimal_test.go b/decimal_test.go index b0b2088..dad4462 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -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