sessions: lastIndex finds a key in a line's tail going forward too (#2278)

lastIndex already found a key going forward over a whole line, but the
1 KB tail it looks at first, where Claude Code writes the timestamp,
still went through bytes.LastIndex, a byte at a time back. tsAt and
ccReply's usage both take it on every Claude line of a first start.

Run on mote at the head:
- A side-by-side test (not committed) over 620,566 real lines of the
  fixture history (tails cut to 8 KB), for "timestamp" and "usage":
  old, new and bytes.LastIndex agree on every line; 1.14s -> 0.79s and
  1.14s -> 0.82s in two rounds, ~0.5 us a call saved.
- go test ./internal/sessions: ok; TestLastIndexIsLastIndex holds it
  to bytes.LastIndex.
This commit is contained in:
yetone
2026-10-31 15:13:35 +08:00
parent ca7eb9aff7
commit 0273600218
+7 -1
View File
@@ -2291,10 +2291,16 @@ func lastIndex(b, key []byte) int {
return len(b)
}
if len(b) > tail {
if i := bytes.LastIndex(b[len(b)-tail:], key); i >= 0 {
if i := forwardLast(b[len(b)-tail:], key); i >= 0 {
return len(b) - tail + i
}
}
return forwardLast(b, key)
}
// forwardLast is the last key in b, found by Index from each one before;
// even a 1 KB tail took LastIndex ~1 µs.
func forwardLast(b, key []byte) int {
last := -1
for off := 0; off < len(b); {
i := bytes.Index(b[off:], key)