source dump of claude code
1import { stringWidth } from './stringWidth.js'
2
3// During streaming, text grows but completed lines are immutable.
4// Caching stringWidth per-line avoids re-measuring hundreds of
5// unchanged lines on every token (~50x reduction in stringWidth calls).
6const cache = new Map<string, number>()
7
8const MAX_CACHE_SIZE = 4096
9
10export function lineWidth(line: string): number {
11 const cached = cache.get(line)
12 if (cached !== undefined) return cached
13
14 const width = stringWidth(line)
15
16 // Evict when cache grows too large (e.g. after many different responses).
17 // Simple full-clear is fine — the cache repopulates in one frame.
18 if (cache.size >= MAX_CACHE_SIZE) {
19 cache.clear()
20 }
21
22 cache.set(line, width)
23 return width
24}