Skip to content

Commit

Permalink
fix: #3362 IsEmpty panics when some interface implement panics with…
Browse files Browse the repository at this point in the history
… nil receiver (#3367)
  • Loading branch information
gqcn authored Mar 20, 2024
1 parent cade077 commit b3f4821
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
14 changes: 11 additions & 3 deletions internal/empty/empty.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ func IsEmpty(value interface{}, traceSource ...bool) bool {
if v, ok := value.(reflect.Value); ok {
rv = v
} else {
rv = reflect.ValueOf(value)
if IsNil(rv) {
return true
}

// =========================
// Common interfaces checks.
// =========================
Expand Down Expand Up @@ -124,8 +129,6 @@ func IsEmpty(value interface{}, traceSource ...bool) bool {
}
return len(f.MapStrAny()) == 0
}

rv = reflect.ValueOf(value)
}

switch rv.Kind() {
Expand Down Expand Up @@ -188,9 +191,11 @@ func IsEmpty(value interface{}, traceSource ...bool) bool {

case reflect.Invalid:
return true

default:
return false
}
}
return false
}

// IsNil checks whether given `value` is nil, especially for interface{} type value.
Expand Down Expand Up @@ -230,6 +235,9 @@ func IsNil(value interface{}, traceSource ...bool) bool {
} else {
return !rv.IsValid() || rv.IsNil()
}

default:
return false
}
return false
}
35 changes: 35 additions & 0 deletions internal/empty/empty_z_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ package empty_test

import (
"testing"
"time"

"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/internal/empty"
"github.com/gogf/gf/v2/test/gtest"
Expand Down Expand Up @@ -128,3 +130,36 @@ func TestIsNil(t *testing.T) {
t.Assert(empty.IsNil(&i, true), true)
})
}

type Issue3362St struct {
time.Time
}

func Test_Issue3362(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
type A struct {
Issue3362 *Issue3362St `json:"issue,omitempty"`
}
m := gvar.New(
&A{},
).Map(
gvar.MapOption{
OmitEmpty: true,
},
)
t.Assert(m, nil)
})
gtest.C(t, func(t *gtest.T) {
var i int
t.Assert(empty.IsNil(i), false)
})
gtest.C(t, func(t *gtest.T) {
var i *int
t.Assert(empty.IsNil(i), true)
})
gtest.C(t, func(t *gtest.T) {
var i *int
t.Assert(empty.IsNil(&i), false)
t.Assert(empty.IsNil(&i, true), true)
})
}

0 comments on commit b3f4821

Please sign in to comment.