mirror of
https://github.com/apple/swift-http-types
synced 2026-11-22 04:30:40 +00:00
Make HTTPFields hashing consistent with equality (#143)
## Summary HTTPFields equality does not depend on the order of differently named fields. Hashing used storage order, so equal values could hash differently. This hashes each name group in relative order, then mixes those group hashes without depending on name order. The existing hash test now asserts equal hashes. Fixes #139
This commit is contained in:
1 parent
6aff14dae9
commit
dfebed0b4e
2 files changed
+15
-6
No files matched your search
@@ -319,9 +319,22 @@ extension HTTPFields: Equatable {
|
||||
|
||||
extension HTTPFields: Hashable {
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
// Equality ignores the order of differently named fields, so hashing
|
||||
// must too. Combine each name's sequence (order of same-named fields
|
||||
// still matters), then mix those group hashes commutatively.
|
||||
var grouped = [String: Hasher]()
|
||||
grouped.reserveCapacity(self._fields.count)
|
||||
for field in self._fields {
|
||||
hasher.combine(field)
|
||||
let key = field.name.canonicalName
|
||||
grouped[key, default: Hasher()].combine(field)
|
||||
}
|
||||
var combined = 0
|
||||
for nameHasher in grouped.values {
|
||||
// HTTPField already hashes its name, so XOR the per-name sequence hashes directly.
|
||||
combined ^= nameHasher.finalize()
|
||||
}
|
||||
hasher.combine(combined)
|
||||
hasher.combine(self._fields.count)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -279,11 +279,7 @@ extension HTTPField.Name {
|
||||
.acceptEncoding: "gzip",
|
||||
]
|
||||
#expect(fields1 == fields2)
|
||||
|
||||
// Equal values must therefore hash equally.
|
||||
withKnownIssue("HTTPFields.hash(into:) is order sensitive while == is not") {
|
||||
#expect(fields1.hashValue == fields2.hashValue)
|
||||
}
|
||||
#expect(fields1.hashValue == fields2.hashValue)
|
||||
}
|
||||
|
||||
@Test func sendable() {
|
||||
|
||||
Reference in new issue
Block a user