| 288 | const WIDTH_CACHE_LIMIT = 8192 |
| 289 | |
| 290 | export const stringWidth: (str: string) => number = str => { |
| 291 | if (!str) { |
| 292 | return 0 |
| 293 | } |
| 294 | |
| 295 | // ASCII fast-path detection — for short ASCII, skip the cache. |
| 296 | if (str.length <= 64) { |
| 297 | let asciiOnly = true |
| 298 | |
| 299 | for (let i = 0; i < str.length; i++) { |
| 300 | const code = str.charCodeAt(i) |
| 301 | |
| 302 | if (code >= 127 || code === 0x1b) { |
| 303 | asciiOnly = false |
| 304 | |
| 305 | break |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | if (asciiOnly) { |
| 310 | return rawStringWidth(str) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | const cached = widthCache.get(str) |
| 315 | |
| 316 | if (cached !== undefined) { |
| 317 | // True LRU: refresh recency by re-inserting (Map iteration is insertion order). |
| 318 | widthCache.delete(str) |
| 319 | widthCache.set(str, cached) |
| 320 | |
| 321 | return cached |
| 322 | } |
| 323 | |
| 324 | const w = rawStringWidth(str) |
| 325 | |
| 326 | if (widthCache.size >= WIDTH_CACHE_LIMIT) { |
| 327 | widthCache.delete(widthCache.keys().next().value!) |
| 328 | } |
| 329 | |
| 330 | widthCache.set(str, w) |
| 331 | |
| 332 | return w |
| 333 | } |
| 334 | |
| 335 | export function widthCacheSize(): number { |
| 336 | return widthCache.size |