signer/core: improve performance of isPrimitiveTypeValid function (#30274) (#30277)

Precomputes valid primitive types into a map to use for validation, thus removing sprintf.
pull/30137/head^2
llkhacquan 4 months ago committed by GitHub
parent b37ac5c102
commit 978041feea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 48
      signer/core/apitypes/types.go

@ -843,39 +843,35 @@ func (t Types) validate() error {
return nil return nil
} }
// Checks if the primitive value is valid var validPrimitiveTypes = map[string]struct{}{}
func isPrimitiveTypeValid(primitiveType string) bool {
if primitiveType == "address" || // build the set of valid primitive types
primitiveType == "address[]" || func init() {
primitiveType == "bool" || // Types those are trivially valid
primitiveType == "bool[]" || for _, t := range []string{
primitiveType == "string" || "address", "address[]", "bool", "bool[]", "string", "string[]",
primitiveType == "string[]" || "bytes", "bytes[]", "int", "int[]", "uint", "uint[]",
primitiveType == "bytes" || } {
primitiveType == "bytes[]" || validPrimitiveTypes[t] = struct{}{}
primitiveType == "int" ||
primitiveType == "int[]" ||
primitiveType == "uint" ||
primitiveType == "uint[]" {
return true
} }
// For 'bytesN', 'bytesN[]', we allow N from 1 to 32 // For 'bytesN', 'bytesN[]', we allow N from 1 to 32
for n := 1; n <= 32; n++ { for n := 1; n <= 32; n++ {
// e.g. 'bytes28' or 'bytes28[]' validPrimitiveTypes[fmt.Sprintf("bytes%d", n)] = struct{}{}
if primitiveType == fmt.Sprintf("bytes%d", n) || primitiveType == fmt.Sprintf("bytes%d[]", n) { validPrimitiveTypes[fmt.Sprintf("bytes%d[]", n)] = struct{}{}
return true
}
} }
// For 'intN','intN[]' and 'uintN','uintN[]' we allow N in increments of 8, from 8 up to 256 // For 'intN','intN[]' and 'uintN','uintN[]' we allow N in increments of 8, from 8 up to 256
for n := 8; n <= 256; n += 8 { for n := 8; n <= 256; n += 8 {
if primitiveType == fmt.Sprintf("int%d", n) || primitiveType == fmt.Sprintf("int%d[]", n) { validPrimitiveTypes[fmt.Sprintf("int%d", n)] = struct{}{}
return true validPrimitiveTypes[fmt.Sprintf("int%d[]", n)] = struct{}{}
} validPrimitiveTypes[fmt.Sprintf("uint%d", n)] = struct{}{}
if primitiveType == fmt.Sprintf("uint%d", n) || primitiveType == fmt.Sprintf("uint%d[]", n) { validPrimitiveTypes[fmt.Sprintf("uint%d[]", n)] = struct{}{}
return true
}
} }
return false }
// Checks if the primitive value is valid
func isPrimitiveTypeValid(primitiveType string) bool {
_, ok := validPrimitiveTypes[primitiveType]
return ok
} }
// validate checks if the given domain is valid, i.e. contains at least // validate checks if the given domain is valid, i.e. contains at least

Loading…
Cancel
Save