fix null after MarshalText work

This commit is contained in:
Andrey Berezin
2025-06-06 10:19:01 +03:00
parent fe2707c07a
commit 9b7ae67e7e
5 changed files with 59 additions and 17 deletions
+2 -1
View File
@@ -46,7 +46,8 @@ generate: build
./tests/intern.go \
./tests/nocopy.go \
./tests/escaping.go \
./tests/nested_marshaler.go
./tests/nested_marshaler.go \
./tests/text_marshaler.go
bin/easyjson -snake_case ./tests/snake.go
bin/easyjson -omit_empty ./tests/omitempty.go
bin/easyjson -build_tags=use_easyjson -disable_members_unescape ./benchmark/data.go
+1 -1
View File
@@ -242,7 +242,7 @@ func (g *Generator) genTypeEncoderNoCheck(t reflect.Type, in string, tags fieldT
// NOTE: extra check for TextMarshaler. It overrides default methods.
if reflect.PtrTo(key).Implements(reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()) {
fmt.Fprintln(g.out, ws+" "+fmt.Sprintf("out.RawBytesString(("+tmpVar+"Name).MarshalText()"+")"))
fmt.Fprintln(g.out, ws+" "+fmt.Sprintf("out.RawText(("+tmpVar+"Name).MarshalText()"+")"))
} else if keyEnc != "" {
fmt.Fprintln(g.out, ws+" "+fmt.Sprintf(keyEnc, tmpVar+"Name"))
} else {
+1 -15
View File
@@ -67,18 +67,6 @@ func (w *Writer) RawString(s string) {
w.Buffer.AppendString(s)
}
// RawBytesString appends string from bytes to the buffer.
func (w *Writer) RawBytesString(data []byte, err error) {
switch {
case w.Error != nil:
return
case err != nil:
w.Error = err
default:
w.String(string(data))
}
}
// Raw appends raw binary data to the buffer or sets the error if it is given. Useful for
// calling with results of MarshalJSON-like functions.
func (w *Writer) Raw(data []byte, err error) {
@@ -102,10 +90,8 @@ func (w *Writer) RawText(data []byte, err error) {
return
case err != nil:
w.Error = err
case len(data) > 0:
w.String(string(data))
default:
w.RawString("null")
w.String(string(data))
}
}
+15
View File
@@ -0,0 +1,15 @@
package tests
import (
"strings"
)
//easyjson:json
type StructWrappedTextMarshaler struct {
Value namedWithTextMarshaler
}
type namedWithTextMarshaler string
func (n namedWithTextMarshaler) MarshalText() ([]byte, error) {
return []byte(strings.ToUpper(string(n))), nil
}
+40
View File
@@ -0,0 +1,40 @@
package tests
import (
"testing"
"github.com/mailru/easyjson"
)
func TestStructWithTextMarshalerMarshal(t *testing.T) {
tests := []struct {
name string
input StructWrappedTextMarshaler
expected string
}{
{
name: "Filled struct",
input: StructWrappedTextMarshaler{
Value: namedWithTextMarshaler("test"),
},
expected: `{"Value":"TEST"}`,
},
{
name: "Empty struct",
input: StructWrappedTextMarshaler{},
expected: `{"Value":""}`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
marshaled, err := easyjson.Marshal(test.input)
if err != nil {
t.Errorf("easyjson.Marshal failed: %v", err)
}
if string(marshaled) != test.expected {
t.Errorf("easyjson.Marshal output incorrect: got %s, want %s", string(marshaled), test.expected)
}
})
}
}