Reduce path formatting allocations

This commit is contained in:
2026-10-09 00:34:21 +00:00
parent 91ae4fa7ef
commit 673faea097
4 changed files with 200 additions and 10 deletions

View File

@@ -86,7 +86,20 @@ func (p Path) String() string {
return ""
}
// Include each separator and the extra byte introduced by escaping a token.
// Use stack storage for sizing indexes without allocating another string.
size := len(p.segments)
var indexText [20]byte
for _, segment := range p.segments {
if segment.kind == pathSegmentIndex {
size += len(strconv.AppendInt(indexText[:0], int64(segment.index), 10))
} else {
size += len(segment.key) + strings.Count(segment.key, "~") + strings.Count(segment.key, "/")
}
}
var b strings.Builder
b.Grow(size)
for _, segment := range p.segments {
b.WriteByte('/')
if segment.kind == pathSegmentIndex {

View File

@@ -1,6 +1,9 @@
package engine
import "testing"
import (
"strconv"
"testing"
)
func TestPathRoundTripsSemanticKeys(t *testing.T) {
t.Parallel()
@@ -36,6 +39,13 @@ func TestPathRoundTripsSemanticKeys(t *testing.T) {
if got := Keys("items").Index(12).Key("name").String(); got != "/items/12/name" {
t.Fatalf("indexed path = %q", got)
}
maximum := int(^uint(0) >> 1)
for _, index := range []int{100, maximum, -1, -maximum - 1} {
want := "/items/" + strconv.Itoa(index)
if got := Keys("items").Index(index).String(); got != want {
t.Fatalf("indexed path = %q, want %q", got, want)
}
}
}
func TestPathPreservesSegmentIntentAndImmutability(t *testing.T) {