Internal API review feedback

This commit is contained in:
Guoye Zhang committed 2023-06-30 10:06:35 -07:00
1 parent c164739694
commit ae848811f9
22 files changed
+798 -428

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
.DS_Store
.swift-version
/.build
/Packages
.xcode
/*.xcodeproj
.xcode
.swiftpm/
Package.resolved
# DocC generated files
.docc-build
+4
View File
@@ -0,0 +1,4 @@
version: 1
builder:
configs:
- documentation_targets: [HTTPTypes, HTTPTypesFoundation]
+20
View File
@@ -0,0 +1,20 @@
--swiftversion 5.8
# file options
--exclude .build
# format options
--ifdef no-indent
--indent 4
--extensionacl on-declarations
--patternlet inline
--self insert
--stripunusedargs closure-only
--wraparguments before-first
# rules
--disable blankLinesAroundMark
--disable wrapMultilineStatementBraces
+10 -4
View File
@@ -1,4 +1,4 @@
// swift-tools-version: 5.9
// swift-tools-version: 5.8
import PackageDescription
@@ -8,22 +8,28 @@ let package = Package(
.library(name: "HTTPTypes", targets: ["HTTPTypes"]),
.library(name: "HTTPTypesFoundation", targets: ["HTTPTypesFoundation"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.3.0"),
],
targets: [
.target(name: "HTTPTypes"),
.target(
name: "HTTPTypesFoundation",
dependencies: [
"HTTPTypes",
]),
]
),
.testTarget(
name: "HTTPTypesTests",
dependencies: [
"HTTPTypes",
]),
]
),
.testTarget(
name: "HTTPTypesFoundationTests",
dependencies: [
"HTTPTypesFoundation",
]),
]
),
]
)
+86 -2
View File
@@ -6,7 +6,7 @@ Swift HTTP Types are version-independent HTTP currency types designed for both c
Add the following dependency clause to your Package.swift:
```
```swift
dependencies: [
.package(url: "https://github.com/apple/swift-http-types.git", from: "0.1.0")
]
@@ -16,7 +16,91 @@ The `HTTPTypes` library exposes the core HTTP currency types, including `HTTPReq
The `HTTPTypesFoundation` library provides conveniences for using new HTTP types with Foundation, including bidirectional convertors between the new types and Foundation URL types, and URLSession convenience methods with the new types.
The `HTTPTypesNIO`, `HTTPTypesNIOHTTP1`, and `HTTPTypesNIOHTTP2` libraries provide channel handlers for translating the version-specific NIO HTTP types with the new HTTP types. They can be found in [`swift-nio-extras`](https://github.com/apple/swift-nio-extras).
The `NIOHTTPTypes`, `NIOHTTPTypesHTTP1`, and `NIOHTTPTypesHTTP2` libraries provide channel handlers for translating the version-specific NIO HTTP types with the new HTTP types. They can be found in [`swift-nio-extras`](https://github.com/apple/swift-nio-extras).
## Usage
#### Create a request
```swift
let request = HTTPRequest(method: .get, scheme: "https", authority: "www.example.com", path: "/")
```
#### Create a request from a Foundation URL
```swift
var request = HTTPRequest(method: .get, url: URL(string: "https://www.example.com/")!)
request.method = .post
request.path = "/upload"
```
#### Create a response
```swift
let response = HTTPResponse(status: .ok)
```
#### Access and modify header fields
```swift
extension HTTPField.Name {
static let myCustomHeader = Self("My-Custom-Header")!
}
// Set
request.headerFields[.userAgent] = "MyApp/1.0"
request.headerFields[.myCustomHeader] = "custom-value"
request.headerFields[raw: .acceptLanguage] = ["en-US", "zh-Hans-CN"]
// Get
request.headerFields[.userAgent] // "MyApp/1.0"
request.headerFields[.myCustomHeader] // "custom-value"
request.headerFields[.acceptLanguage] // "en-US, zh-Hans-CN"
request.headerFields[raw: .acceptLanguage] // ["en-US", "zh-Hans-CN"]
```
#### Use with URLSession
```swift
var request = HTTPRequest(method: .post, url: URL(string: "https://www.example.com/upload")!)
request.headerFields[.userAgent] = "MyApp/1.0"
let (responseBody, response) = try await URLSession.shared.upload(for: request, from: requestBody)
guard response.status == .created else {
// Handle error
}
```
#### Use with SwiftNIO
```swift
channel.configureHTTP2Pipeline(mode: .server) { channel in
channel.pipeline.addHandlers([
HTTP2FramePayloadToHTTPServerCodec(),
ExampleChannelHandler()
])
}.map { _ in () }
```
```swift
final class ExampleChannelHandler: ChannelDuplexHandler {
typealias InboundIn = HTTPTypeServerRequestPart
typealias OutboundOut = HTTPTypeServerResponsePart
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch unwrapInboundIn(data) {
case .head(let request):
// Handle request headers
case .body(let body):
// Handle request body
case .end(let trailers):
// Handle complete request
let response = HTTPResponse(status: .ok)
context.write(wrapOutboundOut(.head(response)), promise: nil)
context.writeAndFlush(wrapOutboundOut(.end(nil)), promise: nil)
}
}
}
```
## Developing HTTP Types
+52
View File
@@ -0,0 +1,52 @@
# ``HTTPTypes``
A set of version-independent HTTP currency types.
## Overview
`HTTPRequest` represents an HTTP request message, including its method, scheme, authority, path, and header fields.
`HTTPResponse` represents an HTTP response message, including its status and header fields.
`HTTPFields` represents a list of HTTP header or trailer fields.
## Getting Started
#### Create a request
```swift
let request = HTTPRequest(method: .get, scheme: "https", authority: "www.example.com", path: "/")
```
#### Create a request from a Foundation URL
```swift
var request = HTTPRequest(method: .get, url: URL(string: "https://www.example.com/")!)
request.method = .post
request.path = "/upload"
```
#### Create a response
```swift
let response = HTTPResponse(status: .ok)
```
#### Access and modify header fields
```swift
extension HTTPField.Name {
static let myCustomHeader = Self("My-Custom-Header")!
}
// Set
request.headerFields[.userAgent] = "MyApp/1.0"
request.headerFields[.myCustomHeader] = "custom-value"
request.headerFields[raw: .acceptLanguage] = ["en-US", "zh-Hans-CN"]
// Get
request.headerFields[.userAgent] // "MyApp/1.0"
request.headerFields[.myCustomHeader] // "custom-value"
request.headerFields[.acceptLanguage] // "en-US, zh-Hans-CN"
request.headerFields[raw: .acceptLanguage] // ["en-US", "zh-Hans-CN"]
```
+32 -27
View File
@@ -1,41 +1,46 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// HTTP field is a name-value pair with additional metadata.
/// A name-value pair with additional metadata.
///
/// HTTP field name is a case-insensitive but case-preserving ASCII string; HTTP field value is a
/// The field name is a case-insensitive but case-preserving ASCII string; the field value is a
/// collection of bytes.
public struct HTTPField: Sendable, Hashable {
/// The strategy for whether the field is indexed in the HPACK or QPACK dynamic table.
public enum DynamicTableIndexingStrategy: UInt8, Sendable, Hashable {
public struct DynamicTableIndexingStrategy: Sendable, Hashable {
/// Default strategy.
case automatic
public static var automatic: Self { .init(rawValue: 0) }
/// Always put this field in the dynamic table if possible.
case prefer
public static var prefer: Self { .init(rawValue: 1) }
/// Don't put this field in the dynamic table.
case avoid
public static var avoid: Self { .init(rawValue: 2) }
/// Don't put this field in the dynamic table, and set a flag to disallow intermediaries to
/// index this field.
case disallow
public static var disallow: Self { .init(rawValue: 3) }
private let rawValue: UInt8
}
/// Create an HTTP field from a name and a value.
/// - Parameters:
/// - name: The HTTP field name.
/// - value: The HTTP field value is initialized from the UTF-8 encoded bytes of the string.
/// Invalid bytes are converted into whitespace characters.
public init(name: Name, value: some StringProtocol) {
/// Invalid bytes are converted into space characters.
public init(name: Name, value: String) {
self.name = name
self.rawValue = Self.legalizeValue(ISOLatin1String(value))
}
@@ -43,7 +48,7 @@ public struct HTTPField: Sendable, Hashable {
/// Create an HTTP field from a name and a value.
/// - Parameters:
/// - name: The HTTP field name.
/// - value: The HTTP field value. Invalid bytes are converted into whitespace characters.
/// - value: The HTTP field value. Invalid bytes are converted into space characters.
public init(name: Name, value: some Collection<UInt8>) {
self.name = name
self.rawValue = Self.legalizeValue(ISOLatin1String(value))
@@ -59,18 +64,18 @@ public struct HTTPField: Sendable, Hashable {
/// The HTTP field value as a UTF-8 string.
///
/// When setting the value, invalid bytes (defined in RFC 9110) are converted into whitespace characters.
/// When setting the value, invalid bytes (defined in RFC 9110) are converted into space characters.
///
/// https://www.rfc-editor.org/rfc/rfc9110.html#name-field-values
///
/// If the field is not UTF-8 encoded, `withUnsafeValueBytes` can be used to access the
/// If the field is not UTF-8 encoded, `withUnsafeBytesOfValue` can be used to access the
/// underlying bytes of the field value.
public var value: String {
get {
rawValue.string
self.rawValue.string
}
set {
rawValue = Self.legalizeValue(ISOLatin1String(newValue))
self.rawValue = Self.legalizeValue(ISOLatin1String(newValue))
}
}
@@ -83,8 +88,8 @@ public struct HTTPField: Sendable, Hashable {
///
/// - Parameter body: The closure to be invoked with the buffer.
/// - Returns: Result of the `body` closure.
public func withUnsafeValueBytes<Result>(_ body: (UnsafeBufferPointer<UInt8>) throws -> Result) rethrows -> Result {
try rawValue.withUnsafeBytes(body)
public func withUnsafeBytesOfValue<Result>(_ body: (UnsafeBufferPointer<UInt8>) throws -> Result) rethrows -> Result {
try self.rawValue.withUnsafeBytes(body)
}
/// The strategy for whether the field is indexed in the HPACK or QPACK dynamic table.
@@ -106,7 +111,7 @@ public struct HTTPField: Sendable, Hashable {
switch byte {
case 0x09, 0x20:
break
case 0x21...0x7E, 0x80...0xFF:
case 0x21 ... 0x7E, 0x80 ... 0xFF:
break
default:
return false
@@ -132,7 +137,7 @@ public struct HTTPField: Sendable, Hashable {
switch byte {
case 0x09, 0x20:
return byte
case 0x21...0x7E, 0x80...0xFF:
case 0x21 ... 0x7E, 0x80 ... 0xFF:
return byte
default:
return 0x20
@@ -149,8 +154,8 @@ public struct HTTPField: Sendable, Hashable {
///
/// - Parameter value: The string to validate.
/// - Returns: Whether the string is valid.
public static func isValidValue(_ value: some StringProtocol) -> Bool {
_isValidValue(value.utf8)
public static func isValidValue(_ value: String) -> Bool {
self._isValidValue(value.utf8)
}
/// Whether the byte collection is valid for an HTTP field value based on RFC 9110.
@@ -160,19 +165,19 @@ public struct HTTPField: Sendable, Hashable {
/// - Parameter value: The byte collection to validate.
/// - Returns: Whether the byte collection is valid.
public static func isValidValue(_ value: some Collection<UInt8>) -> Bool {
_isValidValue(value)
self._isValidValue(value)
}
}
extension HTTPField: CustomStringConvertible {
public var description: String {
"\(name): \(value)"
"\(self.name): \(self.value)"
}
}
extension HTTPField: CustomPlaygroundDisplayConvertible {
public var playgroundDescription: Any {
description
self.description
}
}
@@ -182,7 +187,7 @@ extension HTTPField {
switch $0 {
case 0x21, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2A, 0x2B, 0x2D, 0x2E, 0x5E, 0x5F, 0x60, 0x7C, 0x7E:
return true
case 0x30...0x39, 0x41...0x5A, 0x61...0x7A: // DIGHT, ALPHA
case 0x30 ... 0x39, 0x41 ... 0x5A, 0x61 ... 0x7A: // DIGHT, ALPHA
return true
default:
return false
+10 -10
View File
@@ -1,24 +1,24 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension HTTPField {
/// HTTP field name is a case-insensitive but case-preserving ASCII string with an allowed
/// character set defined in RFC 9110.
/// A case-insensitive but case-preserving ASCII string with an allowed character set defined
/// in RFC 9110.
///
/// https://www.rfc-editor.org/rfc/rfc9110.html#name-field-names
///
/// Common HTTP field names are provided as convenience static functions, and for custom field
/// Common HTTP field names are provided as convenience static properties, and for custom field
/// names, it is recommended to extend the `HTTPField.Name` struct with new static members.
///
/// ```
@@ -44,8 +44,8 @@ extension HTTPField {
guard HTTPField.isValidToken(name) else {
return nil
}
rawName = name
canonicalName = name.lowercased()
self.rawName = name
self.canonicalName = name.lowercased()
}
private init(rawName: String, canonicalName: String) {
@@ -60,7 +60,7 @@ extension HTTPField.Name: Hashable {
hasher.combine(canonicalName)
}
public static func ==(lhs: HTTPField.Name, rhs: HTTPField.Name) -> Bool {
public static func == (lhs: HTTPField.Name, rhs: HTTPField.Name) -> Bool {
lhs.canonicalName == rhs.canonicalName
}
}
@@ -73,7 +73,7 @@ extension HTTPField.Name: LosslessStringConvertible {
extension HTTPField.Name: CustomPlaygroundDisplayConvertible {
public var playgroundDescription: Any {
description
self.description
}
}
+77 -78
View File
@@ -1,12 +1,12 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
@@ -18,8 +18,8 @@
@_implementationOnly import Glibc
#endif
/// A collection of HTTP fields. It is used in `HTTPRequest` and `HTTPResponse`, and also used for
/// HTTP trailer fields.
/// A collection of HTTP fields. It is used in `HTTPRequest` and `HTTPResponse`, and can also be
/// used as HTTP trailer fields.
///
/// HTTP fields are an ordered list of name-value pairs. Each field is represented as an instance
/// of `HTTPField` struct. `HTTPFields` also offers conveniences to look up fields by their names.
@@ -30,48 +30,48 @@ public struct HTTPFields: Sendable, Hashable {
private final class _Storage: @unchecked Sendable, Hashable {
var fields: [(HTTPField, UInt16)] = []
var index: [String: UInt16]? = [:]
#if canImport(os.lock)
#if canImport(os.lock)
let lock = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1)
#else
#else
let lock = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
#endif
#endif
init() {
#if canImport(os.lock)
lock.initialize(to: os_unfair_lock())
#else
#if canImport(os.lock)
self.lock.initialize(to: os_unfair_lock())
#else
let err = pthread_mutex_init(lock, nil)
precondition(err == 0, "pthread_mutex_init failed with error \(err)")
#endif
#endif
}
deinit {
#if !canImport(os.lock)
#if !canImport(os.lock)
let err = pthread_mutex_destroy(lock)
precondition(err == 0, "pthread_mutex_destroy failed with error \(err)")
#endif
#endif
lock.deallocate()
}
var ensureIndex: [String: UInt16] {
#if canImport(os.lock)
os_unfair_lock_lock(lock)
#if canImport(os.lock)
os_unfair_lock_lock(self.lock)
defer { os_unfair_lock_unlock(lock) }
#else
#else
let err = pthread_mutex_lock(lock)
precondition(err == 0, "pthread_mutex_lock failed with error \(err)")
defer {
let err = pthread_mutex_unlock(lock)
precondition(err == 0, "pthread_mutex_unlock failed with error \(err)")
}
#endif
if let index = index {
#endif
if let index = self.index {
return index
}
var newIndex = [String: UInt16]()
for i in fields.indices.reversed() {
let name = fields[i].0.name.canonicalName
fields[i].1 = newIndex[name] ?? .max
for i in self.fields.indices.reversed() {
let name = self.fields[i].0.name.canonicalName
self.fields[i].1 = newIndex[name] ?? .max
newIndex[name] = UInt16(i)
}
index = newIndex
@@ -80,29 +80,29 @@ public struct HTTPFields: Sendable, Hashable {
func copy() -> _Storage {
let newStorage = _Storage()
newStorage.fields = fields
#if canImport(os.lock)
os_unfair_lock_lock(lock)
#else
newStorage.fields = self.fields
#if canImport(os.lock)
os_unfair_lock_lock(self.lock)
#else
do {
let err = pthread_mutex_lock(lock)
precondition(err == 0, "pthread_mutex_lock failed with error \(err)")
}
#endif
newStorage.index = index
#if canImport(os.lock)
os_unfair_lock_unlock(lock)
#else
#endif
newStorage.index = self.index
#if canImport(os.lock)
os_unfair_lock_unlock(self.lock)
#else
do {
let err = pthread_mutex_unlock(lock)
precondition(err == 0, "pthread_mutex_unlock failed with error \(err)")
}
#endif
#endif
return newStorage
}
func hash(into hasher: inout Hasher) {
for (field, _) in fields {
for (field, _) in self.fields {
hasher.combine(field)
}
}
@@ -115,29 +115,25 @@ public struct HTTPFields: Sendable, Hashable {
let name = field.name.canonicalName
if var index = index?[name] {
while true {
let next = fields[Int(index)].1
let next = self.fields[Int(index)].1
if next == .max { break }
index = next
}
fields[Int(index)].1 = UInt16(fields.count)
self.fields[Int(index)].1 = UInt16(self.fields.count)
} else {
index?[name] = UInt16(fields.count)
index?[name] = UInt16(self.fields.count)
}
fields.append((field, .max))
self.fields.append((field, .max))
}
}
private var _storage = _Storage()
/// Create an empty list of HTTP fields
public init() {
}
public init() {}
/// Access the field value string by name.
///
/// If multiple fields with the same name exist, they are concatenated with commas (or
/// semicolons in the case of the "Cookie" header field).
///
/// Example:
/// ```swift
/// // Set a header field in the request.
@@ -147,6 +143,9 @@ public struct HTTPFields: Sendable, Hashable {
/// let contentTypeValue = response.headerFields[.contentType]
/// ```
///
/// If multiple fields with the same name exist, they are concatenated with commas (or
/// semicolons in the case of the "Cookie" header field).
///
/// When setting a "Cookie" header field value, it is split into multiple "Cookie" fields by
/// semicolon.
public subscript(name: HTTPField.Name) -> String? {
@@ -164,7 +163,7 @@ public struct HTTPFields: Sendable, Hashable {
if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *),
name == .cookie {
self[fields: name] = newValue.split(separator: "; ", omittingEmptySubsequences: false).map {
HTTPField(name: name, value: $0)
HTTPField(name: name, value: String($0))
}
} else {
self[raw: name] = [newValue]
@@ -189,35 +188,35 @@ public struct HTTPFields: Sendable, Hashable {
public subscript(fields name: HTTPField.Name) -> [HTTPField] {
get {
var fields = [HTTPField]()
var index = _storage.ensureIndex[name.canonicalName] ?? .max
var index = self._storage.ensureIndex[name.canonicalName] ?? .max
while index != .max {
let (field, next) = _storage.fields[Int(index)]
let (field, next) = self._storage.fields[Int(index)]
fields.append(field)
index = next
}
return fields
}
set {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.copy()
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
var existingIndex = _storage.ensureIndex[name.canonicalName] ?? .max
var existingIndex = self._storage.ensureIndex[name.canonicalName] ?? .max
var newFieldIterator = newValue.makeIterator()
var toDelete = [Int]()
while existingIndex != .max {
if let field = newFieldIterator.next() {
_storage.fields[Int(existingIndex)].0 = field
self._storage.fields[Int(existingIndex)].0 = field
} else {
toDelete.append(Int(existingIndex))
}
existingIndex = _storage.fields[Int(existingIndex)].1
existingIndex = self._storage.fields[Int(existingIndex)].1
}
if !toDelete.isEmpty {
_storage.fields.remove(at: toDelete)
_storage.index = nil
self._storage.fields.remove(at: toDelete)
self._storage.index = nil
}
while let field = newFieldIterator.next() {
_storage.append(field: field)
self._storage.append(field: field)
}
}
}
@@ -226,14 +225,14 @@ public struct HTTPFields: Sendable, Hashable {
/// - Parameter name: The field name.
/// - Returns: Whether a field exists.
public func contains(_ name: HTTPField.Name) -> Bool {
_storage.ensureIndex[name.canonicalName] != nil
self._storage.ensureIndex[name.canonicalName] != nil
}
}
extension HTTPFields: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (HTTPField.Name, String)...) {
for (name, value) in elements {
_storage.append(field: HTTPField(name: name, value: value))
self._storage.append(field: HTTPField(name: name, value: value))
}
}
}
@@ -243,73 +242,73 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
public typealias Index = Int
public var startIndex: Int {
_storage.fields.startIndex
self._storage.fields.startIndex
}
public var endIndex: Int {
_storage.fields.endIndex
self._storage.fields.endIndex
}
public var isEmpty: Bool {
_storage.fields.isEmpty
self._storage.fields.isEmpty
}
public subscript(position: Int) -> HTTPField {
get {
guard position >= self.startIndex && position < self.endIndex else {
guard position >= self.startIndex, position < self.endIndex else {
preconditionFailure("getter position: \(position) out of range in HTTPFields")
}
return _storage.fields[position].0
return self._storage.fields[position].0
}
set {
guard position >= self.startIndex && position < self.endIndex else {
guard position >= self.startIndex, position < self.endIndex else {
preconditionFailure("setter position: \(position) out of range in HTTPFields")
}
if _storage.fields[position].0 == newValue {
if self._storage.fields[position].0 == newValue {
return
}
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.copy()
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
if newValue.name != _storage.fields[position].0.name {
_storage.index = nil
if newValue.name != self._storage.fields[position].0.name {
self._storage.index = nil
}
_storage.fields[position].0 = newValue
self._storage.fields[position].0 = newValue
}
}
public mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C: Collection, Element == C.Element {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.copy()
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
if subrange.startIndex == count {
for field in newElements {
_storage.append(field: field)
self._storage.append(field: field)
}
} else {
_storage.index = nil
_storage.fields.replaceSubrange(subrange, with: newElements.lazy.map { ($0, 0) })
self._storage.index = nil
self._storage.fields.replaceSubrange(subrange, with: newElements.lazy.map { ($0, 0) })
}
}
public mutating func reserveCapacity(_ n: Int) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.copy()
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
_storage.index?.reserveCapacity(n)
_storage.fields.reserveCapacity(n)
self._storage.index?.reserveCapacity(n)
self._storage.fields.reserveCapacity(n)
}
}
extension HTTPFields: CustomDebugStringConvertible {
public var debugDescription: String {
_storage.fields.description
self._storage.fields.description
}
}
extension Array {
// `removalIndices` must be ordered.
mutating func remove<S: Sequence>(at removalIndices: S) where S.Element == Index {
mutating func remove(at removalIndices: some Sequence<Index>) {
var offset = 0
var iterator = removalIndices.makeIterator()
var nextToRemoveOptional = iterator.next()
+125 -127
View File
@@ -1,18 +1,18 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// HTTP request message consists of pseudo header fields and header fields.
/// An HTTP request message consisting of pseudo header fields and header fields.
///
/// Currently supported pseudo header fields are ":method", ":scheme", ":authority", ":path", and
/// ":protocol". Conveniences are provided to set these pseudo header fields through a URL and
@@ -21,7 +21,7 @@
/// In a legacy HTTP/1 context, the ":scheme" is ignored and the ":authority" is translated into
/// the "Host" header.
public struct HTTPRequest: Sendable, Hashable {
/// HTTP request method
/// The HTTP request method
public struct Method: Hashable, RawRepresentable, LosslessStringConvertible {
/// The string value of the request.
public let rawValue: String
@@ -29,14 +29,14 @@ public struct HTTPRequest: Sendable, Hashable {
/// Create a request method from a string. Returns nil if the string contains invalid
/// characters defined in RFC 9110.
///
/// https://www.rfc-editor.org/rfc/rfc9110.html#name-overview
/// https://www.rfc-editor.org/rfc/rfc9110.html#name-methods
///
/// - Parameter method: The method string. It can be accessed from the `rawValue` property.
public init?(_ method: String) {
guard HTTPField.isValidToken(method) else {
return nil
}
rawValue = method
self.rawValue = method
}
public init?(rawValue: String) {
@@ -44,153 +44,159 @@ public struct HTTPRequest: Sendable, Hashable {
}
private init(unchecked: String) {
rawValue = unchecked
self.rawValue = unchecked
}
public var description: String {
rawValue
self.rawValue
}
}
/// The HTTP request method.
///
/// A convenient way to access the value of the ":method" pseudo header field.
public var method: Method {
get {
Method(methodField.rawValue._storage)!
Method(self.pseudoHeaderFields.method.rawValue._storage)!
}
set {
methodField.rawValue = ISOLatin1String(unchecked: newValue.rawValue)
self.pseudoHeaderFields.method.rawValue = ISOLatin1String(unchecked: newValue.rawValue)
}
}
/// The value of the ":scheme" pseudo header field.
/// A convenient way to access the value of the ":scheme" pseudo header field.
///
/// The scheme is ignored in a legacy HTTP/1 context.
public var scheme: String? {
get {
schemeField?.value
self.pseudoHeaderFields.scheme?.value
}
set {
if let newValue {
if var field = schemeField {
if var field = pseudoHeaderFields.scheme {
field.value = newValue
schemeField = field
self.pseudoHeaderFields.scheme = field
} else {
var field = HTTPField(name: .scheme, value: newValue)
field.indexingStrategy = .prefer
schemeField = field
self.pseudoHeaderFields.scheme = HTTPField(name: .scheme, value: newValue)
}
} else {
schemeField = nil
self.pseudoHeaderFields.scheme = nil
}
}
}
/// The value of the ":authority" pseudo header field.
/// A convenient way to access the value of the ":authority" pseudo header field.
///
/// The authority is translated into the "Host" header in a legacy HTTP/1 context.
public var authority: String? {
get {
authorityField?.value
self.pseudoHeaderFields.authority?.value
}
set {
if let newValue {
if var field = authorityField {
if var field = pseudoHeaderFields.authority {
field.value = newValue
authorityField = field
self.pseudoHeaderFields.authority = field
} else {
var field = HTTPField(name: .authority, value: newValue)
field.indexingStrategy = .prefer
authorityField = field
self.pseudoHeaderFields.authority = HTTPField(name: .authority, value: newValue)
}
} else {
authorityField = nil
self.pseudoHeaderFields.authority = nil
}
}
}
/// The value of the ":path" pseudo header field.
/// A convenient way to access the value of the ":path" pseudo header field.
public var path: String? {
get {
pathField?.value
self.pseudoHeaderFields.path?.value
}
set {
if let newValue {
if var field = pathField {
if var field = pseudoHeaderFields.path {
field.value = newValue
pathField = field
self.pseudoHeaderFields.path = field
} else {
pathField = HTTPField(name: .path, value: newValue)
self.pseudoHeaderFields.path = HTTPField(name: .path, value: newValue)
}
} else {
pathField = nil
self.pseudoHeaderFields.path = nil
}
}
}
/// The value of the ":protocol" pseudo header field.
/// A convenient way to access the value of the ":protocol" pseudo header field.
public var extendedConnectProtocol: String? {
get {
extendedConnectProtocolField?.value
self.pseudoHeaderFields.extendedConnectProtocol?.value
}
set {
if let newValue {
if var field = extendedConnectProtocolField {
if var field = pseudoHeaderFields.extendedConnectProtocol {
field.value = newValue
extendedConnectProtocolField = field
self.pseudoHeaderFields.extendedConnectProtocol = field
} else {
var field = HTTPField(name: .protocol, value: newValue)
field.indexingStrategy = .prefer
extendedConnectProtocolField = field
self.pseudoHeaderFields.extendedConnectProtocol = HTTPField(name: .protocol, value: newValue)
}
} else {
extendedConnectProtocolField = nil
self.pseudoHeaderFields.extendedConnectProtocol = nil
}
}
}
/// The underlying ":method" pseudo header field.
public var methodField: HTTPField {
willSet {
precondition(newValue.name == .method, "Cannot change pseudo-header field name")
precondition(HTTPField.isValidToken(newValue.rawValue._storage), "Invalid character in method field")
/// The pseudo header fields of a request.
public struct PseudoHeaderFields: Sendable, Hashable {
/// The underlying ":method" pseudo header field.
///
/// The value of this field must be a valid method.
///
/// https://www.rfc-editor.org/rfc/rfc9110.html#name-methods
public var method: HTTPField {
willSet {
precondition(newValue.name == .method, "Cannot change pseudo-header field name")
precondition(HTTPField.isValidToken(newValue.rawValue._storage), "Invalid character in method field")
}
}
}
/// The underlying ":scheme" pseudo header field.
public var schemeField: HTTPField? {
willSet {
if let name = newValue?.name {
precondition(name == .scheme, "Cannot change pseudo-header field name")
/// The underlying ":scheme" pseudo header field.
public var scheme: HTTPField? {
willSet {
if let name = newValue?.name {
precondition(name == .scheme, "Cannot change pseudo-header field name")
}
}
}
/// The underlying ":authority" pseudo header field.
public var authority: HTTPField? {
willSet {
if let name = newValue?.name {
precondition(name == .authority, "Cannot change pseudo-header field name")
}
}
}
/// The underlying ":path" pseudo header field.
public var path: HTTPField? {
willSet {
if let name = newValue?.name {
precondition(name == .path, "Cannot change pseudo-header field name")
}
}
}
/// The underlying ":protocol" pseudo header field.
public var extendedConnectProtocol: HTTPField? {
willSet {
if let name = newValue?.name {
precondition(name == .protocol, "Cannot change pseudo-header field name")
}
}
}
}
/// The underlying ":authority" pseudo header field.
public var authorityField: HTTPField? {
willSet {
if let name = newValue?.name {
precondition(name == .authority, "Cannot change pseudo-header field name")
}
}
}
/// The underlying ":path" pseudo header field.
public var pathField: HTTPField? {
willSet {
if let name = newValue?.name {
precondition(name == .path, "Cannot change pseudo-header field name")
}
}
}
/// The underlying ":protocol" pseudo header field.
public var extendedConnectProtocolField: HTTPField? {
willSet {
if let name = newValue?.name {
precondition(name == .protocol, "Cannot change pseudo-header field name")
}
}
}
/// The pseudo header fields.
public var pseudoHeaderFields: PseudoHeaderFields
/// The request header fields.
public var headerFields: HTTPFields
@@ -203,98 +209,90 @@ public struct HTTPRequest: Sendable, Hashable {
/// - path: The value of the ":path" pseudo header field.
/// - headerFields: The request header fields.
public init(method: Method, scheme: String?, authority: String?, path: String?, headerFields: HTTPFields = [:]) {
methodField = HTTPField(name: .method, uncheckedValue: ISOLatin1String(unchecked: method.rawValue))
methodField.indexingStrategy = .prefer
schemeField = scheme.map {
var field = HTTPField(name: .scheme, value: $0)
field.indexingStrategy = .prefer
return field
}
authorityField = authority.map {
var field = HTTPField(name: .authority, value: $0)
field.indexingStrategy = .prefer
return field
}
pathField = path.map { HTTPField(name: .path, value: $0) }
let methodField = HTTPField(name: .method, uncheckedValue: ISOLatin1String(unchecked: method.rawValue))
let schemeField = scheme.map { HTTPField(name: .scheme, value: $0) }
let authorityField = authority.map { HTTPField(name: .authority, value: $0) }
let pathField = path.map { HTTPField(name: .path, value: $0) }
self.pseudoHeaderFields = .init(method: methodField, scheme: schemeField, authority: authorityField, path: pathField)
self.headerFields = headerFields
}
}
extension HTTPRequest: CustomDebugStringConvertible {
public var debugDescription: String {
"(\(methodField.rawValue._storage)) \((schemeField?.value).map { "\($0)://" } ?? "")\(authorityField?.value ?? "")\(pathField?.value ?? "")"
"(\(self.pseudoHeaderFields.method.rawValue._storage)) \((self.pseudoHeaderFields.scheme?.value).map { "\($0)://" } ?? "")\(self.pseudoHeaderFields.authority?.value ?? "")\(self.pseudoHeaderFields.path?.value ?? "")"
}
}
extension HTTPRequest.Method {
/// GET
public static let get = HTTPRequest.Method(unchecked: "GET")
public static var get: Self { .init(unchecked: "GET") }
/// PUT
public static let put = HTTPRequest.Method(unchecked: "PUT")
public static var put: Self { .init(unchecked: "PUT") }
/// ACL
public static let acl = HTTPRequest.Method(unchecked: "ACL")
public static var acl: Self { .init(unchecked: "ACL") }
/// HEAD
public static let head = HTTPRequest.Method(unchecked: "HEAD")
public static var head: Self { .init(unchecked: "HEAD") }
/// POST
public static let post = HTTPRequest.Method(unchecked: "POST")
public static var post: Self { .init(unchecked: "POST") }
/// COPY
public static let copy = HTTPRequest.Method(unchecked: "COPY")
public static var copy: Self { .init(unchecked: "COPY") }
/// LOCK
public static let lock = HTTPRequest.Method(unchecked: "LOCK")
public static var lock: Self { .init(unchecked: "LOCK") }
/// MOVE
public static let move = HTTPRequest.Method(unchecked: "MOVE")
public static var move: Self { .init(unchecked: "MOVE") }
/// BIND
public static let bind = HTTPRequest.Method(unchecked: "BIND")
public static var bind: Self { .init(unchecked: "BIND") }
/// LINK
public static let link = HTTPRequest.Method(unchecked: "LINK")
public static var link: Self { .init(unchecked: "LINK") }
/// PATCH
public static let patch = HTTPRequest.Method(unchecked: "PATCH")
public static var patch: Self { .init(unchecked: "PATCH") }
/// TRACE
public static let trace = HTTPRequest.Method(unchecked: "TRACE")
public static var trace: Self { .init(unchecked: "TRACE") }
/// MKCOL
public static let mkcol = HTTPRequest.Method(unchecked: "MKCOL")
public static var mkcol: Self { .init(unchecked: "MKCOL") }
/// MERGE
public static let merge = HTTPRequest.Method(unchecked: "MERGE")
public static var merge: Self { .init(unchecked: "MERGE") }
/// PURGE
public static let purge = HTTPRequest.Method(unchecked: "PURGE")
public static var purge: Self { .init(unchecked: "PURGE") }
/// NOTIFY
public static let notify = HTTPRequest.Method(unchecked: "NOTIFY")
public static var notify: Self { .init(unchecked: "NOTIFY") }
/// SEARCH
public static let search = HTTPRequest.Method(unchecked: "SEARCH")
public static var search: Self { .init(unchecked: "SEARCH") }
/// UNLOCK
public static let unlock = HTTPRequest.Method(unchecked: "UNLOCK")
public static var unlock: Self { .init(unchecked: "UNLOCK") }
/// REBIND
public static let rebind = HTTPRequest.Method(unchecked: "REBIND")
public static var rebind: Self { .init(unchecked: "REBIND") }
/// UNBIND
public static let unbind = HTTPRequest.Method(unchecked: "UNBIND")
public static var unbind: Self { .init(unchecked: "UNBIND") }
/// REPORT
public static let report = HTTPRequest.Method(unchecked: "REPORT")
public static var report: Self { .init(unchecked: "REPORT") }
/// DELETE
public static let delete = HTTPRequest.Method(unchecked: "DELETE")
public static var delete: Self { .init(unchecked: "DELETE") }
/// UNLINK
public static let unlink = HTTPRequest.Method(unchecked: "UNLINK")
public static var unlink: Self { .init(unchecked: "UNLINK") }
/// CONNECT
public static let connect = HTTPRequest.Method(unchecked: "CONNECT")
public static var connect: Self { .init(unchecked: "CONNECT") }
/// MSEARCH
public static let msearch = HTTPRequest.Method(unchecked: "MSEARCH")
public static var msearch: Self { .init(unchecked: "MSEARCH") }
/// OPTIONS
public static let options = HTTPRequest.Method(unchecked: "OPTIONS")
public static var options: Self { .init(unchecked: "OPTIONS") }
/// PROPFIND
public static let propfind = HTTPRequest.Method(unchecked: "PROPFIND")
public static var propfind: Self { .init(unchecked: "PROPFIND") }
/// CHECKOUT
public static let checkout = HTTPRequest.Method(unchecked: "CHECKOUT")
public static var checkout: Self { .init(unchecked: "CHECKOUT") }
/// PROPPATCH
public static let proppatch = HTTPRequest.Method(unchecked: "PROPPATCH")
public static var proppatch: Self { .init(unchecked: "PROPPATCH") }
/// SUBSCRIBE
public static let subscribe = HTTPRequest.Method(unchecked: "SUBSCRIBE")
public static var subscribe: Self { .init(unchecked: "SUBSCRIBE") }
/// MKCALENDAR
public static let mkcalendar = HTTPRequest.Method(unchecked: "MKCALENDAR")
public static var mkcalendar: Self { .init(unchecked: "MKCALENDAR") }
/// MKACTIVITY
public static let mkactivity = HTTPRequest.Method(unchecked: "MKACTIVITY")
public static var mkactivity: Self { .init(unchecked: "MKACTIVITY") }
/// UNSUBSCRIBE
public static let unsubscribe = HTTPRequest.Method(unchecked: "UNSUBSCRIBE")
public static var unsubscribe: Self { .init(unchecked: "UNSUBSCRIBE") }
/// SOURCE
public static let source = HTTPRequest.Method(unchecked: "SOURCE")
public static var source: Self { .init(unchecked: "SOURCE") }
/// CONNECT-UDP
static let connectUDP = HTTPRequest.Method(unchecked: "CONNECT-UDP")
static var connectUDP: Self { .init(unchecked: "CONNECT-UDP") }
}
+98 -92
View File
@@ -1,42 +1,44 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// HTTP request message consists of the ":status" pseudo header field, an optional reason phrase,
/// and header fields.
/// An HTTP response message consisting of the ":status" pseudo header field and header fields.
///
/// Conveniences are provided to access the status code and its reason phrase.
public struct HTTPResponse: Sendable, Hashable {
/// Status consists of a 3-digit status code and a reason phrase. The reason phrase is ignored
/// by modern HTTP versions.
/// The response status consisting of a 3-digit status code and a reason phrase. The reason
/// phrase is ignored by modern HTTP versions.
public struct Status: Hashable, ExpressibleByIntegerLiteral, CustomStringConvertible {
/// The 3-digit status code.
public let code: Int
/// The optional reason phrase (ISOLatin1 encoded).
public let reasonPhrase: String?
/// The reason phrase.
///
/// ISO Latin 1 encoding should be used to serialize and deserialize this string.
public let reasonPhrase: String
/// Create a custom status from a code and a reason phrase.
/// - Parameters:
/// - code: The status code.
/// - reasonPhrase: The optional reason phrase. Invalid characters are converted into
/// whitespace characters.
public init(code: Int, reasonPhrase: String? = nil) {
precondition((0...999).contains(code), "Invalid status code")
/// - reasonPhrase: The optional reason phrase. Invalid characters, including any
/// characters not representable in ISO Latin 1 encoding, are converted
/// into space characters.
public init(code: Int, reasonPhrase: String = "") {
precondition((0 ... 999).contains(code), "Invalid status code")
self.code = code
self.reasonPhrase = reasonPhrase.map(Self.legalizingReasonPhrase)
self.reasonPhrase = Self.legalizingReasonPhrase(reasonPhrase)
}
fileprivate init(uncheckedCode: Int, reasonPhrase: String?) {
fileprivate init(uncheckedCode: Int, reasonPhrase: String) {
self.code = uncheckedCode
self.reasonPhrase = reasonPhrase
}
@@ -44,58 +46,67 @@ public struct HTTPResponse: Sendable, Hashable {
/// Create a custom status from an integer literal.
/// - Parameter value: The status code.
public init(integerLiteral value: Int) {
precondition((0...999).contains(value), "Invalid status code")
code = value
reasonPhrase = nil
precondition((0 ... 999).contains(value), "Invalid status code")
self.code = value
self.reasonPhrase = ""
}
/// The status code is informational (1xx) and the response is not final.
public var isInformational: Bool {
(100...199).contains(code)
/// The first digit of the status code defines the kind of response.
@frozen public enum Kind {
/// The status code is outside the range of 100...599.
case invalid
/// The status code is informational (1xx) and the response is not final.
case informational
/// The status code is successful (2xx).
case successful
/// The status code is a redirection (3xx).
case redirection
/// The status code is a client error (4xx).
case clientError
/// The status code is a server error (5xx).
case serverError
}
/// The status code is successful (2xx).
public var isSuccessful: Bool {
(200...299).contains(code)
}
/// The status code is a redirection (3xx).
public var isRedirection: Bool {
(300...399).contains(code)
}
/// The status code is a client error (4xx).
public var isClientError: Bool {
(400...499).contains(code)
}
/// The status code is a server error (5xx).
public var isServerError: Bool {
(500...599).contains(code)
/// The kind of the status code.
public var kind: Kind {
switch self.code {
case 100 ... 199:
return .informational
case 200 ... 299:
return .successful
case 300 ... 399:
return .redirection
case 400 ... 499:
return .clientError
case 500 ... 599:
return .serverError
default:
return .invalid
}
}
public func hash(into hasher: inout Hasher) {
hasher.combine(code)
hasher.combine(self.code)
}
public static func ==(lhs: Status, rhs: Status) -> Bool {
public static func == (lhs: Status, rhs: Status) -> Bool {
lhs.code == rhs.code
}
public var description: String {
"\(code)"
"\(self.code) \(self.reasonPhrase)"
}
var fieldValue: String {
String([
Character(Unicode.Scalar(UInt8(code / 100) + 48)),
Character(Unicode.Scalar(UInt8((code / 10) % 10) + 48)),
Character(Unicode.Scalar(UInt8(code % 10) + 48))
Character(Unicode.Scalar(UInt8(self.code / 100) + 48)),
Character(Unicode.Scalar(UInt8((self.code / 10) % 10) + 48)),
Character(Unicode.Scalar(UInt8(self.code % 10) + 48)),
])
}
static func isValidStatus(_ status: String) -> Bool {
status.count == 3 && status.utf8.allSatisfy { (0x30...0x39).contains($0) }
status.count == 3 && status.utf8.allSatisfy { (0x30 ... 0x39).contains($0) }
}
static func isValidReasonPhrase(_ reasonPhrase: String) -> Bool {
@@ -103,7 +114,7 @@ public struct HTTPResponse: Sendable, Hashable {
switch $0 {
case 0x09, 0x20:
return true
case 0x21...0x7E, 0x80...0xFF:
case 0x21 ... 0x7E, 0x80 ... 0xFF:
return true
default:
return false
@@ -119,7 +130,7 @@ public struct HTTPResponse: Sendable, Hashable {
switch scala.value {
case 0x09, 0x20:
return scala
case 0x21...0x7E, 0x80...0xFF:
case 0x21 ... 0x7E, 0x80 ... 0xFF:
return scala
default:
return " "
@@ -133,25 +144,36 @@ public struct HTTPResponse: Sendable, Hashable {
}
/// The status of the response.
///
/// A convenient way to access the value of the ":status" pseudo header field and the reason
/// phrase.
public var status: Status {
get {
Status(uncheckedCode: Int(statusField.rawValue._storage)!, reasonPhrase: reasonPhrase)
Status(uncheckedCode: Int(self.pseudoHeaderFields.status.rawValue._storage)!, reasonPhrase: self.reasonPhrase)
}
set {
statusField.rawValue = ISOLatin1String(unchecked: newValue.fieldValue)
reasonPhrase = newValue.reasonPhrase
self.pseudoHeaderFields.status.rawValue = ISOLatin1String(unchecked: newValue.fieldValue)
self.reasonPhrase = newValue.reasonPhrase
}
}
/// The underlying ":status" pseudo header field.
public var statusField: HTTPField {
willSet {
precondition(newValue.name == .status, "Cannot change pseudo-header field name")
precondition(Status.isValidStatus(newValue.rawValue._storage), "Invalid status code")
/// The pseudo header fields of a response.
public struct PseudoHeaderFields: Sendable, Hashable {
/// The underlying ":status" pseudo header field.
///
/// The value of this field must be 3 ASCII decimal digits.
public var status: HTTPField {
willSet {
precondition(newValue.name == .status, "Cannot change pseudo-header field name")
precondition(Status.isValidStatus(newValue.rawValue._storage), "Invalid status code")
}
}
}
private var reasonPhrase: String?
/// The pseudo header fields.
public var pseudoHeaderFields: PseudoHeaderFields
private var reasonPhrase: String
/// The response header fields.
public var headerFields: HTTPFields
@@ -161,39 +183,40 @@ public struct HTTPResponse: Sendable, Hashable {
/// - status: The status code and an optional reason phrase.
/// - headerFields: The response header fields.
public init(status: Status, headerFields: HTTPFields = [:]) {
statusField = HTTPField(name: .status, uncheckedValue: ISOLatin1String(unchecked: status.fieldValue))
reasonPhrase = status.reasonPhrase
let statusField = HTTPField(name: .status, uncheckedValue: ISOLatin1String(unchecked: status.fieldValue))
self.pseudoHeaderFields = .init(status: statusField)
self.reasonPhrase = status.reasonPhrase
self.headerFields = headerFields
}
public func hash(into hasher: inout Hasher) {
hasher.combine(statusField)
hasher.combine(headerFields)
hasher.combine(self.pseudoHeaderFields)
hasher.combine(self.headerFields)
}
public static func ==(lhs: HTTPResponse, rhs: HTTPResponse) -> Bool {
lhs.statusField == rhs.statusField && lhs.headerFields == lhs.headerFields
public static func == (lhs: HTTPResponse, rhs: HTTPResponse) -> Bool {
lhs.pseudoHeaderFields == rhs.pseudoHeaderFields && lhs.headerFields == lhs.headerFields
}
}
extension HTTPResponse: CustomDebugStringConvertible {
public var debugDescription: String {
"\(status)"
"\(self.status)"
}
}
extension HTTPResponse.Status {
// MARK: 1xx
/// 100 Continue
public static var `continue`: Self { .init(uncheckedCode: 100, reasonPhrase: "Continue") }
/// 101 Switching Protocols
public static var switchingProtocols: Self { .init(uncheckedCode: 101, reasonPhrase: "Switching Protocols") }
/// 102 Processing
public static var processing: Self { .init(uncheckedCode: 102, reasonPhrase: "Processing") }
/// 103 Early Hints
public static var earlyHints: Self { .init(uncheckedCode: 103, reasonPhrase: "Early Hints") }
// MARK: 2xx
/// 200 OK
public static var ok: Self { .init(uncheckedCode: 200, reasonPhrase: "OK") }
/// 201 Created
@@ -208,14 +231,9 @@ extension HTTPResponse.Status {
public static var resetContent: Self { .init(uncheckedCode: 205, reasonPhrase: "Reset Content") }
/// 206 Partial Content
public static var partialContent: Self { .init(uncheckedCode: 206, reasonPhrase: "Partial Content") }
/// 207 Multi-Status
public static var multiStatus: Self { .init(uncheckedCode: 207, reasonPhrase: "Multi-Status") }
/// 208 Already Reported
public static var alreadyReported: Self { .init(uncheckedCode: 208, reasonPhrase: "Already Reported") }
/// 226 IM Used
public static var imUsed: Self { .init(uncheckedCode: 226, reasonPhrase: "IM Used") }
// MARK: 3xx
/// 300 Multiple Choices
public static var multipleChoices: Self { .init(uncheckedCode: 300, reasonPhrase: "Multiple Choices") }
/// 301 Moved Permanently
@@ -226,20 +244,17 @@ extension HTTPResponse.Status {
public static var seeOther: Self { .init(uncheckedCode: 303, reasonPhrase: "See Other") }
/// 304 Not Modified
public static var notModified: Self { .init(uncheckedCode: 304, reasonPhrase: "Not Modified") }
/// 305 Use Proxy
public static var useProxy: Self { .init(uncheckedCode: 305, reasonPhrase: "Use Proxy") }
/// 307 Temporary Redirect
public static var temporaryRedirect: Self { .init(uncheckedCode: 307, reasonPhrase: "Temporary Redirect") }
/// 308 Permanent Redirect
public static var permanentRedirect: Self { .init(uncheckedCode: 308, reasonPhrase: "Permanent Redirect") }
// MARK: 4xx
/// 400 Bad Request
public static var badRequest: Self { .init(uncheckedCode: 400, reasonPhrase: "Bad Request") }
/// 401 Unauthorized
public static var unauthorized: Self { .init(uncheckedCode: 401, reasonPhrase: "Unauthorized") }
/// 402 Payment Required
public static var paymentRequired: Self { .init(uncheckedCode: 402, reasonPhrase: "Payment Required") }
/// 403 Forbidden
public static var forbidden: Self { .init(uncheckedCode: 403, reasonPhrase: "Forbidden") }
/// 404 Not Found
@@ -260,8 +275,8 @@ extension HTTPResponse.Status {
public static var lengthRequired: Self { .init(uncheckedCode: 411, reasonPhrase: "Length Required") }
/// 412 Precondition Failed
public static var preconditionFailed: Self { .init(uncheckedCode: 412, reasonPhrase: "Precondition Failed") }
/// 413 Payload Too Large
public static var payloadTooLarge: Self { .init(uncheckedCode: 413, reasonPhrase: "Payload Too Large") }
/// 413 Content Too Large
public static var contentTooLarge: Self { .init(uncheckedCode: 413, reasonPhrase: "Content Too Large") }
/// 414 URI Too Long
public static var uriTooLong: Self { .init(uncheckedCode: 414, reasonPhrase: "URI Too Long") }
/// 415 Unsupported Media Type
@@ -272,12 +287,10 @@ extension HTTPResponse.Status {
public static var expectationFailed: Self { .init(uncheckedCode: 417, reasonPhrase: "Expectation Failed") }
/// 421 Misdirected Request
public static var misdirectedRequest: Self { .init(uncheckedCode: 421, reasonPhrase: "Misdirected Request") }
/// 422 Unprocessable Entity
public static var unprocessableEntity: Self { .init(uncheckedCode: 422, reasonPhrase: "Unprocessable Entity") }
/// 423 Locked
public static var locked: Self { .init(uncheckedCode: 423, reasonPhrase: "Locked") }
/// 424 Failed Dependency
public static var failedDependency: Self { .init(uncheckedCode: 424, reasonPhrase: "Failed Dependency") }
/// 422 Unprocessable Content
public static var unprocessableContent: Self { .init(uncheckedCode: 422, reasonPhrase: "Unprocessable Content") }
/// 425 Too Early
public static var tooEarly: Self { .init(uncheckedCode: 425, reasonPhrase: "Too Early") }
/// 426 Upgrade Required
public static var upgradeRequired: Self { .init(uncheckedCode: 426, reasonPhrase: "Upgrade Required") }
/// 428 Precondition Required
@@ -290,6 +303,7 @@ extension HTTPResponse.Status {
public static var unavailableForLegalReasons: Self { .init(uncheckedCode: 451, reasonPhrase: "Unavailable For Legal Reasons") }
// MARK: 5xx
/// 500 Internal Server Error
public static var internalServerError: Self { .init(uncheckedCode: 500, reasonPhrase: "Internal Server Error") }
/// 501 Not Implemented
@@ -302,14 +316,6 @@ extension HTTPResponse.Status {
public static var gatewayTimeout: Self { .init(uncheckedCode: 504, reasonPhrase: "Gateway Timeout") }
/// 505 HTTP Version Not Supported
public static var httpVersionNotSupported: Self { .init(uncheckedCode: 505, reasonPhrase: "HTTP Version Not Supported") }
/// 506 Variant Also Negotiates
public static var variantAlsoNegotiates: Self { .init(uncheckedCode: 506, reasonPhrase: "Variant Also Negotiates") }
/// 507 Insufficient Storage
public static var insufficientStorage: Self { .init(uncheckedCode: 507, reasonPhrase: "Insufficient Storage") }
/// 508 Loop Detected
public static var loopDetected: Self { .init(uncheckedCode: 508, reasonPhrase: "Loop Detected") }
/// 510 Not Extended
public static var notExtended: Self { .init(uncheckedCode: 510, reasonPhrase: "Not Extended") }
/// 511 Network Authentication Required
public static var networkAuthenticationRequired: Self { .init(uncheckedCode: 511, reasonPhrase: "Network Authentication Required") }
}
+18 -18
View File
@@ -1,18 +1,18 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension StringProtocol {
extension String {
var isASCII: Bool {
utf8.allSatisfy { $0 & 0x80 == 0 }
}
@@ -29,8 +29,8 @@ struct ISOLatin1String: Sendable, Hashable {
}
private func withISOLatin1BytesSlowPath<Result>(_ body: (UnsafeBufferPointer<UInt8>) throws -> Result) rethrows -> Result {
try withUnsafeTemporaryAllocation(of: UInt8.self, capacity: _storage.unicodeScalars.count) { buffer in
for (index, scalar) in _storage.unicodeScalars.enumerated() {
try withUnsafeTemporaryAllocation(of: UInt8.self, capacity: self._storage.unicodeScalars.count) { buffer in
for (index, scalar) in self._storage.unicodeScalars.enumerated() {
assert(scalar.value <= UInt8.max)
buffer.initializeElement(at: index, to: UInt8(truncatingIfNeeded: scalar.value))
}
@@ -38,43 +38,43 @@ struct ISOLatin1String: Sendable, Hashable {
}
}
init(_ string: some StringProtocol) {
init(_ string: String) {
if string.isASCII {
_storage = String(string)
self._storage = string
} else {
_storage = Self.transcodeSlowPath(from: string.utf8)
self._storage = Self.transcodeSlowPath(from: string.utf8)
}
}
init(_ bytes: some Collection<UInt8>) {
let ascii = bytes.allSatisfy { $0 & 0x80 == 0 }
if ascii {
_storage = String(decoding: bytes, as: UTF8.self)
self._storage = String(decoding: bytes, as: UTF8.self)
} else {
_storage = Self.transcodeSlowPath(from: bytes)
self._storage = Self.transcodeSlowPath(from: bytes)
}
}
init(unchecked: String) {
_storage = unchecked
self._storage = unchecked
}
var string: String {
if _storage.isASCII {
return _storage
if self._storage.isASCII {
return self._storage
} else {
return withISOLatin1BytesSlowPath {
return self.withISOLatin1BytesSlowPath {
String(decoding: $0, as: UTF8.self)
}
}
}
func withUnsafeBytes<Result>(_ body: (UnsafeBufferPointer<UInt8>) throws -> Result) rethrows -> Result {
if _storage.isASCII {
var string = _storage
if self._storage.isASCII {
var string = self._storage
return try string.withUTF8(body)
} else {
return try withISOLatin1BytesSlowPath(body)
return try self.withISOLatin1BytesSlowPath(body)
}
}
}
@@ -1,32 +1,32 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import HTTPTypes
import Foundation
@_implementationOnly import CoreFoundation
import Foundation
import HTTPTypes
public extension HTTPRequest {
extension HTTPRequest {
/// The URL of the request synthesized from the scheme, authority, and path pseudo header
/// fields.
var url: URL? {
public var url: URL? {
get {
if let schemeField,
let authorityField,
let pathField {
return schemeField.withUnsafeValueBytes { scheme in
authorityField.withUnsafeValueBytes { authority in
pathField.withUnsafeValueBytes { path in
if let schemeField = pseudoHeaderFields.scheme,
let authorityField = pseudoHeaderFields.authority,
let pathField = pseudoHeaderFields.path {
return schemeField.withUnsafeBytesOfValue { scheme in
authorityField.withUnsafeBytesOfValue { authority in
pathField.withUnsafeBytesOfValue { path in
URL(scheme: scheme, authority: authority, path: path)
}
}
@@ -42,9 +42,9 @@ public extension HTTPRequest {
self.authority = authority.map { String(decoding: $0, as: UTF8.self) }
self.path = String(decoding: path, as: UTF8.self)
} else {
schemeField = nil
authorityField = nil
pathField = nil
pseudoHeaderFields.scheme = nil
pseudoHeaderFields.authority = nil
pseudoHeaderFields.path = nil
}
}
}
@@ -54,7 +54,7 @@ public extension HTTPRequest {
/// - method: The request method, defaults to GET.
/// - url: The URL to populate the scheme, authority, and path pseudo header fields.
/// - headerFields: The request header fields.
init(method: Method = .get, url: URL, headerFields: HTTPFields = [:]) {
public init(method: Method = .get, url: URL, headerFields: HTTPFields = [:]) {
let (scheme, authority, path) = url.httpRequestComponents
let schemeString = String(decoding: scheme, as: UTF8.self)
let authorityString = authority.map { String(decoding: $0, as: UTF8.self) }
@@ -64,8 +64,8 @@ public extension HTTPRequest {
}
}
private extension URL {
init?(scheme: some Collection<UInt8>, authority: some Collection<UInt8>, path: some Collection<UInt8>) {
extension URL {
fileprivate init?(scheme: some Collection<UInt8>, authority: some Collection<UInt8>, path: some Collection<UInt8>) {
var buffer = [UInt8]()
buffer.reserveCapacity(scheme.count + 3 + authority.count + path.count)
buffer.append(contentsOf: scheme)
@@ -82,7 +82,7 @@ private extension URL {
}
}
var httpRequestComponents: (scheme: [UInt8], authority: [UInt8]?, path: [UInt8]) {
fileprivate var httpRequestComponents: (scheme: [UInt8], authority: [UInt8]?, path: [UInt8]) {
// CFURL parser based on byte ranges does not unnecessarily percent-encode WHATWG URL
let url = unsafeBitCast(self as NSURL, to: CFURL.self)
let length = CFURLGetBytes(url, nil, 0)
@@ -92,11 +92,11 @@ private extension URL {
func unionRange(_ a: CFRange, _ b: CFRange) -> CFRange {
if a.location == kCFNotFound { return b }
if b.location == kCFNotFound { return a }
return CFRange(location: a.location, length: b.location + b.length - a.location )
return CFRange(location: a.location, length: b.location + b.length - a.location)
}
func bufferSlice(_ range: CFRange) -> some Collection<UInt8> {
buffer[range.location..<range.location + range.length]
buffer[range.location ..< range.location + range.length]
}
let schemeRange = CFURLGetByteRangeForComponent(url, .scheme, nil)
@@ -1,12 +1,12 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
@@ -42,7 +42,7 @@ extension HTTPField {
if value.isASCII {
return value
} else {
return withUnsafeValueBytes { buffer in
return withUnsafeBytesOfValue { buffer in
let scalars = buffer.lazy.map { UnicodeScalar(UInt32($0))! }
var string = ""
string.unicodeScalars.append(contentsOf: scalars)
@@ -1,12 +1,12 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
@@ -47,7 +47,8 @@ extension URLRequest {
/// Convert the `URLRequest` into an `HTTPRequest`.
public var httpRequest: HTTPRequest? {
guard let method = HTTPRequest.Method(httpMethod ?? "GET"),
let url else {
let url
else {
return nil
}
var request = HTTPRequest(method: method, url: url)
@@ -1,12 +1,12 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
@@ -40,7 +40,7 @@ extension HTTPURLResponse {
/// Convert the `HTTPURLResponse` into an `HTTPResponse`.
public var httpResponse: HTTPResponse? {
guard (0...999).contains(statusCode) else {
guard (0 ... 999).contains(statusCode) else {
return nil
}
var response = HTTPResponse(status: .init(code: statusCode))
@@ -1,12 +1,12 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
@@ -40,7 +40,7 @@ private enum HTTPTypeConversionError: Error {
case failedToConvertURLResponseToHTTPResponse
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
extension URLSession {
/// Convenience method to load data using an `HTTPRequest`; creates and resumes a `URLSessionDataTask` internally.
@@ -1,20 +1,20 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import HTTPTypes
import HTTPTypesFoundation
import XCTest
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
@@ -22,33 +22,33 @@ import FoundationNetworking
final class HTTPTypesFoundationTests: XCTestCase {
func testRequestURLParsing() {
let request1 = HTTPRequest(url: URL(string: "h://a")!)
XCTAssertEqual(request1.schemeField?.value, "h")
XCTAssertEqual(request1.authorityField?.value, "a")
XCTAssertEqual(request1.pathField?.value, "/")
XCTAssertEqual(request1.scheme, "h")
XCTAssertEqual(request1.authority, "a")
XCTAssertEqual(request1.path, "/")
XCTAssertEqual(request1.url?.absoluteString, "h://a/")
let request2 = HTTPRequest(url: URL(string: "h://a:4?")!)
XCTAssertEqual(request2.schemeField?.value, "h")
XCTAssertEqual(request2.authorityField?.value, "a:4")
XCTAssertEqual(request2.pathField?.value, "/?")
XCTAssertEqual(request2.scheme, "h")
XCTAssertEqual(request2.authority, "a:4")
XCTAssertEqual(request2.path, "/?")
XCTAssertEqual(request2.url?.absoluteString, "h://a:4/?")
let request3 = HTTPRequest(url: URL(string: "h://a/")!)
XCTAssertEqual(request3.schemeField?.value, "h")
XCTAssertEqual(request3.authorityField?.value, "a")
XCTAssertEqual(request3.pathField?.value, "/")
XCTAssertEqual(request3.scheme, "h")
XCTAssertEqual(request3.authority, "a")
XCTAssertEqual(request3.path, "/")
XCTAssertEqual(request3.url?.absoluteString, "h://a/")
let request4 = HTTPRequest(url: URL(string: "h://a/p?q#1")!)
XCTAssertEqual(request4.schemeField?.value, "h")
XCTAssertEqual(request4.authorityField?.value, "a")
XCTAssertEqual(request4.pathField?.value, "/p?q")
XCTAssertEqual(request4.scheme, "h")
XCTAssertEqual(request4.authority, "a")
XCTAssertEqual(request4.path, "/p?q")
XCTAssertEqual(request4.url?.absoluteString, "h://a/p?q")
let request5 = HTTPRequest(url: URL(string: "data:,Hello%2C%20World%21")!)
XCTAssertEqual(request5.schemeField?.value, "data")
XCTAssertNil(request5.authorityField)
XCTAssertEqual(request5.pathField?.value, "/")
XCTAssertEqual(request5.scheme, "data")
XCTAssertNil(request5.authority)
XCTAssertEqual(request5.path, "/")
XCTAssertNil(request5.url)
}
@@ -101,7 +101,7 @@ final class HTTPTypesFoundationTests: XCTestCase {
let urlResponse = HTTPURLResponse(
url: URL(string: "https://www.example.com/")!, statusCode: 204, httpVersion: nil,
headerFields: [
"X-Emoji": "😀"
"X-Emoji": "😀",
]
)!
+8 -8
View File
@@ -1,19 +1,19 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Types open source project
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
// Copyright (c) 2023 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 HTTP Types project authors
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import HTTPTypes
import XCTest
extension HTTPField.Name {
static let acceptEncodingLower = HTTPField.Name("accept-encoding")!
@@ -43,7 +43,7 @@ final class HTTPTypesTests: XCTestCase {
func testRequest() {
var request1 = HTTPRequest(method: .get, scheme: "https", authority: "www.example.com", path: "/")
request1.headerFields = [
.acceptLanguage: "en"
.acceptLanguage: "en",
]
var request2 = HTTPRequest(method: HTTPRequest.Method("GET")!, scheme: "https", authority: "www.example.com", path: "/")
request2.headerFields.append(HTTPField(name: .acceptLanguageUpper, value: "en"))
@@ -56,7 +56,7 @@ final class HTTPTypesTests: XCTestCase {
var response1 = HTTPResponse(status: 200)
response1.headerFields = [
.server: "HTTPServer/1.0",
.contentLength: "0"
.contentLength: "0",
]
var response2 = response1
@@ -64,11 +64,11 @@ final class HTTPTypesTests: XCTestCase {
response2.headerFields.append(HTTPField(name: .location, value: "https://www.example.com/new"))
XCTAssertEqual(response1.status, .ok)
XCTAssertTrue(response1.status.isSuccessful)
XCTAssertEqual(response1.status.kind, .successful)
XCTAssertEqual(response1.headerFields.count, 2)
XCTAssertEqual(response2.status, 301)
XCTAssertTrue(response2.status.isRedirection)
XCTAssertEqual(response2.status.kind, .redirection)
XCTAssertEqual(response2.headerFields.count, 3)
XCTAssertEqual(response2.headerFields[.server], "HTTPServer/1.0")
}
+4 -4
View File
@@ -1,13 +1,13 @@
#!/bin/sh
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift HTTP Types open source project
## This source file is part of the Swift open source project
##
## Copyright (c) 2023 Apple Inc. and the Swift HTTP Types project authors
## Copyright (c) 2023 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 HTTP Types project authors
## See CONTRIBUTORS.txt for the list of Swift project authors
##
## SPDX-License-Identifier: Apache-2.0
##
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift open source project
##
## Copyright (c) 2023 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
##
##===----------------------------------------------------------------------===##
swift package --disable-sandbox preview-documentation --target $1
+165
View File
@@ -0,0 +1,165 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift open source project
##
## Copyright (c) 2023 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
##
##===----------------------------------------------------------------------===##
set -eu
here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
function replace_acceptable_years() {
# this needs to replace all acceptable forms with 'YEARS'
sed -e 's/20[12][7890123]-20[12][890123]/YEARS/' -e 's/20[12][890123]/YEARS/'
}
printf "=> Checking for unacceptable language... "
# This greps for unacceptable terminology. The square bracket[s] are so that
# "git grep" doesn't find the lines that greps :).
unacceptable_terms=(
-e blacklis[t]
-e whitelis[t]
-e slav[e]
-e sanit[y]
)
# We have to exclude the code of conduct as it gives examples of unacceptable
# language.
if git grep --color=never -i "${unacceptable_terms[@]}" -- . ":(exclude)CODE_OF_CONDUCT.md" > /dev/null; then
printf "\033[0;31mUnacceptable language found.\033[0m\n"
git grep -i "${unacceptable_terms[@]}" -- . ":(exclude)CODE_OF_CONDUCT.md"
exit 1
fi
printf "\033[0;32mokay.\033[0m\n"
printf "=> Checking format... "
FIRST_OUT="$(git status --porcelain)"
swiftformat . > /dev/null 2>&1
SECOND_OUT="$(git status --porcelain)"
if [[ "$FIRST_OUT" != "$SECOND_OUT" ]]; then
printf "\033[0;31mformatting issues!\033[0m\n"
git --no-pager diff
exit 1
else
printf "\033[0;32mokay.\033[0m\n"
fi
printf "=> Checking license headers\n"
tmp=$(mktemp /tmp/.swift-http-types-soundness_XXXXXX)
for language in swift-or-c bash dtrace python; do
printf " * $language... "
declare -a matching_files
declare -a exceptions
expections=( )
matching_files=( -name '*' )
case "$language" in
swift-or-c)
exceptions=( -name Package.swift -o -name 'Package@*.swift')
matching_files=( -name '*.swift' -o -name '*.c' -o -name '*.h' )
cat > "$tmp" <<"EOF"
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) YEARS 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
//
//===----------------------------------------------------------------------===//
EOF
;;
bash)
matching_files=( -name '*.sh' )
cat > "$tmp" <<"EOF"
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift open source project
##
## Copyright (c) YEARS 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
##
##===----------------------------------------------------------------------===##
EOF
;;
python)
matching_files=( -name '*.py' )
cat > "$tmp" <<"EOF"
#!/usr/bin/env python3
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift open source project
##
## Copyright (c) YEARS 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
##
##===----------------------------------------------------------------------===##
EOF
;;
dtrace)
matching_files=( -name '*.d' )
cat > "$tmp" <<"EOF"
#!/usr/sbin/dtrace -q -s
/*===----------------------------------------------------------------------===*
*
* This source file is part of the Swift open source project
*
* Copyright (c) YEARS 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
*
*===----------------------------------------------------------------------===*/
EOF
;;
*)
echo >&2 "ERROR: unknown language '$language'"
;;
esac
expected_lines=$(cat "$tmp" | wc -l)
expected_sha=$(cat "$tmp" | shasum)
(
cd "$here/.."
find . \
\( \! -path './.build/*' -a \
\( "${matching_files[@]}" \) -a \
\( \! \( "${exceptions[@]}" \) \) \) | while read line; do
if [[ "$(cat "$line" | replace_acceptable_years | head -n $expected_lines | shasum)" != "$expected_sha" ]]; then
printf "\033[0;31mmissing headers in file '$line'!\033[0m\n"
diff -u <(cat "$line" | replace_acceptable_years | head -n $expected_lines) "$tmp"
exit 1
fi
done
printf "\033[0;32mokay.\033[0m\n"
)
done
rm "$tmp"