浏览代码

fix html escape test and omit empty

Tao Wen 8 年之前
父节点
当前提交
945fe53724
共有 3 个文件被更改,包括 21 次插入7 次删除
  1. 17 4
      feature_config.go
  2. 2 2
      feature_reflect_native.go
  3. 2 1
      jsoniter_string_test.go

+ 17 - 4
feature_config.go

@@ -113,12 +113,25 @@ func (cfg *frozenConfig) marshalFloatWith6Digits() {
 	}})
 }
 
+type htmlEscapedStringEncoder struct {
+}
+
+func (encoder *htmlEscapedStringEncoder) encode(ptr unsafe.Pointer, stream *Stream) {
+	str := *((*string)(ptr))
+	stream.WriteStringWithHtmlEscaped(str)
+}
+
+func (encoder *htmlEscapedStringEncoder) encodeInterface(val interface{}, stream *Stream) {
+	writeToStream(val, stream, encoder)
+}
+
+func (encoder *htmlEscapedStringEncoder) isEmpty(ptr unsafe.Pointer) bool {
+	return *((*string)(ptr)) == ""
+}
+
 func (cfg *frozenConfig) escapeHtml() {
 	// for better performance
-	cfg.addEncoderToCache(reflect.TypeOf((*string)(nil)).Elem(), &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) {
-		val := *((*string)(ptr))
-		stream.WriteStringWithHtmlEscaped(val)
-	}})
+	cfg.addEncoderToCache(reflect.TypeOf((*string)(nil)).Elem(), &htmlEscapedStringEncoder{})
 }
 
 func (cfg *frozenConfig) addDecoderToCache(cacheKey reflect.Type, decoder Decoder) {

+ 2 - 2
feature_reflect_native.go

@@ -18,8 +18,8 @@ func (codec *stringCodec) encode(ptr unsafe.Pointer, stream *Stream) {
 	stream.WriteString(str)
 }
 
-func (encoder *stringCodec) encodeInterface(val interface{}, stream *Stream) {
-	writeToStream(val, stream, encoder)
+func (codec *stringCodec) encodeInterface(val interface{}, stream *Stream) {
+	writeToStream(val, stream, codec)
 }
 
 func (codec *stringCodec) isEmpty(ptr unsafe.Pointer) bool {

+ 2 - 1
jsoniter_string_test.go

@@ -118,6 +118,7 @@ func Test_string_encode_with_std(t *testing.T) {
 }
 
 func Test_string_encode_with_std_without_html_escape(t *testing.T) {
+	api := Config{EscapeHtml: false}.Froze()
 	should := require.New(t)
 	for i := 0; i < utf8.RuneSelf; i++ {
 		input := string([]byte{byte(i)})
@@ -128,7 +129,7 @@ func Test_string_encode_with_std_without_html_escape(t *testing.T) {
 		should.Nil(err)
 		stdOutput := buf.String()
 		stdOutput = stdOutput[:len(stdOutput)-1]
-		jsoniterOutputBytes, err := Marshal(input)
+		jsoniterOutputBytes, err := api.Marshal(input)
 		should.Nil(err)
 		jsoniterOutput := string(jsoniterOutputBytes)
 		should.Equal(stdOutput, jsoniterOutput)