Skip to content

Commit

Permalink
Also precompute hook in decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
Fabrice Vaillant authored and cedric-cordenier committed Jun 28, 2024
1 parent 1036125 commit 0855c8a
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,8 @@ type DecoderConfig struct {
// structure. The top-level Decode method is just a convenience that sets
// up the most basic Decoder.
type Decoder struct {
config *DecoderConfig
config *DecoderConfig
cachedDecodeHook func(from reflect.Value, to reflect.Value) (interface{}, error)
}

// Metadata contains information about decoding a structure that
Expand Down Expand Up @@ -408,6 +409,9 @@ func NewDecoder(config *DecoderConfig) (*Decoder, error) {
result := &Decoder{
config: config,
}
if config.DecodeHook != nil {
result.cachedDecodeHook = cachedDecodeHook(config.DecodeHook)
}

return result, nil
}
Expand Down Expand Up @@ -462,10 +466,10 @@ func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) e
return nil
}

if d.config.DecodeHook != nil {
if d.cachedDecodeHook != nil {
// We have a DecodeHook, so let's pre-process the input.
var err error
input, err = DecodeHookExec(d.config.DecodeHook, inputVal, outVal)
input, err = d.cachedDecodeHook(inputVal, outVal)
if err != nil {
return fmt.Errorf("error decoding '%s': %w", name, err)
}
Expand Down

0 comments on commit 0855c8a

Please # to comment.