mirror of
https://github.com/apple/swift-nio
synced 2026-11-27 05:04:22 +00:00
Provides a means to control the underlying header storage capacity. (#1451)
Motivation: It's not always possible to initialize `HTTPHeaders` with all the headers one needs to set. In such case, the underlying array will be expanded as and when needed upon headers being appended. `Array` provides the means to reserve capacity to optimize such use case. This PR exposes this functionality in `HTTPHeaders`. Modifications: Expose method `reserveCapacity(_ minimumCapacity: Int)` and computed variable `capacity: Int` in `HTTPHeaders` and added some tests. Result: Developers will be able to control the capacity of the underlying headers array as such: ``` var headers = HTTPHeaders() headers.reserveCapacity(5) ``` Co-authored-by: Ludovic Dewailly <ldewailly@apple.com>
This commit is contained in:
1 parent
e5298263ec
commit
fefd0c854f
3 files changed
+32
No files matched your search
@@ -476,6 +476,21 @@ public struct HTTPHeaders: CustomStringConvertible, ExpressibleByDictionaryLiter
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPHeaders {
|
||||
|
||||
/// The total number of headers that can be contained without allocating new storage.
|
||||
public var capacity: Int {
|
||||
return self.headers.capacity
|
||||
}
|
||||
|
||||
/// Reserves enough space to store the specified number of headers.
|
||||
///
|
||||
/// - Parameter minimumCapacity: The requested number of headers to store.
|
||||
public mutating func reserveCapacity(_ minimumCapacity: Int) {
|
||||
self.headers.reserveCapacity(minimumCapacity)
|
||||
}
|
||||
}
|
||||
|
||||
extension ByteBuffer {
|
||||
|
||||
/// Serializes this HTTP header block to bytes suitable for writing to the wire.
|
||||
|
||||
@@ -51,6 +51,7 @@ extension HTTPHeadersTest {
|
||||
("testWeDefaultToCloseIfDoesNotMakeSense", testWeDefaultToCloseIfDoesNotMakeSense),
|
||||
("testAddingSequenceOfPairs", testAddingSequenceOfPairs),
|
||||
("testAddingOtherHTTPHeader", testAddingOtherHTTPHeader),
|
||||
("testCapacity", testCapacity),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,4 +357,20 @@ class HTTPHeadersTest : XCTestCase {
|
||||
XCTAssertEqual(["bazzy"], fooBarHeaders["baz"])
|
||||
XCTAssertEqual(.unknown, fooBarHeaders.keepAliveState)
|
||||
}
|
||||
|
||||
func testCapacity() {
|
||||
// no headers
|
||||
var headers = HTTPHeaders()
|
||||
XCTAssertEqual(headers.capacity, 0)
|
||||
// reserve capacity
|
||||
headers.reserveCapacity(5)
|
||||
XCTAssertEqual(headers.capacity, 5)
|
||||
|
||||
// initialize with some headers
|
||||
headers = HTTPHeaders([("foo", "bar")])
|
||||
XCTAssertEqual(headers.capacity, 1)
|
||||
// reserve more capacity
|
||||
headers.reserveCapacity(4)
|
||||
XCTAssertEqual(headers.capacity, 4)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user