Skip to content

Commit

Permalink
predicates/forwarded: use strings.Cut 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 794d04b
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions predicates/forwarded/forwarded.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,16 @@ 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

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 +153,22 @@ 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) {
first, rest, _ := strings.Cut(s, sep)
for first != "" {
if !yield(first) {
return
}
first, rest, _ = strings.Cut(rest, sep)
}
}
}

0 comments on commit 794d04b

Please sign in to comment.