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

Unnecessary lock operation for reading from cache in extractStructCache method - fixed double checknig/reading cStruct in validateStruct method #1236

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
6 changes: 3 additions & 3 deletions cache.go
Expand Up @@ -100,9 +100,6 @@ type cTag struct {
}

func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStruct {
v.structCache.lock.Lock()
defer v.structCache.lock.Unlock() // leave as defer! because if inner panics, it will never get unlocked otherwise!

typ := current.Type()

// could have been multiple trying to access, but once first is done this ensures struct
Expand All @@ -112,6 +109,9 @@ func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStr
return cs
}

v.structCache.lock.Lock()
defer v.structCache.lock.Unlock() // leave as defer! because if inner panics, it will never get unlocked otherwise!

cs = &cStruct{name: sName, fields: make([]*cField, 0), fn: v.structLevelFuncs[typ]}

numFields := current.NumField()
Expand Down
8 changes: 2 additions & 6 deletions validator.go
Expand Up @@ -31,11 +31,7 @@ type validate struct {

// parent and current will be the same the first run of validateStruct
func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) {

cs, ok := v.v.structCache.Get(typ)
if !ok {
cs = v.v.extractStructCache(current, typ.Name())
}
cs := v.v.extractStructCache(current, typ.Name())

if len(ns) == 0 && len(cs.name) != 0 {

Expand Down Expand Up @@ -66,7 +62,7 @@ func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, cur

} else {
// used with StructPartial & StructExcept
_, ok = v.includeExclude[string(append(structNs, f.name...))]
_, ok := v.includeExclude[string(append(structNs, f.name...))]

if (ok && v.hasExcludes) || (!ok && !v.hasExcludes) {
continue
Expand Down