Skip to content

Commit

Permalink
Added sync pool for field scope and error
Browse files Browse the repository at this point in the history
  • Loading branch information
BoBch27 committed Dec 15, 2024
1 parent 07a2acd commit b12b8db
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"reflect"
"slices"
"strings"
"sync"
"time"
)

Expand Down Expand Up @@ -42,13 +43,25 @@ type validator struct {
validations map[string]valFnWrapper
transformations map[string]transFnWrapper
errFormatters []ErrorFormatterFn
fieldScopePool sync.Pool
fieldErrorPool sync.Pool
}

func newValidator() *validator {
validator := &validator{
make(map[string]valFnWrapper, len(builtInValidators)),
make(map[string]transFnWrapper, len(builtInTransformators)),
make([]ErrorFormatterFn, 0),
sync.Pool{
New: func() interface{} {
return &fieldScope{}
},
},
sync.Pool{
New: func() interface{} {
return &fieldError{}
},
},
}

// register predefined validators
Expand Down Expand Up @@ -240,7 +253,9 @@ func (v *validator) processField(
return "", nil, nil
}

fs := &fieldScope{
fs := v.fieldScopePool.Get().(*fieldScope)
defer v.fieldScopePool.Put(fs)
*fs = fieldScope{
strct: rs.values,
field: fieldType.Name,
structField: fieldType.Name,
Expand Down Expand Up @@ -412,7 +427,9 @@ func (v *validator) applyRules(
continue
}

fe := &fieldError{
fe := v.fieldErrorPool.Get().(*fieldError)
defer v.fieldErrorPool.Put(fe)
*fe = fieldError{
field: fs.field,
structField: fs.structField,
displayField: fs.displayField,
Expand Down Expand Up @@ -568,7 +585,9 @@ func (v *validator) processMapValue(
kind = val.Kind()
}

newFs := &fieldScope{
newFs := v.fieldScopePool.Get().(*fieldScope)
defer v.fieldScopePool.Put(newFs)
*newFs = fieldScope{
strct: fs.strct,
field: key.String(),
structField: key.String(),
Expand Down Expand Up @@ -607,7 +626,9 @@ func (v *validator) processSliceValue(
kind = val.Kind()
}

newFs := &fieldScope{
newFs := v.fieldScopePool.Get().(*fieldScope)
defer v.fieldScopePool.Put(newFs)
*newFs = fieldScope{
strct: fs.strct,
field: fmt.Sprintf("[%d]", i),
structField: fmt.Sprintf("[%d]", i),
Expand Down

0 comments on commit b12b8db

Please sign in to comment.