Join File.join parts in linear time
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful

This commit is contained in:
2026-11-09 23:11:58 +11:00
parent fb3d2f2d0d
commit 081ea12714
2 changed files with 15 additions and 13 deletions
+4
View File
@@ -332,4 +332,8 @@ func TestFileJoin(t *testing.T) {
t.Errorf("fileJoin(%q) = %q, want %q", c.parts, got, c.want)
}
}
parts := slices.Repeat([]string{"/a"}, 1<<12)
if n := testing.AllocsPerRun(1, func() { _ = fileJoin(parts) }); n > 64 {
t.Errorf("fileJoin of %d rooted parts allocates %v times", len(parts), n)
}
}
+11 -13
View File
@@ -1,6 +1,7 @@
package gentypes
import (
"bytes"
_ "embed"
"fmt"
"path"
@@ -996,6 +997,9 @@ func (p *parser) joinArg(fn string, depth int) (string, error) {
p.take()
return fileJoin(t.words), nil
case fn == "join" && t.kind == tOp && t.text == "[":
if depth > maxDepth {
return "", errLimit
}
p.take()
var elems []string
for p.skipNL(); !p.op("]"); p.skipNL() {
@@ -1016,22 +1020,16 @@ func (p *parser) joinArg(fn string, depth int) (string, error) {
// fileJoin is Ruby's File.join: one separator between parts, keeping a part's leading one and the doubled ones within.
func fileJoin(parts []string) string {
var b strings.Builder
var b []byte
for i, s := range parts {
if i > 0 {
cur := b.String()
trimmed := strings.TrimRight(cur, "/")
switch {
case strings.HasPrefix(s, "/"):
b.Reset()
b.WriteString(trimmed)
case len(trimmed) == len(cur):
b.WriteByte('/')
}
if n := len(bytes.TrimRight(b, "/")); i > 0 && strings.HasPrefix(s, "/") {
b = b[:n]
} else if i > 0 && n == len(b) {
b = append(b, '/')
}
b.WriteString(s)
b = append(b, s...)
}
return b.String()
return string(b)
}
// provDecl is a provide call: its name, its parent by provider name or class, and its class body.