Remove custom DecodingError and harden fields

This commit is contained in:
Guoye Zhang committed 2023-08-08 13:39:37 -07:00
1 parent 792abeab1f
commit e885fa315c
5 files changed
+33 -49

No files matched your search

+14 -8
View File
@@ -112,6 +112,7 @@ public struct HTTPFields: Sendable, Hashable {
}
func append(field: HTTPField) {
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
let name = field.name.canonicalName
if var index = self.index?[name] {
while true {
@@ -124,6 +125,7 @@ public struct HTTPFields: Sendable, Hashable {
self.index?[name] = UInt16(self.fields.count)
}
self.fields.append((field, .max))
precondition(self.fields.count < UInt16.max, "Too many fields")
}
}
@@ -232,8 +234,10 @@ public struct HTTPFields: Sendable, Hashable {
extension HTTPFields: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (HTTPField.Name, String)...) {
for (name, value) in elements {
precondition(!name.isPseudo, "Pseudo header field \"\(name)\" disallowed")
self._storage.append(field: HTTPField(name: name, value: value))
}
precondition(self.count < UInt16.max, "Too many fields")
}
}
@@ -271,6 +275,7 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
self._storage = self._storage.copy()
}
if newValue.name != self._storage.fields[position].0.name {
precondition(!newValue.name.isPseudo, "Pseudo header field \"\(newValue.name)\" disallowed")
self._storage.index = nil
}
self._storage.fields[position].0 = newValue
@@ -281,13 +286,18 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
if subrange.startIndex == count {
if subrange.startIndex == self.count {
for field in newElements {
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
self._storage.append(field: field)
}
} else {
self._storage.index = nil
self._storage.fields.replaceSubrange(subrange, with: newElements.lazy.map { ($0, 0) })
self._storage.fields.replaceSubrange(subrange, with: newElements.lazy.map { field in
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
return (field, 0)
})
precondition(self.count < UInt16.max, "Too many fields")
}
}
@@ -312,10 +322,6 @@ extension HTTPFields: Codable {
try container.encode(contentsOf: self)
}
private enum DecodingError: Error {
case isPseudo(String)
}
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
if let count = container.count {
@@ -323,8 +329,8 @@ extension HTTPFields: Codable {
}
while !container.isAtEnd {
let field = try container.decode(HTTPField.self)
guard !field.name.rawName.hasPrefix(":") else {
throw DecodingError.isPseudo(field.name.rawName)
guard !field.name.isPseudo else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Pseudo header field \"\(field)\" disallowed")
}
self.append(field)
}