Files
Mathias QuinteroandFabian Fett f41c097554 Improve Performance of HTTPField.value (#146)
### Motivation

When instantiating new HTTPFields, the values need to be validated,
legalized and turned into the internal representation.
We use this representation to expose a string in `HTTPField.value` as
well as to iterate over raw bytes using
`HTTPField.withUnsafeBytesOfValue`.

Currently the internal representation is to use a ISO Latin 1 String to
store the bytes only once. This however means that we need to transcode
back and forth for non ascii values, which causes a lot of extra
computations and allocations.

### Modifications

1. Moved logic to a standalone structure for `HTTPField.Value` rather
than `ISOLatin1String`
2. Added Unit Tests and Benchmarks
3. Swapped internal storage of values to be an enum of either a string
or a value
4. Whenever the bytes stored are valid utf8, we will not always store
the value as a raw string. This means that we need the least amount of
allocations and transcoding when operating with the value through our
public API
5. We only store a raw array of bytes whenever the bytes are not valid
utf8. This speeds up `withUnsafeBytesOfValue` massively and
`HTTPField.value` a little bit
6. During legalization, store the modified bytes in a temporary buffer
instead of using lazy collections to avoid allocating an array and speed
up utf8 validation
7. Use spans whenever possible to speed up access to bytes without
boundary checks

### Result

These are the changes on the benchmarks added in this PR

```
HTTPField-asciiBytesValueRoundTrip
Instructions: 28K -> 6847 (-75%)
Malloc: 1 -> 1

HTTPField-asciiValueRoundTrip
Instructions: 7367 -> 3081 (-58%)
Malloc: 0 -> 0

HTTPField-invalidAsciiBytesValueRoundTrip
Instructions: 133K -> 7255 (-94%)
Malloc: 6 -> 1 (-83%)

HTTPField-invalidAsciiBytesValueRoundTripAsLenientValue
Instructions: 62K -> 6623 (-89%)
Malloc: 3 -> 1 (-66%)

HTTPField-invalidAsciiValueRoundTrip
Instructions: 93K -> 6959 (-92%)
Malloc: 5 -> 1 (-80%)

HTTPField-invalidNonASCIIValueRoundTrip
Instructions: 393K -> 8735 (-97%)
Malloc: 11 -> 1 (-91%)

HTTPField-nonASCIIValueRoundTrip
Instructions: 131K -> 3219 (-97%)
Malloc: 4 -> 0 (-100%)
```

---------

Co-authored-by: Fabian Fett <fabianfett@apple.com>
2026-08-31 11:30:56 +02:00

247 lines
8.4 KiB
Swift

//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if !hasFeature(Embedded) || compiler(>=6.4)
struct HTTPParsedFields {
private var method: HTTPField.Value?
private var scheme: HTTPField.Value?
private var authority: HTTPField.Value?
private var path: HTTPField.Value?
private var extendedConnectProtocol: HTTPField.Value?
private var status: HTTPField.Value?
private var contentLength: HTTPField.Value?
private var contentDisposition: HTTPField.Value?
private var location: HTTPField.Value?
private var fields: HTTPFields
enum ParsingError: Error {
case invalidName
case invalidPseudoName
case invalidPseudoValue
case multiplePseudo
case pseudoNotFirst
case requestWithoutMethod
case invalidMethod
case requestWithResponsePseudo
case responseWithoutStatus
case invalidStatus
case responseWithRequestPseudo
case trailerFieldsWithPseudo
case multipleContentLength
case multipleContentDisposition
case multipleLocation
}
init() {
self.fields = .init()
}
init(parsed: [HTTPFields.Element]) throws {
self.fields = .init()
self.fields.reserveCapacity(parsed.count)
for field in parsed {
try self.add(field: field)
}
}
mutating func add(field: HTTPField) throws {
if field.name.isPseudo {
if !self.fields.isEmpty {
throw ParsingError.pseudoNotFirst
}
switch field.name {
case .method:
if self.method != nil {
throw ParsingError.multiplePseudo
}
self.method = field.rawValue
case .scheme:
if self.scheme != nil {
throw ParsingError.multiplePseudo
}
self.scheme = field.rawValue
case .authority:
if self.authority != nil {
throw ParsingError.multiplePseudo
}
self.authority = field.rawValue
case .path:
if self.path != nil {
throw ParsingError.multiplePseudo
}
self.path = field.rawValue
case .protocol:
if self.extendedConnectProtocol != nil {
throw ParsingError.multiplePseudo
}
self.extendedConnectProtocol = field.rawValue
case .status:
if self.status != nil {
throw ParsingError.multiplePseudo
}
self.status = field.rawValue
default:
throw ParsingError.invalidPseudoName
}
} else {
switch field.name {
case .contentLength:
if let contentLength = self.contentLength, contentLength != field.rawValue {
throw ParsingError.multipleContentLength
}
self.contentLength = field.rawValue
case .contentDisposition:
if let contentDisposition = self.contentDisposition, contentDisposition != field.rawValue {
throw ParsingError.multipleContentDisposition
}
self.contentDisposition = field.rawValue
case .location:
if let location = self.location, location != field.rawValue {
throw ParsingError.multipleLocation
}
self.location = field.rawValue
default:
break
}
self.fields.append(field)
}
}
var request: HTTPRequest {
get throws {
guard let method = self.method else {
throw ParsingError.requestWithoutMethod
}
guard let requestMethod = HTTPRequest.Method(method.string) else {
throw ParsingError.invalidMethod
}
if self.status != nil {
throw ParsingError.requestWithResponsePseudo
}
var request = HTTPRequest(
method: requestMethod,
scheme: self.scheme,
authority: self.authority,
path: self.path,
headerFields: self.fields
)
if let extendedConnectProtocol = self.extendedConnectProtocol {
request.pseudoHeaderFields.extendedConnectProtocol = HTTPField(
name: .protocol,
uncheckedValue: extendedConnectProtocol
)
}
return request
}
}
var response: HTTPResponse {
get throws {
guard let statusString = self.status?.string else {
throw ParsingError.responseWithoutStatus
}
if self.method != nil || self.scheme != nil || self.authority != nil || self.path != nil
|| self.extendedConnectProtocol != nil
{
throw ParsingError.responseWithRequestPseudo
}
if !HTTPResponse.Status.isValidStatus(statusString) {
throw ParsingError.invalidStatus
}
return HTTPResponse(status: .init(code: Int(statusString)!), headerFields: self.fields)
}
}
var trailerFields: HTTPFields {
get throws {
if self.method != nil || self.scheme != nil || self.authority != nil || self.path != nil
|| self.extendedConnectProtocol != nil || self.status != nil
{
throw ParsingError.trailerFieldsWithPseudo
}
return self.fields
}
}
}
extension HTTPRequest {
fileprivate init(
method: Method,
scheme: HTTPField.Value?,
authority: HTTPField.Value?,
path: HTTPField.Value?,
headerFields: HTTPFields
) {
let methodField = HTTPField(name: .method, uncheckedValue: HTTPField.Value(unchecked: method.rawValue))
let schemeField = scheme.map { HTTPField(name: .scheme, uncheckedValue: $0) }
let authorityField = authority.map { HTTPField(name: .authority, uncheckedValue: $0) }
let pathField = path.map { HTTPField(name: .path, uncheckedValue: $0) }
self.pseudoHeaderFields = .init(
method: methodField,
scheme: schemeField,
authority: authorityField,
path: pathField
)
self.headerFields = headerFields
}
}
@available(HTTPTypes 1.2, *)
extension HTTPRequest {
/// Create an HTTP request with an array of parsed `HTTPField`. The fields must include the
/// necessary request pseudo header fields.
///
/// - Parameter fields: The array of parsed `HTTPField` produced by HPACK or QPACK decoders
/// used in modern HTTP versions.
public init(parsed fields: [HTTPField]) throws {
let parsedFields = try HTTPParsedFields(parsed: fields)
self = try parsedFields.request
}
}
@available(HTTPTypes 1.2, *)
extension HTTPResponse {
/// Create an HTTP response with an array of parsed `HTTPField`. The fields must include the
/// necessary response pseudo header fields.
///
/// - Parameter fields: The array of parsed `HTTPField` produced by HPACK or QPACK decoders
/// used in modern HTTP versions.
public init(parsed fields: [HTTPField]) throws {
let parsedFields = try HTTPParsedFields(parsed: fields)
self = try parsedFields.response
}
}
@available(HTTPTypes 1.2, *)
extension HTTPFields {
/// Create an HTTP trailer fields with an array of parsed `HTTPField`. The fields must not
/// include any pseudo header fields.
///
/// - Parameter fields: The array of parsed `HTTPField` produced by HPACK or QPACK decoders
/// used in modern HTTP versions.
public init(parsedTrailerFields fields: [HTTPField]) throws {
let parsedFields = try HTTPParsedFields(parsed: fields)
self = try parsedFields.trailerFields
}
}
#endif