Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🧑‍💻 ToString: improve test and bench setup #63

Merged
merged 4 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,20 @@ func ToString(arg any, timeFormat ...string) string {
if rv.Kind() == reflect.Ptr && !rv.IsNil() {
// Dereference the pointer and recursively call ToString
return ToString(rv.Elem().Interface(), timeFormat...)
} else if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array {
// handle slices
var buf strings.Builder
buf.WriteString("[")
for i := 0; i < rv.Len(); i++ {
if i > 0 {
buf.WriteString(" ")
}
buf.WriteString(ToString(rv.Index(i).Interface()))
}
buf.WriteString("]")
return buf.String()
}

// For types not explicitly handled, use fmt.Sprint to generate a string representation
return fmt.Sprint(arg)
}
Expand Down
8 changes: 8 additions & 0 deletions convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,13 @@ func Test_ToString(t *testing.T) {
{time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC), "2000-01-01 12:34:56"},
{struct{ Name string }{"John"}, "{John}"},
{[]string{"Hello", "World"}, "[Hello World]"},
{[]int{42, 21}, "[42 21]"},
{[2]int{42, 21}, "[42 21]"},
{[]interface{}{[]int{42, 21}, 42, "Hello", true, []string{"Hello", "World"}}, "[[42 21] 42 Hello true [Hello World]]"},
ReneWerner87 marked this conversation as resolved.
Show resolved Hide resolved
}

for _, tc := range tests {
tc := tc
t.Run(reflect.TypeOf(tc.input).String(), func(t *testing.T) {
t.Parallel()
res := ToString(tc.input)
Expand All @@ -112,6 +116,7 @@ func Test_ToString(t *testing.T) {
{&intPtr, "42"},
}
for _, tc := range testsPtr {
tc := tc
t.Run("pointer to "+reflect.TypeOf(tc.input).Elem().String(), func(t *testing.T) {
t.Parallel()
res := ToString(tc.input)
Expand Down Expand Up @@ -140,6 +145,9 @@ func Benchmark_ToString(b *testing.B) {
float64(3.14),
time.Now(),
[]string{"Hello", "World"},
[]int{42, 21},
[2]int{42, 21},
[]interface{}{[]int{42, 21}, 42, "Hello", true, []string{"Hello", "World"}},
}
for _, value := range values {
b.Run(reflect.TypeOf(value).String(), func(b *testing.B) {
ReneWerner87 marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
Loading