Skip to content

Commit 276d389

Browse files
perf: optimize context valid identifier check (#340)
1 parent 230201e commit 276d389

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

context.go

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,8 @@ package pongo2
33
import (
44
"errors"
55
"fmt"
6-
"regexp"
76
)
87

9-
var reIdentifiers = regexp.MustCompile("^[a-zA-Z0-9_]+$")
10-
118
var autoescape = true
129

1310
func SetAutoescape(newValue bool) {
@@ -30,7 +27,7 @@ type Context map[string]any
3027

3128
func (c Context) checkForValidIdentifiers() *Error {
3229
for k, v := range c {
33-
if !reIdentifiers.MatchString(k) {
30+
if !isValidIdentifier(k) {
3431
return &Error{
3532
Sender: "checkForValidIdentifiers",
3633
OrigError: fmt.Errorf("context-key '%s' (value: '%+v') is not a valid identifier", k, v),
@@ -40,6 +37,22 @@ func (c Context) checkForValidIdentifiers() *Error {
4037
return nil
4138
}
4239

40+
func isValidIdentifier(s string) bool {
41+
for i := range s {
42+
if !isValidIdentifierChar(s[i]) {
43+
return false
44+
}
45+
}
46+
return true
47+
}
48+
49+
func isValidIdentifierChar(c byte) bool {
50+
return (c >= 'a' && c <= 'z') ||
51+
(c >= 'A' && c <= 'Z') ||
52+
(c >= '0' && c <= '9') ||
53+
c == '_'
54+
}
55+
4356
// Update updates this context with the key/value-pairs from another context.
4457
func (c Context) Update(other Context) Context {
4558
for k, v := range other {

0 commit comments

Comments
 (0)