Skip to content

Commit

Permalink
improvement: optimization of readmap function
Browse files Browse the repository at this point in the history
Signed-off-by: thomas-dg <dyhshome@126.com>
  • Loading branch information
thomas-dg committed Jul 3, 2024
1 parent 67073b7 commit 9fa6865
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
7 changes: 6 additions & 1 deletion gremlin-go/driver/graphBinary.go
Original file line number Diff line number Diff line change
Expand Up @@ -992,7 +992,12 @@ func readMap(data *[]byte, i *int) (interface{}, error) {
} else if reflect.TypeOf(k).Comparable() {
mapData[k] = v
} else {
mapData[fmt.Sprint(k)] = v
switch reflect.TypeOf(k).Kind() {
case reflect.Map:
mapData[&k] = v
default:
mapData[fmt.Sprint(k)] = v
}
}
}
return mapData, nil
Expand Down
32 changes: 28 additions & 4 deletions gremlin-go/driver/graphBinary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,12 +232,12 @@ func TestGraphBinaryV1(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, fmt.Sprintf("%v", source), fmt.Sprintf("%v", res))
})
t.Run("read incomparable map", func(t *testing.T) {
t.Run("read incomparable map: a map value as the key", func(t *testing.T) {
// prepare test data
var buf = &bytes.Buffer{}
typeSerializer := &graphBinaryTypeSerializer{}
// write the size of map
err := binary.Write(buf, binary.BigEndian, uint32(2))
err := binary.Write(buf, binary.BigEndian, uint32(1))
if err != nil {
t.Fatalf("Failed to write data: %v", err)
}
Expand All @@ -252,6 +252,31 @@ func TestGraphBinaryV1(t *testing.T) {
if err != nil {
t.Fatalf("Failed to encode data: %v", err)
}

data := buf.Bytes()
i := 0
result, err := readMap(&data, &i)
if err != nil {
t.Fatalf("readMap failed: %v", err)
}
mResult, ok := result.(map[interface{}]interface{})
if !ok {
t.Fatalf("readMap result not map[interface{}]interface{}")
}
for k, v := range mResult {
assert.Equal(t, reflect.Ptr, reflect.TypeOf(k).Kind())
assert.Equal(t, "value1", v)
}
})
t.Run("read incomparable map: a slice value as the key", func(t *testing.T) {
// prepare test data
var buf = &bytes.Buffer{}
typeSerializer := &graphBinaryTypeSerializer{}
// write the size of map
err := binary.Write(buf, binary.BigEndian, uint32(1))
if err != nil {
t.Fatalf("Failed to write data: %v", err)
}
// write a slice value as the key
k2 := []int{1, 2, 3}
_, err = typeSerializer.write(reflect.ValueOf(k2).Interface(), buf)
Expand All @@ -271,8 +296,7 @@ func TestGraphBinaryV1(t *testing.T) {
t.Fatalf("readMap failed: %v", err)
}
expected := map[interface{}]interface{}{
"map[key:value]": "value1",
"[1 2 3]": "value2",
"[1 2 3]": "value2",
}
if !reflect.DeepEqual(result, expected) {
t.Errorf("Expected %v, but got %v", expected, result)
Expand Down

0 comments on commit 9fa6865

Please sign in to comment.