Skip to content

Commit 978041f

Browse files
authored
signer/core: improve performance of isPrimitiveTypeValid function (#30274) (#30277)
Precomputes valid primitive types into a map to use for validation, thus removing sprintf.
1 parent b37ac5c commit 978041f

File tree

1 file changed

+22
-26
lines changed

1 file changed

+22
-26
lines changed

signer/core/apitypes/types.go

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -843,39 +843,35 @@ func (t Types) validate() error {
843843
return nil
844844
}
845845

846-
// Checks if the primitive value is valid
847-
func isPrimitiveTypeValid(primitiveType string) bool {
848-
if primitiveType == "address" ||
849-
primitiveType == "address[]" ||
850-
primitiveType == "bool" ||
851-
primitiveType == "bool[]" ||
852-
primitiveType == "string" ||
853-
primitiveType == "string[]" ||
854-
primitiveType == "bytes" ||
855-
primitiveType == "bytes[]" ||
856-
primitiveType == "int" ||
857-
primitiveType == "int[]" ||
858-
primitiveType == "uint" ||
859-
primitiveType == "uint[]" {
860-
return true
846+
var validPrimitiveTypes = map[string]struct{}{}
847+
848+
// build the set of valid primitive types
849+
func init() {
850+
// Types those are trivially valid
851+
for _, t := range []string{
852+
"address", "address[]", "bool", "bool[]", "string", "string[]",
853+
"bytes", "bytes[]", "int", "int[]", "uint", "uint[]",
854+
} {
855+
validPrimitiveTypes[t] = struct{}{}
861856
}
862857
// For 'bytesN', 'bytesN[]', we allow N from 1 to 32
863858
for n := 1; n <= 32; n++ {
864-
// e.g. 'bytes28' or 'bytes28[]'
865-
if primitiveType == fmt.Sprintf("bytes%d", n) || primitiveType == fmt.Sprintf("bytes%d[]", n) {
866-
return true
867-
}
859+
validPrimitiveTypes[fmt.Sprintf("bytes%d", n)] = struct{}{}
860+
validPrimitiveTypes[fmt.Sprintf("bytes%d[]", n)] = struct{}{}
868861
}
869862
// For 'intN','intN[]' and 'uintN','uintN[]' we allow N in increments of 8, from 8 up to 256
870863
for n := 8; n <= 256; n += 8 {
871-
if primitiveType == fmt.Sprintf("int%d", n) || primitiveType == fmt.Sprintf("int%d[]", n) {
872-
return true
873-
}
874-
if primitiveType == fmt.Sprintf("uint%d", n) || primitiveType == fmt.Sprintf("uint%d[]", n) {
875-
return true
876-
}
864+
validPrimitiveTypes[fmt.Sprintf("int%d", n)] = struct{}{}
865+
validPrimitiveTypes[fmt.Sprintf("int%d[]", n)] = struct{}{}
866+
validPrimitiveTypes[fmt.Sprintf("uint%d", n)] = struct{}{}
867+
validPrimitiveTypes[fmt.Sprintf("uint%d[]", n)] = struct{}{}
877868
}
878-
return false
869+
}
870+
871+
// Checks if the primitive value is valid
872+
func isPrimitiveTypeValid(primitiveType string) bool {
873+
_, ok := validPrimitiveTypes[primitiveType]
874+
return ok
879875
}
880876

881877
// validate checks if the given domain is valid, i.e. contains at least

0 commit comments

Comments
 (0)