Skip to content

Commit d489279

Browse files
Support maps in Stringify (#752)
1 parent a11b76f commit d489279

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

strings.go

+24
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"io"
77
"reflect"
8+
"sort"
89
"strings"
910
)
1011

@@ -46,6 +47,8 @@ func stringifyValue(w io.Writer, val reflect.Value) {
4647
return
4748
case reflect.Struct:
4849
stringifyStruct(w, v)
50+
case reflect.Map:
51+
stringifyMap(w, v)
4952
default:
5053
if v.CanInterface() {
5154
fmt.Fprint(w, v.Interface())
@@ -66,6 +69,27 @@ func stringifySlice(w io.Writer, v reflect.Value) {
6669
_, _ = w.Write([]byte{']'})
6770
}
6871

72+
func stringifyMap(w io.Writer, v reflect.Value) {
73+
_, _ = w.Write([]byte("map["))
74+
75+
// Sort the keys so that the output is stable
76+
keys := v.MapKeys()
77+
sort.Slice(keys, func(i, j int) bool {
78+
return fmt.Sprintf("%v", keys[i]) < fmt.Sprintf("%v", keys[j])
79+
})
80+
81+
for i, key := range keys {
82+
stringifyValue(w, key)
83+
_, _ = w.Write([]byte{':'})
84+
stringifyValue(w, v.MapIndex(key))
85+
if i < len(keys)-1 {
86+
_, _ = w.Write([]byte(", "))
87+
}
88+
}
89+
90+
_, _ = w.Write([]byte("]"))
91+
}
92+
6993
func stringifyStruct(w io.Writer, v reflect.Value) {
7094
if v.Type().Name() != "" {
7195
_, _ = w.Write([]byte(v.Type().String()))

strings_test.go

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package godo
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestStringify_Map(t *testing.T) {
8+
result := Stringify(map[int]*DropletBackupPolicy{
9+
1: {DropletID: 1, BackupEnabled: true},
10+
2: {DropletID: 2},
11+
3: {DropletID: 3, BackupEnabled: true},
12+
})
13+
14+
expected := `map[1:godo.DropletBackupPolicy{DropletID:1, BackupEnabled:true}, 2:godo.DropletBackupPolicy{DropletID:2, BackupEnabled:false}, 3:godo.DropletBackupPolicy{DropletID:3, BackupEnabled:true}]`
15+
if result != expected {
16+
t.Errorf("Expected %s, got %s", expected, result)
17+
}
18+
}

0 commit comments

Comments
 (0)