Skip to content

Commit

Permalink
predicates/forwarded: use strings.Index to parse header
Browse files Browse the repository at this point in the history
Use strings.Cut instead of strings.Split to reduce memory allocations.

See #3403 for details.

Signed-off-by: Alexander Yastrebov <alexander.yastrebov@zalando.de>
  • Loading branch information
AlexanderYastrebov committed Feb 11, 2025
1 parent 30f0005 commit 4356b7a
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions predicates/forwarded/forwarded.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,18 @@ func parseForwarded(fh string) *forwarded {

f := &forwarded{}

for _, forwardedFull := range strings.Split(fh, ",") {
for _, forwardedPair := range strings.Split(strings.TrimSpace(forwardedFull), ";") {
// TODO: use range over func added in go1.23 like:
// for forwardedFull := range split(fh, ",") {
// for forwardedPair := range split(strings.TrimSpace(forwardedFull), ";") {
// // ...
// }
// }
// once go1.24 is released
//
// Also use strings.SplitSeq added in go1.24 once go1.25 is released.

split(fh, ",")(func(forwardedFull string) bool {
split(strings.TrimSpace(forwardedFull), ";")(func(forwardedPair string) bool {
token, value, found := strings.Cut(forwardedPair, "=")
value = strings.Trim(value, `"`)
if found && value != "" {
Expand All @@ -145,8 +155,27 @@ func parseForwarded(fh string) *forwarded {
f.host = value
}
}
}
}
return true
})
return true
})

return f
}

func split(s string, sep string) func(yield func(string) bool) {
return func(yield func(string) bool) {
for {
i := strings.Index(s, sep)
if i < 0 {
break
}
frag := s[:i]
if !yield(frag) {
return
}
s = s[i+len(sep):]
}
yield(s)
}
}

0 comments on commit 4356b7a

Please sign in to comment.