瀏覽代碼

Experiment with inf/dec

Ben Hood 11 年之前
父節點
當前提交
ea4ac4e691
共有 2 個文件被更改,包括 20 次插入12 次删除
  1. 13 10
      marshal.go
  2. 7 2
      marshal_test.go

+ 13 - 10
marshal.go

@@ -6,10 +6,12 @@ package gocql
 
 import (
 	"bytes"
+	"encoding/binary"
 	"fmt"
 	"math"
 	"math/big"
 	"reflect"
+	"speter.net/go/exp/math/dec/inf"
 	"time"
 )
 
@@ -684,16 +686,17 @@ func marshalDecimal(info *TypeInfo, value interface{}) ([]byte, error) {
 	switch v := value.(type) {
 	case Marshaler:
 		return v.MarshalCQL(info)
-	case *big.Rat:
+	case *inf.Dec:
 
 		if v == nil {
 			return nil, nil
 		}
-		num := v.Num().Bytes()
-		denom := v.Denom().Bytes()
-		buf := make([]byte, 4+len(num))
-		copy(buf[4-len(denom):4], denom)
-		copy(buf[4:], num)
+
+		unscaled := v.UnscaledBig().Bytes()
+		scale := v.Scale()
+		buf := make([]byte, 4+len(unscaled))
+		binary.BigEndian.PutUint32(buf, uint32(scale))
+		copy(buf[4:], unscaled)
 		return buf, nil
 	}
 	return nil, marshalErrorf("can not marshal %T into %s", value, info)
@@ -703,11 +706,11 @@ func unmarshalDecimal(info *TypeInfo, data []byte, value interface{}) error {
 	switch v := value.(type) {
 	case Unmarshaler:
 		return v.UnmarshalCQL(info, data)
-	case **big.Rat:
+	case **inf.Dec:
 		if len(data) > 4 {
-			denom := new(big.Int).SetBytes(data[0:4])
-			num := new(big.Int).SetBytes(data[4:])
-			*v = new(big.Rat).SetFrac(num, denom)
+			scale := binary.BigEndian.Uint32(data[0:4])
+			unscaled := new(big.Int).SetBytes(data[4:])
+			*v = inf.NewDecBig(unscaled, inf.Scale(scale))
 		}
 		return nil
 	}

+ 7 - 2
marshal_test.go

@@ -3,8 +3,8 @@ package gocql
 import (
 	"bytes"
 	"math"
-	"math/big"
 	"reflect"
+	"speter.net/go/exp/math/dec/inf"
 	"strings"
 	"testing"
 	"time"
@@ -121,7 +121,12 @@ var marshalTests = []struct {
 	{
 		&TypeInfo{Type: TypeDecimal},
 		[]byte("\x00\x01\x86\xa0\xcb\xd7\x12\xbb\x6d"),
-		big.NewRat(875486690157, 100000),
+		inf.NewDec(875486690157, 100000),
+	},
+	{
+		&TypeInfo{Type: TypeDecimal},
+		[]byte("\x00\x00\x00\x00\x00"),
+		inf.NewDec(0, 1),
 	},
 	{
 		&TypeInfo{Type: TypeTimestamp},