Skip to content

Commit a9250c6

Browse files
committed
refactor: simplify ChainConfig.UnmarshalJSON() branches
1 parent 0c14c32 commit a9250c6

File tree

1 file changed

+15
-24
lines changed

1 file changed

+15
-24
lines changed

params/json.libevm.go

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -25,29 +25,20 @@ type chainConfigWithExportedExtra struct {
2525

2626
// UnmarshalJSON implements the [json.Unmarshaler] interface.
2727
func (c *ChainConfig) UnmarshalJSON(data []byte) error {
28-
extras := registeredExtras
29-
30-
if extras != nil && !extras.reuseJSONRoot {
28+
switch reg := registeredExtras; {
29+
case reg != nil && !reg.reuseJSONRoot:
3130
return c.unmarshalJSONWithExtra(data)
32-
}
33-
34-
if err := json.Unmarshal(data, (*chainConfigWithoutMethods)(c)); err != nil {
35-
return err
36-
}
37-
if extras == nil {
38-
return nil
39-
}
40-
41-
// Invariants if here:
42-
// - reg.reuseJSONRoot == true
43-
// - Non-extra ChainConfig fields already unmarshalled
4431

45-
c.extra = extras.chainConfig.NilPointer()
46-
if err := json.Unmarshal(data, c.extra); err != nil {
47-
c.extra = nil
48-
return err
32+
case reg != nil && reg.reuseJSONRoot: // although the latter is redundant, it's clearer
33+
c.extra = reg.chainConfig.NilPointer()
34+
if err := json.Unmarshal(data, c.extra); err != nil {
35+
c.extra = nil
36+
return err
37+
}
38+
fallthrough // Important! We've only unmarshalled the extra field.
39+
default: // reg == nil
40+
return json.Unmarshal(data, (*chainConfigWithoutMethods)(c))
4941
}
50-
return nil
5142
}
5243

5344
// unmarshalJSONWithExtra unmarshals JSON under the assumption that the
@@ -67,14 +58,14 @@ func (c *ChainConfig) unmarshalJSONWithExtra(data []byte) error {
6758

6859
// MarshalJSON implements the [json.Marshaler] interface.
6960
func (c *ChainConfig) MarshalJSON() ([]byte, error) {
70-
switch extras := registeredExtras; {
71-
case extras == nil:
61+
switch reg := registeredExtras; {
62+
case reg == nil:
7263
return json.Marshal((*chainConfigWithoutMethods)(c))
7364

74-
case !extras.reuseJSONRoot:
65+
case !reg.reuseJSONRoot:
7566
return c.marshalJSONWithExtra()
7667

77-
default:
68+
default: // reg.reuseJSONRoot == true
7869
// The inverse of reusing the JSON root is merging two JSON buffers,
7970
// which isn't supported by the native package. So we use
8071
// map[string]json.RawMessage intermediates.

0 commit comments

Comments
 (0)