From 43c78a4f9d0686d39f150f620d67ba0d48045a2c Mon Sep 17 00:00:00 2001 From: Guoye Zhang Date: Tue, 28 Nov 2023 18:32:11 -0800 Subject: [PATCH 1/2] Improve the performance of setting and parsing status code --- Sources/HTTPTypes/HTTPResponse.swift | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/Sources/HTTPTypes/HTTPResponse.swift b/Sources/HTTPTypes/HTTPResponse.swift index 5d5bc40..67c528f 100644 --- a/Sources/HTTPTypes/HTTPResponse.swift +++ b/Sources/HTTPTypes/HTTPResponse.swift @@ -98,11 +98,20 @@ public struct HTTPResponse: Sendable, Hashable { } var fieldValue: String { - String([ - 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)), - ]) + if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { + return String(unsafeUninitializedCapacity: 3) { buffer in + buffer[0] = UInt8(self.code / 100) + 48 + buffer[1] = UInt8((self.code / 10) % 10) + 48 + buffer[2] = UInt8(self.code % 10) + 48 + return 3 + } + } else { + return String([ + 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 { @@ -149,7 +158,11 @@ public struct HTTPResponse: Sendable, Hashable { /// phrase. public var status: Status { get { - Status(uncheckedCode: Int(self.pseudoHeaderFields.status.rawValue._storage)!, reasonPhrase: self.reasonPhrase) + var codeIterator = self.pseudoHeaderFields.status.rawValue._storage.utf8.makeIterator() + let code = (Int(codeIterator.next()! - 48) * 100 + + Int(codeIterator.next()! - 48) * 10 + + Int(codeIterator.next()! - 48)) + return Status(uncheckedCode: code, reasonPhrase: self.reasonPhrase) } set { self.pseudoHeaderFields.status.rawValue = ISOLatin1String(unchecked: newValue.fieldValue) From 37e6ccad1c644fa50bd7d639ec0dfb97b354ea75 Mon Sep 17 00:00:00 2001 From: Guoye Zhang Date: Tue, 28 Nov 2023 21:38:14 -0800 Subject: [PATCH 2/2] Fix format --- Sources/HTTPTypes/HTTPResponse.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/HTTPTypes/HTTPResponse.swift b/Sources/HTTPTypes/HTTPResponse.swift index 67c528f..863bdae 100644 --- a/Sources/HTTPTypes/HTTPResponse.swift +++ b/Sources/HTTPTypes/HTTPResponse.swift @@ -159,9 +159,9 @@ public struct HTTPResponse: Sendable, Hashable { public var status: Status { get { var codeIterator = self.pseudoHeaderFields.status.rawValue._storage.utf8.makeIterator() - let code = (Int(codeIterator.next()! - 48) * 100 + - Int(codeIterator.next()! - 48) * 10 + - Int(codeIterator.next()! - 48)) + let code = Int(codeIterator.next()! - 48) * 100 + + Int(codeIterator.next()! - 48) * 10 + + Int(codeIterator.next()! - 48) return Status(uncheckedCode: code, reasonPhrase: self.reasonPhrase) } set {