From 3f1fcaff87cb42d3677b5677f5248aa59d374d91 Mon Sep 17 00:00:00 2001 From: Tao Wen Date: Thu, 11 May 2017 08:00:50 +0800 Subject: [PATCH] demonstrate how to customize float encoding --- feature_stream_float.go | 8 ++++---- jsoniter_demo_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/feature_stream_float.go b/feature_stream_float.go index 9dd8c36..6a205ca 100644 --- a/feature_stream_float.go +++ b/feature_stream_float.go @@ -34,9 +34,9 @@ func (stream *Stream) WriteFloat32(val float32) { for p := precision - 1; p > 0 && fval < POW10[p]; p-- { stream.writeByte('0') } - stream.WriteUint64(fval); + stream.WriteUint64(fval) for stream.buf[stream.n - 1] == '0' { - stream.n--; + stream.n-- } } @@ -64,8 +64,8 @@ func (stream *Stream) WriteFloat64(val float64) { for p := precision - 1; p > 0 && fval < POW10[p]; p-- { stream.writeByte('0') } - stream.WriteUint64(fval); + stream.WriteUint64(fval) for stream.buf[stream.n - 1] == '0' { - stream.n--; + stream.n-- } } \ No newline at end of file diff --git a/jsoniter_demo_test.go b/jsoniter_demo_test.go index e90502c..8b5359a 100644 --- a/jsoniter_demo_test.go +++ b/jsoniter_demo_test.go @@ -4,6 +4,8 @@ import ( "fmt" "testing" "github.com/json-iterator/go/require" + "unsafe" + "strconv" ) func Test_bind_api_demo(t *testing.T) { @@ -22,3 +24,38 @@ func Test_iterator_api_demo(t *testing.T) { } fmt.Println(total) } + +type DocumentMatch struct { + Index string `json:"index,omitempty"` + ID string `json:"id"` + Score float64 `json:"score"` + Sort []string `json:"sort,omitempty"` +} + +type DocumentMatchCollection []*DocumentMatch + +type SearchResult struct { + Hits DocumentMatchCollection `json:"hits"` +} + +func Test2(t *testing.T) { + RegisterTypeEncoder("float64", func(ptr unsafe.Pointer, stream *Stream) { + t := *((*float64)(ptr)) + stream.WriteRaw(strconv.FormatFloat(t, 'E', -1, 64)) + }) + hits := []byte(`{"hits":[{"index":"geo","id":"firehouse_grill_brewery","score":3.584608106366055e-07, + "sort":[" \u0001@\t\u0007\u0013;a\u001b}W"]}, + {"index":"geo","id":"jack_s_brewing","score":2.3332790568885077e-07, + "sort":[" \u0001@\u0013{w?.\"0\u0010"]}, + {"index":"geo","id":"brewpub_on_the_green","score":2.3332790568885077e-07, + "sort":[" \u0001@\u0014\u0017+\u00137QZG"]}]}`) + var h SearchResult + err := Unmarshal(hits, &h) + fmt.Printf("SR %+v \n", h.Hits[0]) + b, err := Marshal(h.Hits[0]) + if err != nil { + fmt.Printf("error marshalling search res: %v", err) + //return + } + fmt.Printf("SR %s \n", string(b)) +}