From e7acb7a1e0452ee41c382121cff568c458abbb4d Mon Sep 17 00:00:00 2001 From: Azim Sonawalla Date: Tue, 17 Feb 2026 13:56:47 -0500 Subject: [PATCH] Optimize JSONL scanner chunk parsing --- .../Vendored/CostUsage/CostUsageJsonl.swift | 38 ++++++------- .../CodexBarTests/CostUsageScannerTests.swift | 54 +++++++++++++++++++ 2 files changed, 73 insertions(+), 19 deletions(-) diff --git a/Sources/CodexBarCore/Vendored/CostUsage/CostUsageJsonl.swift b/Sources/CodexBarCore/Vendored/CostUsage/CostUsageJsonl.swift index c5132737a..5105f9759 100644 --- a/Sources/CodexBarCore/Vendored/CostUsage/CostUsageJsonl.swift +++ b/Sources/CodexBarCore/Vendored/CostUsage/CostUsageJsonl.swift @@ -23,15 +23,24 @@ enum CostUsageJsonl { try handle.seek(toOffset: UInt64(startOffset)) } - var buffer = Data() - buffer.reserveCapacity(64 * 1024) - var current = Data() current.reserveCapacity(4 * 1024) var lineBytes = 0 var truncated = false var bytesRead: Int64 = 0 + func appendSegment(_ segment: Data.SubSequence) { + guard !segment.isEmpty else { return } + lineBytes += segment.count + guard !truncated else { return } + if lineBytes > maxLineBytes || lineBytes > prefixBytes { + truncated = true + current.removeAll(keepingCapacity: true) + return + } + current.append(contentsOf: segment) + } + func flushLine() { guard lineBytes > 0 else { return } let line = Line(bytes: current, wasTruncated: truncated) @@ -49,23 +58,14 @@ enum CostUsageJsonl { } bytesRead += Int64(chunk.count) - buffer.append(chunk) - - while true { - guard let nl = buffer.firstIndex(of: 0x0A) else { break } - let linePart = buffer[.. maxLineBytes || lineBytes > prefixBytes { - truncated = true - current.removeAll(keepingCapacity: true) - } else { - current.append(contentsOf: linePart) - } - } + var segmentStart = chunk.startIndex + while let nl = chunk[segmentStart...].firstIndex(of: 0x0A) { + appendSegment(chunk[segmentStart..