From d489279d4fe9a481eefd3b5bca28a591b2b05445 Mon Sep 17 00:00:00 2001 From: Andrew Starr-Bochicchio Date: Wed, 6 Nov 2024 10:36:55 -0500 Subject: [PATCH] Support maps in Stringify (#752) --- strings.go | 24 ++++++++++++++++++++++++ strings_test.go | 18 ++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 strings_test.go diff --git a/strings.go b/strings.go index f92893ed..5a258131 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 00000000..a107ab76 --- /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) + } +}