Skip to content

Commit

Permalink
fix: #3362 IsEmpty panics when interface implement panics with nil re…
Browse files Browse the repository at this point in the history
…ceiver
  • Loading branch information
gqcn committed Mar 12, 2024
1 parent 3a8f246 commit 17b227e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
15 changes: 12 additions & 3 deletions internal/empty/empty.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,17 @@ func IsEmpty(value interface{}, traceSource ...bool) bool {
return len(result) == 0

default:

// Finally, using reflect.
var rv reflect.Value
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 +130,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 +192,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 +236,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 @@ -7,7 +7,9 @@
package empty_test

import (
"github.com/gogf/gf/v2/container/gvar"
"testing"
"time"

"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/internal/empty"
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 17b227e

Please # to comment.