Skip to content

Commit

Permalink
Allow matching HBMediaType in switch statements (#203)
Browse files Browse the repository at this point in the history
* Allow matching HBMediaType in switch statements

* Add mediatype mismatch test
  • Loading branch information
adam-fowler authored Jul 12, 2023
1 parent aa84090 commit 5c3ac60
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
16 changes: 13 additions & 3 deletions Sources/Hummingbird/HTTP/MediaType.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,15 @@ public struct HBMediaType: Sendable, CustomStringConvertible {
/// Return if media type matches the input
public func isType(_ type: HBMediaType) -> Bool {
guard self.type == type.type,
self.subType == type.subType || type.subType == "*",
type.parameter == nil || (self.parameter?.name == type.parameter?.name && self.parameter?.value == type.parameter?.value)
self.subType == type.subType || type.subType == "*"
else {
return false
}
return true
if let parameter = type.parameter {
return parameter.name == self.parameter?.name && parameter.value == self.parameter?.value
} else {
return true
}
}

/// Get media type from a file extension
Expand Down Expand Up @@ -422,3 +425,10 @@ extension HBMediaType {
"7z": .application7z,
]
}

extension HBMediaType {
// Allow matching media types in switch statements
public static func ~= (_ lhs: Self, _ rhs: Self) -> Bool {
rhs.isType(lhs)
}
}
26 changes: 26 additions & 0 deletions Tests/HummingbirdTests/HTTPTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,32 @@ class HTTPTests: XCTestCase {
XCTAssert(HBMediaType(from: "audio/ogg")?.isType(.audioOgg) == true)
}

func testMediaTypeMatching() {
switch HBMediaType(from: "application/json; charset=utf8") {
case .some(.application), .some(.applicationJson):
break
default: XCTFail()
}
switch HBMediaType(from: "application/json") {
case .some(.application), .some(.applicationJson):
break
default: XCTFail()
}
}

func testMediaTypeMisMatching() {
switch HBMediaType.applicationJson {
case HBMediaType(from: "application/json; charset=utf8")!:
XCTFail()
default: break
}
switch HBMediaType.application {
case .applicationJson:
XCTFail()
default: break
}
}

func testMediaTypeParameters() {
let mediaType = HBMediaType(from: "application/json; charset=utf8")
XCTAssertEqual(mediaType?.parameter?.name, "charset")
Expand Down

0 comments on commit 5c3ac60

Please sign in to comment.