Skip to content

Commit

Permalink
fix(gutil): ListItemValuesUnique panic when field type is []byte(BINA…
Browse files Browse the repository at this point in the history
…RY in mysql)
  • Loading branch information
刘顺钰 committed Sep 15, 2023
1 parent ef1e18d commit e4fcc6b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
9 changes: 7 additions & 2 deletions util/gutil/gutil_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,15 @@ 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 {
// make byte slice comparable
value = string(t)
}
if _, ok = m[value]; ok {
values = SliceDelete(values, i)
} else {
m[values[i]] = struct{}{}
m[value] = struct{}{}
i++
}
}
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 e4fcc6b

Please sign in to comment.