Skip to content

Commit

Permalink
fix: checked if a interface is empty by its value field instead of ty…
Browse files Browse the repository at this point in the history
…pe field (#540)
  • Loading branch information
AsterDY authored Oct 18, 2023
1 parent fd7e221 commit de254c3
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/encoder/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,7 @@ func (self *_Compiler) compileStructFieldZero(p *_Program, vt reflect.Type) {
case reflect.Float32 : p.add(_OP_is_zero_4)
case reflect.Float64 : p.add(_OP_is_zero_8)
case reflect.String : p.add(_OP_is_nil_p1)
case reflect.Interface : p.add(_OP_is_nil_p1)
case reflect.Interface : p.add(_OP_is_nil)
case reflect.Map : p.add(_OP_is_zero_map)
case reflect.Ptr : p.add(_OP_is_nil)
case reflect.Slice : p.add(_OP_is_nil_p1)
Expand Down
51 changes: 51 additions & 0 deletions issue_test/issue539_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2023 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package issue_test

import (
`encoding/json`
`testing`

`github.com/bytedance/sonic`
`github.com/stretchr/testify/require`
)

type OmitEmptyInterface struct {
ErrCode int32 `json:"code"`
Data interface{} `json:"data,omitempty"`
}

func TestOmitEmptyInterface(t *testing.T) {
// non-enmpty type
var data *string
resp := &OmitEmptyInterface{
ErrCode: 123,
Data: data,
}
eout, eerr := json.Marshal(resp)
sout, serr := sonic.Marshal(resp)
require.Equal(t, eerr == nil, serr == nil)
require.Equal(t, string(eout), string(sout))

// empty type and value
resp = &OmitEmptyInterface{
ErrCode: 123,
Data: nil,
}
eout, eerr = json.Marshal(resp)
sout, serr = sonic.Marshal(resp)
require.Equal(t, eerr == nil, serr == nil)
require.Equal(t, string(eout), string(sout))
}

0 comments on commit de254c3

Please sign in to comment.