浏览代码

Fix standard compatiblility

Encode has trailing newline at the end.

Signed-off-by: Peng Gao <peng.gao.dut@gmail.com>
Peng Gao 8 年之前
父节点
当前提交
5fffb9b8f7
共有 3 个文件被更改,包括 27 次插入0 次删除
  1. 20 0
      compatible_test.go
  2. 3 0
      feature_adapter.go
  3. 4 0
      feature_config.go

+ 20 - 0
compatible_test.go

@@ -0,0 +1,20 @@
+package jsoniter
+
+import (
+	"bytes"
+	"encoding/json"
+	"testing"
+
+	"github.com/stretchr/testify/require"
+)
+
+// Standard Encoder has trailing newline.
+func TestEncoderHasTrailingNewline(t *testing.T) {
+	should := require.New(t)
+	var buf, stdbuf bytes.Buffer
+	enc := ConfigCompatibleWithStandardLibrary.NewEncoder(&buf)
+	enc.Encode(1)
+	stdenc := json.NewEncoder(&stdbuf)
+	stdenc.Encode(1)
+	should.Equal(stdbuf.Bytes(), buf.Bytes())
+}

+ 3 - 0
feature_adapter.go

@@ -110,6 +110,9 @@ type Encoder struct {
 // Encode encode interface{} as JSON to io.Writer
 func (adapter *Encoder) Encode(val interface{}) error {
 	adapter.stream.WriteVal(val)
+	if adapter.stream.cfg.addNewline {
+		adapter.stream.WriteRaw("\n")
+	}
 	adapter.stream.Flush()
 	return adapter.stream.Error
 }

+ 4 - 0
feature_config.go

@@ -19,11 +19,13 @@ type Config struct {
 	UseNumber               bool
 	TagKey                  string
 	ValidateJsonRawMessage  bool
+	AddNewline              bool
 }
 
 type frozenConfig struct {
 	configBeforeFrozen Config
 	sortMapKeys        bool
+	addNewline         bool
 	indentionStep      int
 	decoderCache       unsafe.Pointer
 	encoderCache       unsafe.Pointer
@@ -58,6 +60,7 @@ var ConfigCompatibleWithStandardLibrary = Config{
 	EscapeHTML:             true,
 	SortMapKeys:            true,
 	ValidateJsonRawMessage: true,
+	AddNewline:             true,
 }.Froze()
 
 // ConfigFastest marshals float with only 6 digits precision
@@ -72,6 +75,7 @@ func (cfg Config) Froze() API {
 	frozenConfig := &frozenConfig{
 		sortMapKeys:   cfg.SortMapKeys,
 		indentionStep: cfg.IndentionStep,
+		addNewline:    cfg.AddNewline,
 		streamPool:    make(chan *Stream, 16),
 		iteratorPool:  make(chan *Iterator, 16),
 	}