Merge pull request #338 from francois-berder/optimize-hastag

Optimize HasTag function
This commit is contained in:
colincross 2021-01-28 10:28:04 -08:00 committed by GitHub
commit e09509592d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 11 deletions

View file

@ -23,10 +23,17 @@ import (
// HasTag returns true if a StructField has a tag in the form `name:"foo,value"`.
func HasTag(field reflect.StructField, name, value string) bool {
tag := field.Tag.Get(name)
for _, entry := range strings.Split(tag, ",") {
if entry == value {
for len(tag) > 0 {
idx := strings.Index(tag, ",")
if idx < 0 {
return tag == value
}
if tag[:idx] == value {
return true
}
tag = tag[idx+1:]
}
return false

View file

@ -19,16 +19,16 @@ import (
"testing"
)
func TestHasTag(t *testing.T) {
type testType struct {
NoTag string
EmptyTag string ``
OtherTag string `foo:"bar"`
MatchingTag string `name:"value"`
ExtraValues string `name:"foo,value,bar"`
ExtraTags string `foo:"bar" name:"value"`
}
type testType struct {
NoTag string
EmptyTag string ``
OtherTag string `foo:"bar"`
MatchingTag string `name:"value"`
ExtraValues string `name:"foo,value,bar"`
ExtraTags string `foo:"bar" name:"value"`
}
func TestHasTag(t *testing.T) {
tests := []struct {
field string
want bool
@ -68,6 +68,39 @@ func TestHasTag(t *testing.T) {
}
}
func BenchmarkHasTag(b *testing.B) {
tests := []struct {
field string
}{
{
field: "NoTag",
},
{
field: "EmptyTag",
},
{
field: "OtherTag",
},
{
field: "MatchingTag",
},
{
field: "ExtraValues",
},
{
field: "ExtraTags",
},
}
for _, test := range tests {
b.Run(test.field, func(b *testing.B) {
field, _ := reflect.TypeOf(testType{}).FieldByName(test.field)
for i := 0; i < b.N; i++ {
HasTag(field, "name", "value")
}
})
}
}
func TestPropertyIndexesWithTag(t *testing.T) {
tests := []struct {
name string