Skip to content

Commit 701296d

Browse files
authored
fix panic (#18)
1 parent 6be16c0 commit 701296d

File tree

2 files changed

+89
-2
lines changed

2 files changed

+89
-2
lines changed

fix-panic_test.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package pcopy
2+
3+
import (
4+
"database/sql"
5+
"testing"
6+
"time"
7+
)
8+
9+
type TopicItem struct {
10+
ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"`
11+
Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"`
12+
CreateTime string `protobuf:"bytes,3,opt,name=CreateTime,proto3" json:"CreateTime,omitempty"`
13+
OwnerRid uint64 `protobuf:"varint,4,opt,name=OwnerRid,proto3" json:"OwnerRid,omitempty"`
14+
}
15+
16+
type OmGroupUserTopic struct {
17+
ID int64
18+
Rid int64
19+
GroupID string
20+
TopicID string
21+
Name sql.NullString
22+
CreateTime time.Time
23+
CreateTimeMilli int64
24+
OwnerRid int64
25+
}
26+
27+
func Test_Panic(t *testing.T) {
28+
// 类型不匹配
29+
t.Run("类型不一样导致的panic, dst是uint, src是int", func(t *testing.T) {
30+
v := &TopicItem{}
31+
Copy(v, &OmGroupUserTopic{
32+
OwnerRid: 1,
33+
})
34+
if v.OwnerRid != 1 {
35+
t.Fatal("OwnerRid not equal")
36+
}
37+
38+
Preheat(&TopicItem{}, &OmGroupUserTopic{})
39+
dst := &TopicItem{}
40+
src := &OmGroupUserTopic{OwnerRid: 1}
41+
Copy(&dst, src, WithUsePreheat())
42+
if dst.OwnerRid != 1 {
43+
t.Fatal("OwnerRid not equal")
44+
}
45+
})
46+
47+
t.Run("类型不一样导致的panic, dst是int, src是uint", func(t *testing.T) {
48+
src := &TopicItem{
49+
OwnerRid: 1,
50+
}
51+
dst := &OmGroupUserTopic{}
52+
Copy(dst, src)
53+
if dst.OwnerRid != 1 {
54+
t.Fatal("OwnerRid not equal")
55+
}
56+
57+
Preheat(&OmGroupUserTopic{}, &TopicItem{})
58+
dst = &OmGroupUserTopic{}
59+
src = &TopicItem{OwnerRid: 1}
60+
Copy(dst, src, WithUsePreheat())
61+
if dst.OwnerRid != 1 {
62+
t.Fatal("OwnerRid not equal")
63+
}
64+
})
65+
}

pcopy.go

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,15 +475,37 @@ func (d *pcopy) cpyDefault(dst, src reflect.Value, dstBase, srcBase unsafe.Point
475475
reflect.Int16,
476476
reflect.Int32,
477477
reflect.Int64:
478-
dst.SetInt(src.Int())
478+
479+
switch dst.Kind() {
480+
case
481+
reflect.Uint,
482+
reflect.Uint8,
483+
reflect.Uint16,
484+
reflect.Uint32,
485+
reflect.Uint64:
486+
dst.SetUint(uint64(src.Int()))
487+
default:
488+
dst.SetInt(src.Int())
489+
}
479490
return nil
480491
case
481492
reflect.Uint,
482493
reflect.Uint8,
483494
reflect.Uint16,
484495
reflect.Uint32,
485496
reflect.Uint64:
486-
dst.SetUint(src.Uint())
497+
498+
switch dst.Kind() {
499+
case
500+
reflect.Int,
501+
reflect.Int8,
502+
reflect.Int16,
503+
reflect.Int32,
504+
reflect.Int64:
505+
dst.SetInt(int64(src.Uint()))
506+
default:
507+
dst.SetUint(src.Uint())
508+
}
487509
return nil
488510
case reflect.String:
489511
dst.SetString(src.String())

0 commit comments

Comments
 (0)