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

refactor(slice): simplify SliceValidationError Error method #3910

Merged
merged 2 commits into from May 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 11 additions & 16 deletions binding/default_validator.go
Expand Up @@ -5,8 +5,8 @@
package binding

import (
"fmt"
"reflect"
"strconv"
"strings"
"sync"

Expand All @@ -22,25 +22,20 @@ type SliceValidationError []error

// Error concatenates all error elements in SliceValidationError into a single string separated by \n.
func (err SliceValidationError) Error() string {
n := len(err)
switch n {
case 0:
if len(err) == 0 {
return ""
default:
var b strings.Builder
if err[0] != nil {
fmt.Fprintf(&b, "[%d]: %s", 0, err[0].Error())
}
if n > 1 {
for i := 1; i < n; i++ {
if err[i] != nil {
b.WriteString("\n")
fmt.Fprintf(&b, "[%d]: %s", i, err[i].Error())
}
}

var b strings.Builder
for i := 0; i < len(err); i++ {
if err[i] != nil {
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString("[" + strconv.Itoa(i) + "]: " + err[i].Error())
}
return b.String()
}
return b.String()
}

var _ StructValidator = (*defaultValidator)(nil)
Expand Down
12 changes: 8 additions & 4 deletions binding/default_validator_benchmark_test.go
Expand Up @@ -12,11 +12,15 @@ import (

func BenchmarkSliceValidationError(b *testing.B) {
const size int = 100
e := make(SliceValidationError, size)
for j := 0; j < size; j++ {
e[j] = errors.New(strconv.Itoa(j))
}

b.ReportAllocs()
b.ResetTimer()

for i := 0; i < b.N; i++ {
e := make(SliceValidationError, size)
for j := 0; j < size; j++ {
e[j] = errors.New(strconv.Itoa(j))
}
if len(e.Error()) == 0 {
b.Errorf("error")
}
Expand Down