From 40c73b1c3da6cd3a0a00b33f7fec94fe6bc48df9 Mon Sep 17 00:00:00 2001 From: Daniel Duan Date: Thu, 5 Feb 2026 23:20:13 -0800 Subject: [PATCH] Short-circuit empty key lookup paths Skip unsafe-buffer setup in key lookup helpers when the index list is empty. Also decode key substrings directly from pointer ranges in makeString to avoid repeated slice construction on the hot key path. --- Sources/TOMLDecoder/Parsing/Parser.swift | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/Sources/TOMLDecoder/Parsing/Parser.swift b/Sources/TOMLDecoder/Parsing/Parser.swift index ccbf5ea..55032fb 100644 --- a/Sources/TOMLDecoder/Parsing/Parser.swift +++ b/Sources/TOMLDecoder/Parsing/Parser.swift @@ -1885,14 +1885,23 @@ private func packedKeyHash(_ buffer: UnsafeBufferPointer) -> UInt64 { return packed } +@inline(__always) private func makeString(bytes: UnsafeBufferPointer, range: Range) -> String { - String(decoding: bytes[range], as: UTF8.self) + guard let baseAddress = bytes.baseAddress else { + return "" + } + let start = baseAddress.advanced(by: range.lowerBound) + let count = range.upperBound - range.lowerBound + return String(decoding: UnsafeBufferPointer(start: start, count: count), as: UTF8.self) } extension Parser { @inline(__always) func matchKeyValue(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { - keyValues.withUnsafeBufferPointer { keyValueBuffer in + if indices.isEmpty { + return nil + } + return keyValues.withUnsafeBufferPointer { keyValueBuffer -> Int? in guard let keyValueBase = keyValueBuffer.baseAddress else { return nil } @@ -1916,7 +1925,10 @@ extension Parser { @inline(__always) func matchKeyArray(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { - keyArrays.withUnsafeBufferPointer { keyArrayBuffer in + if indices.isEmpty { + return nil + } + return keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in guard let keyArrayBase = keyArrayBuffer.baseAddress else { return nil } @@ -1940,7 +1952,10 @@ extension Parser { @inline(__always) func matchKeyTable(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { - keyTables.withUnsafeBufferPointer { keyTableBuffer in + if indices.isEmpty { + return nil + } + return keyTables.withUnsafeBufferPointer { keyTableBuffer -> Int? in guard let keyTableBase = keyTableBuffer.baseAddress else { return nil }