diff --git a/strings.go b/strings.go index f92893e..5a25813 100644 --- a/strings.go +++ b/strings.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "reflect" + "sort" "strings" ) @@ -46,6 +47,8 @@ func stringifyValue(w io.Writer, val reflect.Value) { return case reflect.Struct: stringifyStruct(w, v) + case reflect.Map: + stringifyMap(w, v) default: if v.CanInterface() { fmt.Fprint(w, v.Interface()) @@ -66,6 +69,27 @@ func stringifySlice(w io.Writer, v reflect.Value) { _, _ = w.Write([]byte{']'}) } +func stringifyMap(w io.Writer, v reflect.Value) { + _, _ = w.Write([]byte("map[")) + + // Sort the keys so that the output is stable + keys := v.MapKeys() + sort.Slice(keys, func(i, j int) bool { + return fmt.Sprintf("%v", keys[i]) < fmt.Sprintf("%v", keys[j]) + }) + + for i, key := range keys { + stringifyValue(w, key) + _, _ = w.Write([]byte{':'}) + stringifyValue(w, v.MapIndex(key)) + if i < len(keys)-1 { + _, _ = w.Write([]byte(", ")) + } + } + + _, _ = w.Write([]byte("]")) +} + func stringifyStruct(w io.Writer, v reflect.Value) { if v.Type().Name() != "" { _, _ = w.Write([]byte(v.Type().String())) diff --git a/strings_test.go b/strings_test.go new file mode 100644 index 0000000..a107ab7 --- /dev/null +++ b/strings_test.go @@ -0,0 +1,18 @@ +package godo + +import ( + "testing" +) + +func TestStringify_Map(t *testing.T) { + result := Stringify(map[int]*DropletBackupPolicy{ + 1: {DropletID: 1, BackupEnabled: true}, + 2: {DropletID: 2}, + 3: {DropletID: 3, BackupEnabled: true}, + }) + + expected := `map[1:godo.DropletBackupPolicy{DropletID:1, BackupEnabled:true}, 2:godo.DropletBackupPolicy{DropletID:2, BackupEnabled:false}, 3:godo.DropletBackupPolicy{DropletID:3, BackupEnabled:true}]` + if result != expected { + t.Errorf("Expected %s, got %s", expected, result) + } +}