Skip to content

Commit

Permalink
Support maps in Stringify (#752)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewsomething authored Nov 6, 2024
1 parent a11b76f commit d489279
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
24 changes: 24 additions & 0 deletions strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"reflect"
"sort"
"strings"
)

Expand Down Expand Up @@ -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())
Expand All @@ -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()))
Expand Down
18 changes: 18 additions & 0 deletions strings_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit d489279

Please sign in to comment.