Skip to content

Commit

Permalink
fix(gutil): panic when field is []byte(BINARY in mysql)
Browse files Browse the repository at this point in the history
  • Loading branch information
刘顺钰 committed Sep 12, 2023
1 parent 5bc9acd commit 0fe7ffd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
13 changes: 11 additions & 2 deletions util/gutil/gutil_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package gutil

import (
"reflect"
"unsafe"

"github.com/gogf/gf/v2/internal/utils"
)
Expand Down Expand Up @@ -122,17 +123,25 @@ func ListItemValuesUnique(list interface{}, key string, subKey ...interface{}) [
m = make(map[interface{}]struct{}, len(values))
)
for i := 0; i < len(values); {
if _, ok = m[values[i]]; ok {
value := values[i]
if t, ok := value.([]byte); ok {
value = unsafeString(t)
}
if _, ok = m[value]; ok {
values = SliceDelete(values, i)
} else {
m[values[i]] = struct{}{}
m[value] = struct{}{}
i++
}
}
}
return values
}

func unsafeString(a []byte) string {
return *(*string)(unsafe.Pointer(&a))
}

// ListToMapByKey converts `list` to a map[string]interface{} of which key is specified by `key`.
// Note that the item value may be type of slice.
func ListToMapByKey(list []map[string]interface{}, key string) map[string]interface{} {
Expand Down
14 changes: 14 additions & 0 deletions util/gutil/gutil_z_unit_list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,17 @@ func Test_ListItemValuesUnique_Map_Array_SubKey(t *testing.T) {
t.Assert(gutil.ListItemValuesUnique(listMap, "scores", "PE"), g.Slice{})
})
}

func Test_ListItemValuesUnique_Binary_ID(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
listMap := g.List{
g.Map{"id": []byte{1}, "score": 100},
g.Map{"id": []byte{2}, "score": 100},
g.Map{"id": []byte{3}, "score": 100},
g.Map{"id": []byte{4}, "score": 100},
g.Map{"id": []byte{4}, "score": 100},
}
t.Assert(gutil.ListItemValuesUnique(listMap, "id"), g.Slice{[]byte{1}, []byte{2}, []byte{3}, []byte{4}})
t.Assert(gutil.ListItemValuesUnique(listMap, "score"), g.Slice{100})
})
}

0 comments on commit 0fe7ffd

Please sign in to comment.