Skip to content

Commit

Permalink
ensure tags are hashable
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdata committed Mar 7, 2024
1 parent 0b3e4f4 commit 6cd1cc7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
18 changes: 15 additions & 3 deletions tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,25 @@ func (errIllegalTagType) Is(other error) bool {

var ErrIllegalTagType = errIllegalTagType{}

func checkHashable(tag any) (yes bool) {
defer func() {
if recover() == nil {
yes = true
}
}()
tmp := map[any]struct{}{}
tmp[tag] = struct{}{}
return
}

func tagExpand(l int, rq *Request, tag any, result []any) ([]any, error) {
if l > 10 || len(result) > 100 {
return result, ErrTooManyTags
}
switch data := tag.(type) {
case string:
case template.HTML:
case template.HTMLAttr:
case int:
case int8:
case int16:
Expand All @@ -62,8 +74,6 @@ func tagExpand(l int, rq *Request, tag any, result []any) ([]any, error) {
case float64:
case bool:
case error:
case []string:
case []template.HTML:

case nil:
return result, nil
Expand All @@ -86,7 +96,9 @@ func tagExpand(l int, rq *Request, tag any, result []any) ([]any, error) {
}
return result, err
default:
return append(result, data), nil
if checkHashable(data) {
return append(result, data), nil
}
}
return result, errIllegalTagType{tag: tag}
}
Expand Down
8 changes: 5 additions & 3 deletions tag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func TestTagExpand_IllegalTypesPanic(t *testing.T) {
tags := []any{
string("string"),
template.HTML("template.HTML"),
template.HTMLAttr("template.HTMLAttr"),
int(1),
int8(2),
int16(3),
Expand All @@ -72,20 +73,21 @@ func TestTagExpand_IllegalTypesPanic(t *testing.T) {
errors.New("error"),
[]string{"a", "b"},
[]template.HTML{"a", "b"},
map[int]int{1: 1},
}
for _, tag := range tags {
t.Run(fmt.Sprintf("%T", tag), func(t *testing.T) {
defer func() {
x := recover()
e, ok := x.(error)
if !ok {
t.Fail()
t.FailNow()
}
if !errors.Is(e, ErrIllegalTagType) {
t.Fail()
t.FailNow()
}
if !strings.Contains(e.Error(), fmt.Sprintf("%T", tag)) {
t.Fail()
t.FailNow()
}
}()
MustTagExpand(nil, tag)
Expand Down

0 comments on commit 6cd1cc7

Please sign in to comment.