Reimplement HTTPFields on top of a simple Array (#138)

### Motivation

We like faster and simpler code. When optimizing performance we focus on
often used use-cases.

### Changes

- Reimplement HTTPFields on top of a simple Array

### Result

- HTTPFields building becomes significantly faster
- HTTPFields lookups are faster for small fields, and only slightly
slower for larger (nearly always offset by reduced build time)

Follow ups:

- Make the equality implementation smarter
This commit is contained in:
Fabian Fett authored and GitHub committed 2026-08-18 14:26:31 +02:00
1 parent 4b1dd0cab3
commit 43cf84fb56
113 files changed
+225 -505

No files matched your search

+105 -191
View File
@@ -12,8 +12,6 @@
//
//===----------------------------------------------------------------------===//
import Synchronization
/// A collection of HTTP fields. It is used in `HTTPRequest` and `HTTPResponse`, and can also be
/// used as HTTP trailer fields.
///
@@ -23,150 +21,25 @@ import Synchronization
/// `HTTPFields` adheres to modern HTTP semantics. In particular, the "Cookie" request header field
/// is split into separate header fields by default.
@available(HTTPTypes 1.0, *)
public struct HTTPFields: Sendable, Hashable {
private class _Storage: @unchecked Sendable, Hashable {
var fields: [(field: HTTPField, next: UInt16)] = []
var index: [String: (first: UInt16, last: UInt16)]? = [:]
required init() {
}
#if canImport(Darwin) && !hasFeature(Embedded)
func withLock<Result, Failure: Error>(_ body: () throws(Failure) -> Result) throws(Failure) -> Result {
fatalError()
}
#else
#if !hasFeature(Embedded) || (os(WASI) && compiler(>=6.4))
let mutex = Mutex<Void>(())
#endif
final func withLock<Result, Failure: Error>(_ body: () throws(Failure) -> Result) throws(Failure) -> Result {
#if !hasFeature(Embedded) || (os(WASI) && compiler(>=6.4))
try self.mutex.withLock { _ throws(Failure) in
try body()
}
#else
// Mutex not available
try body()
#endif
}
#endif
var ensureIndex: [String: (first: UInt16, last: UInt16)] {
self.withLock {
if let index = self.index {
return index
}
var newIndex = [String: (first: UInt16, last: UInt16)]()
for index in self.fields.indices {
let name = self.fields[index].field.name.canonicalName
self.fields[index].next = .max
if let lastIndex = newIndex[name]?.last {
self.fields[Int(lastIndex)].next = UInt16(index)
}
newIndex[name, default: (first: UInt16(index), last: 0)].last = UInt16(index)
}
self.index = newIndex
return newIndex
}
}
func copy() -> Self {
let newStorage = Self()
newStorage.fields = self.fields
self.withLock {
newStorage.index = self.index
}
return newStorage
}
func hash(into hasher: inout Hasher) {
for (field, _) in self.fields {
hasher.combine(field)
}
}
static func == (lhs: _Storage, rhs: _Storage) -> Bool {
let leftFieldsIndex = lhs.ensureIndex
let rightFieldsIndex = rhs.ensureIndex
if leftFieldsIndex.count != rightFieldsIndex.count {
return false
}
for (name, (var leftIndex, _)) in leftFieldsIndex {
guard var rightIndex = rightFieldsIndex[name]?.first else {
return false
}
while leftIndex != .max && rightIndex != .max {
let (leftField, leftNext) = lhs.fields[Int(leftIndex)]
let (rightField, rightNext) = rhs.fields[Int(rightIndex)]
if leftField != rightField {
return false
}
leftIndex = leftNext
rightIndex = rightNext
}
if leftIndex != rightIndex {
return false
}
}
return true
}
func append(field: HTTPField) {
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
let name = field.name.canonicalName
let location = UInt16(self.fields.count)
if self.index != nil {
if let entry = self.index![name] {
self.fields[Int(entry.last)].next = location
self.index![name] = (first: entry.first, last: location)
} else {
self.index![name] = (first: location, last: location)
}
}
self.fields.append((field, .max))
precondition(self.fields.count < UInt16.max, "Too many fields")
}
}
#if canImport(Darwin) && !hasFeature(Embedded)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
private final class _StorageWithMutex: _Storage, @unchecked Sendable {
let mutex = Mutex<Void>(())
override func withLock<Result, Failure: Error>(_ body: () throws(Failure) -> Result) throws(Failure) -> Result {
try self.mutex.withLock { _ throws(Failure) in
try body()
}
}
}
private final class _StorageWithNIOLock: _Storage, @unchecked Sendable {
let lock = LockStorage.create(value: ())
override func withLock<Result, Failure: Error>(_ body: () throws(Failure) -> Result) throws(Failure) -> Result {
try self.lock.withLockedValue { _ throws(Failure) in
try body()
}
}
}
#endif
private var _storage = {
#if canImport(Darwin) && !hasFeature(Embedded)
if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {
_StorageWithMutex()
} else {
_StorageWithNIOLock()
}
#else
_Storage()
#endif
}()
public struct HTTPFields: Sendable {
/// The fields, in the order they were added.
private var fields: [HTTPField] = []
/// Create an empty list of HTTP fields
public init() {}
/// The position of the first field at or after `start` whose canonical name is `name`, or
/// `nil` if there is none.
private func firstIndex(ofCanonicalName name: String, from start: [HTTPField].Index = 0) -> Int? {
self.fields[start...].firstIndex(where: { $0.name.canonicalName == name })
}
private mutating func append(field: HTTPField) {
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
self.fields.append(field)
precondition(self.fields.count < UInt16.max, "Too many fields")
}
/// Access the field value string by name.
///
/// Example:
@@ -236,54 +109,60 @@ public struct HTTPFields: Sendable, Hashable {
}
private struct HTTPFieldSequence: Sequence {
let fields: [(field: HTTPField, next: UInt16)]
let index: UInt16
let fields: HTTPFields
let name: HTTPField.Name
struct Iterator: IteratorProtocol {
let fields: [(field: HTTPField, next: UInt16)]
var index: UInt16
let fields: HTTPFields
let name: HTTPField.Name
/// The position to resume scanning at. Keeping it in the iterator makes reading all
/// the fields with one name a single pass over `fields`.
var index: Int
init(fields: HTTPFields, name: HTTPField.Name) {
self.fields = fields
self.name = name
self.index = fields.startIndex
}
mutating func next() -> HTTPField? {
if self.index == .max {
return nil
if let index = self.fields.firstIndex(ofCanonicalName: self.name.canonicalName, from: self.index) {
defer { self.index = self.fields.index(after: index) }
return self.fields[index]
}
let (field, next) = self.fields[Int(self.index)]
self.index = next
return field
return nil
}
}
func makeIterator() -> Iterator {
Iterator(fields: self.fields, index: self.index)
Iterator(fields: self.fields, name: self.name)
}
}
private func fields(for name: HTTPField.Name) -> HTTPFieldSequence {
let index = self._storage.ensureIndex[name.canonicalName]?.first ?? .max
return HTTPFieldSequence(fields: self._storage.fields, index: index)
HTTPFieldSequence(fields: self, name: name)
}
private mutating func setFields(_ fieldSequence: some Sequence<HTTPField>, for name: HTTPField.Name) {
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
var existingIndex = self._storage.ensureIndex[name.canonicalName]?.first ?? .max
let canonicalName = name.canonicalName
var existingIndex = self.firstIndex(ofCanonicalName: canonicalName)
var newFieldIterator = fieldSequence.makeIterator()
var toDelete = [Int]()
while existingIndex != .max {
// A single pass over the fields: the existing fields with this name are overwritten in
// place while new fields last, and the leftovers are collected for removal.
while let index = existingIndex {
if let field = newFieldIterator.next() {
self._storage.fields[Int(existingIndex)].field = field
self.fields[index] = field
} else {
toDelete.append(Int(existingIndex))
toDelete.append(index)
}
existingIndex = self._storage.fields[Int(existingIndex)].next
existingIndex = self.firstIndex(ofCanonicalName: canonicalName, from: index + 1)
}
if !toDelete.isEmpty {
self._storage.fields.remove(at: toDelete)
self._storage.index = nil
self.fields.remove(at: toDelete)
}
while let field = newFieldIterator.next() {
self._storage.append(field: field)
self.append(field: field)
}
}
@@ -291,7 +170,54 @@ public struct HTTPFields: Sendable, Hashable {
/// - Parameter name: The field name.
/// - Returns: Whether a field exists.
public func contains(_ name: HTTPField.Name) -> Bool {
self._storage.ensureIndex[name.canonicalName] != nil
self.firstIndex(ofCanonicalName: name.canonicalName) != nil
}
}
extension HTTPFields: Equatable {
public static func == (lhs: HTTPFields, rhs: HTTPFields) -> Bool {
// Two field lists are equal when, for every name, they hold the same fields in the
// same order. That implies an equal total field count, so checking it up front also
// proves that matching every name run of `lhs` leaves no unmatched field in `rhs`.
if lhs.fields.count != rhs.fields.count {
return false
}
// Fast path: field lists that were built the same way carry their fields in the same
// order, so a single lock step walk usually settles it. Element wise equality is
// sufficient, but not necessary, for the definition above, so a mismatch only means the
// general comparison below has to run.
if lhs.fields.elementsEqual(rhs.fields) {
return true
}
for position in lhs.fields.indices {
let name = lhs.fields[position].name.canonicalName
if lhs.firstIndex(ofCanonicalName: name) != position {
// Not the first field with this name; its run was compared already.
continue
}
var leftIndex: Int? = position
var rightIndex = rhs.firstIndex(ofCanonicalName: name)
while let left = leftIndex, let right = rightIndex {
if lhs.fields[left] != rhs.fields[right] {
return false
}
leftIndex = lhs.firstIndex(ofCanonicalName: name, from: left + 1)
rightIndex = rhs.firstIndex(ofCanonicalName: name, from: right + 1)
}
if (leftIndex == nil) != (rightIndex == nil) {
// One of the two runs of this name is longer than the other.
return false
}
}
return true
}
}
extension HTTPFields: Hashable {
public func hash(into hasher: inout Hasher) {
for field in self.fields {
hasher.combine(field)
}
}
}
@@ -301,7 +227,7 @@ extension HTTPFields: ExpressibleByDictionaryLiteral {
self.reserveCapacity(elements.count)
for (name, value) in elements {
precondition(!name.isPseudo, "Pseudo header field \"\(name)\" disallowed")
self._storage.append(field: HTTPField(name: name, value: value))
self.append(field: HTTPField(name: name, value: value))
}
precondition(self.count < UInt16.max, "Too many fields")
}
@@ -313,15 +239,15 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
public typealias Index = Int
public var startIndex: Int {
self._storage.fields.startIndex
self.fields.startIndex
}
public var endIndex: Int {
self._storage.fields.endIndex
self.fields.endIndex
}
public var isEmpty: Bool {
self._storage.fields.isEmpty
self.fields.isEmpty
}
public subscript(position: Int) -> HTTPField {
@@ -329,43 +255,35 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
guard position >= self.startIndex, position < self.endIndex else {
preconditionFailure("getter position: \(position) out of range in HTTPFields")
}
return self._storage.fields[position].field
return self.fields[position]
}
set {
guard position >= self.startIndex, position < self.endIndex else {
preconditionFailure("setter position: \(position) out of range in HTTPFields")
}
if self._storage.fields[position].field == newValue {
if self.fields[position] == newValue {
return
}
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
if newValue.name != self._storage.fields[position].field.name {
if newValue.name != self.fields[position].name {
precondition(!newValue.name.isPseudo, "Pseudo header field \"\(newValue.name)\" disallowed")
self._storage.index = nil
}
self._storage.fields[position].field = newValue
self.fields[position] = newValue
}
}
public mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C)
where C: Collection, Element == C.Element {
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
if subrange.startIndex == self.count {
for field in newElements {
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
self._storage.append(field: field)
self.append(field: field)
}
} else {
self._storage.index = nil
self._storage.fields.replaceSubrange(
self.fields.replaceSubrange(
subrange,
with: newElements.lazy.map { field in
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
return (field, 0)
return field
}
)
precondition(self.count < UInt16.max, "Too many fields")
@@ -373,11 +291,7 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
}
public mutating func reserveCapacity(_ capacity: Int) {
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
self._storage.index?.reserveCapacity(capacity)
self._storage.fields.reserveCapacity(capacity)
self.fields.reserveCapacity(capacity)
}
}
@@ -386,7 +300,7 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
@available(HTTPTypes 1.0, *)
extension HTTPFields: CustomDebugStringConvertible {
public var debugDescription: String {
self._storage.fields.description
self.fields.description
}
}
-204
View File
@@ -1,204 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Darwin)
import Darwin
#elseif os(Windows)
import ucrt
import WinSDK
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Bionic)
import Bionic
#elseif canImport(WASILibc)
import WASILibc
#if canImport(wasi_pthread)
import wasi_pthread
#endif
#else
#error("The concurrency NIOLock module was unable to identify your C library.")
#endif
#if os(Windows)
typealias LockPrimitive = SRWLOCK
#elseif canImport(Darwin)
typealias LockPrimitive = os_unfair_lock
#elseif os(FreeBSD) || os(OpenBSD)
typealias LockPrimitive = pthread_mutex_t?
#else
typealias LockPrimitive = pthread_mutex_t
#endif
enum LockOperations {}
extension LockOperations {
static func create(_ mutex: UnsafeMutablePointer<LockPrimitive>) {
mutex.assertValidAlignment()
#if os(Windows)
InitializeSRWLock(mutex)
#elseif canImport(Darwin)
mutex.initialize(to: .init())
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
#if os(FreeBSD) || os(OpenBSD)
var attr = pthread_mutexattr_t(bitPattern: 0)
#else
var attr = pthread_mutexattr_t()
#endif
pthread_mutexattr_init(&attr)
let err = pthread_mutex_init(mutex, &attr)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
}
static func destroy(_ mutex: UnsafeMutablePointer<LockPrimitive>) {
mutex.assertValidAlignment()
#if os(Windows)
// SRWLOCK does not need to be free'd
#elseif canImport(Darwin)
// os_unfair_lock does not need to be free'd
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
let err = pthread_mutex_destroy(mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
}
static func lock(_ mutex: UnsafeMutablePointer<LockPrimitive>) {
mutex.assertValidAlignment()
#if os(Windows)
AcquireSRWLockExclusive(mutex)
#elseif canImport(Darwin)
os_unfair_lock_lock(mutex)
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
let err = pthread_mutex_lock(mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
}
static func unlock(_ mutex: UnsafeMutablePointer<LockPrimitive>) {
mutex.assertValidAlignment()
#if os(Windows)
ReleaseSRWLockExclusive(mutex)
#elseif canImport(Darwin)
os_unfair_lock_unlock(mutex)
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
let err = pthread_mutex_unlock(mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
}
}
// Tail allocate both the mutex and a generic value using ManagedBuffer.
// Both the header pointer and the elements pointer are stable for
// the class's entire lifetime.
//
// However, for safety reasons, we elect to place the lock in the "elements"
// section of the buffer instead of the head. The reasoning here is subtle,
// so buckle in.
//
// _As a practical matter_, the implementation of ManagedBuffer ensures that
// the pointer to the header is stable across the lifetime of the class, and so
// each time you call `withUnsafeMutablePointers` or `withUnsafeMutablePointerToHeader`
// the value of the header pointer will be the same. This is because ManagedBuffer uses
// `Builtin.addressOf` to load the value of the header, and that does ~magic~ to ensure
// that it does not invoke any weird Swift accessors that might copy the value.
//
// _However_, the header is also available via the `.header` field on the ManagedBuffer.
// This presents a problem! The reason there's an issue is that `Builtin.addressOf` and friends
// do not interact with Swift's exclusivity model. That is, the various `with` functions do not
// conceptually trigger a mutating access to `.header`. For elements this isn't a concern because
// there's literally no other way to perform the access, but for `.header` it's entirely possible
// to accidentally recursively read it.
//
// Our implementation is free from these issues, so we don't _really_ need to worry about it.
// However, out of an abundance of caution, we store the Value in the header, and the LockPrimitive
// in the trailing elements. We still don't use `.header`, but it's better to be safe than sorry,
// and future maintainers will be happier that we were cautious.
//
// See also: https://github.com/apple/swift/pull/40000
final class LockStorage<Value>: ManagedBuffer<Value, LockPrimitive> {
static func create(value: Value) -> Self {
let buffer = Self.create(minimumCapacity: 1) { _ in
value
}
// Intentionally using a force cast here to avoid a miss compiliation in 5.10.
// This is as fast as an unsafeDownCast since ManagedBuffer is inlined and the optimizer
// can eliminate the upcast/downcast pair
let storage = buffer as! Self
storage.withUnsafeMutablePointers { _, lockPtr in
LockOperations.create(lockPtr)
}
return storage
}
func lock() {
self.withUnsafeMutablePointerToElements { lockPtr in
LockOperations.lock(lockPtr)
}
}
func unlock() {
self.withUnsafeMutablePointerToElements { lockPtr in
LockOperations.unlock(lockPtr)
}
}
deinit {
self.withUnsafeMutablePointerToElements { lockPtr in
LockOperations.destroy(lockPtr)
}
}
func withLockPrimitive<T, E: Error>(_ body: (UnsafeMutablePointer<LockPrimitive>) throws(E) -> T) throws(E) -> T {
try self.withUnsafeMutablePointerToElements { lockPtr throws(E) in
try body(lockPtr)
}
}
func withLockedValue<T, E: Error>(_ mutate: (inout Value) throws(E) -> T) throws(E) -> T {
try self.withUnsafeMutablePointers { valuePtr, lockPtr throws(E) in
LockOperations.lock(lockPtr)
defer { LockOperations.unlock(lockPtr) }
return try mutate(&valuePtr.pointee)
}
}
}
extension UnsafeMutablePointer {
func assertValidAlignment() {
assert(UInt(bitPattern: self) % UInt(MemoryLayout<Pointee>.alignment) == 0)
}
}