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 2, 2024
1 parent dc8f203 commit 67073b7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 8 deletions.
11 changes: 3 additions & 8 deletions gremlin-go/driver/graphBinary.go
Original file line number Diff line number Diff line change
Expand Up @@ -989,15 +989,10 @@ func readMap(data *[]byte, i *int) (interface{}, error) {
}
if k == nil {
mapData[nil] = v
} else if reflect.TypeOf(k).Comparable() {
mapData[k] = v
} else {
switch reflect.TypeOf(k).Kind() {
case reflect.Map:
mapData[&k] = v
case reflect.Slice:
mapData[fmt.Sprint(k)] = v
default:
mapData[k] = v
}
mapData[fmt.Sprint(k)] = v
}
}
return mapData, nil
Expand Down
46 changes: 46 additions & 0 deletions gremlin-go/driver/graphBinary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,52 @@ 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) {
// prepare test data
var buf = &bytes.Buffer{}
typeSerializer := &graphBinaryTypeSerializer{}
// write the size of map
err := binary.Write(buf, binary.BigEndian, uint32(2))
if err != nil {
t.Fatalf("Failed to write data: %v", err)
}
// write a map value as the key
k1 := map[string]string{"key": "value"}
_, err = typeSerializer.write(reflect.ValueOf(k1).Interface(), buf)
if err != nil {
t.Fatalf("Failed to encode data: %v", err)
}
v1 := "value1"
_, err = typeSerializer.write(reflect.ValueOf(v1).Interface(), buf)
if err != nil {
t.Fatalf("Failed to encode data: %v", err)
}
// write a slice value as the key
k2 := []int{1, 2, 3}
_, err = typeSerializer.write(reflect.ValueOf(k2).Interface(), buf)
if err != nil {
t.Fatalf("Failed to encode data: %v", err)
}
v2 := "value2"
_, err = typeSerializer.write(reflect.ValueOf(v2).Interface(), buf)
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)
}
expected := map[interface{}]interface{}{
"map[key:value]": "value1",
"[1 2 3]": "value2",
}
if !reflect.DeepEqual(result, expected) {
t.Errorf("Expected %v, but got %v", expected, result)
}
})
t.Run("read-write time", func(t *testing.T) {
pos := 0
var buffer bytes.Buffer
Expand Down

0 comments on commit 67073b7

Please sign in to comment.