Skip to content

Commit

Permalink
UnmarshalChainConfigJSON decodes only once for re-use root case
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 committed Dec 23, 2024
1 parent 3c2a6c4 commit 2172aa7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
24 changes: 13 additions & 11 deletions params/json.libevm.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,27 +53,29 @@ func (c *ChainConfig) UnmarshalJSON(data []byte) (err error) {
// - `reuseJSONRoot` is true:
// `data` is decoded into `config` and `data` is decoded into `extra`.
func UnmarshalChainConfigJSON[T any](data []byte, config *ChainConfig, extra *T, reuseJSONRoot bool) (err error) {
if extra == nil {
return fmt.Errorf("extra pointer argument is nil")
}
err = json.Unmarshal(data, (*chainConfigWithoutMethods)(config))
switch {
case err != nil:
return fmt.Errorf("decoding root chain config: %s", err)
case extra == nil:
return fmt.Errorf("extra pointer argument is nil")
case reuseJSONRoot:
err = json.Unmarshal(data, (*chainConfigWithoutMethods)(config))
if err != nil {
return fmt.Errorf("decoding root chain config: %s", err)
}
err = json.Unmarshal(data, extra)
if err != nil {
return fmt.Errorf("decoding extra config to %T: %s", extra, err)
}
default:
jsonExtra := struct {
case !reuseJSONRoot:
combined := struct {
*chainConfigWithoutMethods
Extra *T `json:"extra"`
}{
Extra: extra,
chainConfigWithoutMethods: (*chainConfigWithoutMethods)(config),
Extra: extra,
}
err = json.Unmarshal(data, &jsonExtra)
err = json.Unmarshal(data, &combined)
if err != nil {
return fmt.Errorf("decoding extra config to %T: %s", extra, err)
return fmt.Errorf("decoding config to combined of chain config and %T: %s", extra, err)
}
}
return nil
Expand Down
5 changes: 3 additions & 2 deletions params/json.libevm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ func TestUnmarshalChainConfigJSON(t *testing.T) {
"invalid_json": {
extra: &testExtra{},
expectedExtra: &testExtra{},
errMessage: "decoding root chain config: unexpected end of JSON input",
errMessage: "decoding config to combined of chain config and *params.testExtra: " +
"unexpected end of JSON input",
},
"nil_extra_at_root_depth": {
jsonData: `{"chainId": 1}`,
Expand Down Expand Up @@ -195,7 +196,7 @@ func TestUnmarshalChainConfigJSON(t *testing.T) {
extra: &testExtra{},
expectedConfig: ChainConfig{ChainID: big.NewInt(1)},
expectedExtra: &testExtra{},
errMessage: "decoding extra config to *params.testExtra: " +
errMessage: "decoding config to combined of chain config and *params.testExtra: " +
"json: cannot unmarshal number into Go struct field " +
".extra of type params.testExtra",
},
Expand Down

0 comments on commit 2172aa7

Please sign in to comment.