Skip to content

Commit 4c54209

Browse files
authored
Merge pull request #37 from guoye-zhang/status
Improve the performance of setting and parsing status code
2 parents b4af788 + 37e6cca commit 4c54209

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

Sources/HTTPTypes/HTTPResponse.swift

+19-6
Original file line numberDiff line numberDiff line change
@@ -98,11 +98,20 @@ public struct HTTPResponse: Sendable, Hashable {
9898
}
9999

100100
var fieldValue: String {
101-
String([
102-
Character(Unicode.Scalar(UInt8(self.code / 100) + 48)),
103-
Character(Unicode.Scalar(UInt8((self.code / 10) % 10) + 48)),
104-
Character(Unicode.Scalar(UInt8(self.code % 10) + 48)),
105-
])
101+
if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
102+
return String(unsafeUninitializedCapacity: 3) { buffer in
103+
buffer[0] = UInt8(self.code / 100) + 48
104+
buffer[1] = UInt8((self.code / 10) % 10) + 48
105+
buffer[2] = UInt8(self.code % 10) + 48
106+
return 3
107+
}
108+
} else {
109+
return String([
110+
Character(Unicode.Scalar(UInt8(self.code / 100) + 48)),
111+
Character(Unicode.Scalar(UInt8((self.code / 10) % 10) + 48)),
112+
Character(Unicode.Scalar(UInt8(self.code % 10) + 48)),
113+
])
114+
}
106115
}
107116

108117
static func isValidStatus(_ status: String) -> Bool {
@@ -149,7 +158,11 @@ public struct HTTPResponse: Sendable, Hashable {
149158
/// phrase.
150159
public var status: Status {
151160
get {
152-
Status(uncheckedCode: Int(self.pseudoHeaderFields.status.rawValue._storage)!, reasonPhrase: self.reasonPhrase)
161+
var codeIterator = self.pseudoHeaderFields.status.rawValue._storage.utf8.makeIterator()
162+
let code = Int(codeIterator.next()! - 48) * 100 +
163+
Int(codeIterator.next()! - 48) * 10 +
164+
Int(codeIterator.next()! - 48)
165+
return Status(uncheckedCode: code, reasonPhrase: self.reasonPhrase)
153166
}
154167
set {
155168
self.pseudoHeaderFields.status.rawValue = ISOLatin1String(unchecked: newValue.fieldValue)

0 commit comments

Comments
 (0)