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 1 month 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
}
// Checks if the primitive value is valid
func isPrimitiveTypeValid(primitiveType string) bool {
if primitiveType == "address" ||
primitiveType == "address[]" ||
primitiveType == "bool" ||
primitiveType == "bool[]" ||
primitiveType == "string" ||
primitiveType == "string[]" ||
primitiveType == "bytes" ||
primitiveType == "bytes[]" ||
primitiveType == "int" ||
primitiveType == "int[]" ||
primitiveType == "uint" ||
primitiveType == "uint[]" {
return true
var validPrimitiveTypes = map[string]struct{}{}
// build the set of valid primitive types
func init() {
// Types those are trivially valid
for _, t := range []string{
"address", "address[]", "bool", "bool[]", "string", "string[]",
"bytes", "bytes[]", "int", "int[]", "uint", "uint[]",
} {
validPrimitiveTypes[t] = struct{}{}
}
// For 'bytesN', 'bytesN[]', we allow N from 1 to 32
for n := 1; n <= 32; n++ {
// e.g. 'bytes28' or 'bytes28[]'
if primitiveType == fmt.Sprintf("bytes%d", n) || primitiveType == fmt.Sprintf("bytes%d[]", n) {
return true
}
validPrimitiveTypes[fmt.Sprintf("bytes%d", n)] = struct{}{}
validPrimitiveTypes[fmt.Sprintf("bytes%d[]", n)] = struct{}{}
}
// 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 {
if primitiveType == fmt.Sprintf("int%d", n) || primitiveType == fmt.Sprintf("int%d[]", n) {
return true
}
if primitiveType == fmt.Sprintf("uint%d", n) || primitiveType == fmt.Sprintf("uint%d[]", n) {
return true
}
validPrimitiveTypes[fmt.Sprintf("int%d", n)] = struct{}{}
validPrimitiveTypes[fmt.Sprintf("int%d[]", n)] = struct{}{}
validPrimitiveTypes[fmt.Sprintf("uint%d", n)] = struct{}{}
validPrimitiveTypes[fmt.Sprintf("uint%d[]", n)] = struct{}{}
}
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

Loading…
Cancel
Save