Browse Source

support encoding.Text(Un)Marshaler

speter 11 years ago
parent
commit
1fffabb3f5
2 changed files with 47 additions and 0 deletions
  1. 14 0
      dec.go
  2. 33 0
      dec_go1_2_test.go

+ 14 - 0
dec.go

@@ -615,3 +615,17 @@ func (z *Dec) GobDecode(buf []byte) error {
 	z.SetScale(scale(buf[l : l+scaleSize]))
 	return nil
 }
+
+// MarshalText implements the encoding.TextMarshaler interface.
+func (x *Dec) MarshalText() ([]byte, error) {
+	return []byte(x.String()), nil
+}
+
+// UnmarshalText implements the encoding.TextUnmarshaler interface.
+func (z *Dec) UnmarshalText(data []byte) error {
+	_, ok := z.SetString(string(data))
+	if !ok {
+		return fmt.Errorf("invalid inf.Dec")
+	}
+	return nil
+}

+ 33 - 0
dec_go1_2_test.go

@@ -0,0 +1,33 @@
+// +build go1.2
+
+package inf
+
+import (
+	"encoding"
+	"encoding/json"
+	"testing"
+)
+
+var _ encoding.TextMarshaler = new(Dec)
+var _ encoding.TextUnmarshaler = new(Dec)
+
+type Obj struct {
+	Val *Dec
+}
+
+func TestDecJsonMarshalUnmarshal(t *testing.T) {
+	o := Obj{Val: NewDec(123, 2)}
+	js, err := json.Marshal(o)
+	if err != nil {
+		t.Fatalf("json.Marshal(%v): got %v, want ok", o, err)
+	}
+	o2 := &Obj{}
+	err = json.Unmarshal(js, o2)
+	if err != nil {
+		t.Fatalf("json.Unmarshal(%#q): got %v, want ok", js, err)
+	}
+	if o.Val.Scale() != o2.Val.Scale() ||
+		o.Val.UnscaledBig().Cmp(o2.Val.UnscaledBig()) != 0 {
+		t.Fatalf("json.Unmarshal(json.Marshal(%v)): want %v, got %v", o, o, o2)
+	}
+}