Skip to content

Commit

Permalink
Add a helper function for Decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
juri committed Jul 11, 2023
1 parent f790334 commit b8430c9
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Sources/Parse3339/Documentation.docc/Documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,7 @@ print(date.timeIntervalSinceReferenceDate)
### Parser output

- ``Parts``

### Codable support

- ``parseFromDecoder(_:)``
30 changes: 30 additions & 0 deletions Sources/Parse3339/Parse3339.swift
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,36 @@ public func parse(_ seq: some Sequence<UInt8>) -> Parts? {
return nil
}

// MARK: JSONDecoder support

/// Helper function for using Parse3339 with Codable types.
///
/// Use `parseFromDecoder(_:)` with a custom date decoding strategy. The mechanism depends on
/// the `TopLevelDecoder` implementation. With `JSONDecoder` you can use the `dateDecodingStrategy`
/// property with a `custom` value like this:
///
/// ```swift
/// let decoder = JSONDecoder()
/// decoder.dateDecodingStrategy = .custom(Parse3339.parseFromDecoder(_:))
/// ```
///
/// `parseFromDecoder` first decodes a `String` and then parses the string. For formats other than JSON you may get
/// better performance by using an implementation that feeds bytes to ``parse(_:)-9on3x``.
public func parseFromDecoder(_ decoder: some Decoder) throws -> Date {
let container = try decoder.singleValueContainer()
let str = try container.decode(String.self)
guard let parsed = parse(str) else {
throw DecodingError.typeMismatch(
Date.self,
DecodingError.Context(
codingPath: [],
debugDescription: "The string '\(str)' could not be parsed as a date"
)
)
}
return parsed.date
}

// MARK: - Private

private enum ZoneDirection {
Expand Down
40 changes: 40 additions & 0 deletions Tests/Parse3339Tests/Parse3339Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,46 @@ final class Parse3339Tests: XCTestCase {
}
}
}

// MARK: Decodable

func testDecodable() throws {
struct Payload: Codable {
let message: String
let date: Date
}

let dateComponents = DateComponents(
timeZone: TimeZone(identifier: "Europe/Helsinki"),
year: 2023,
month: 7,
day: 11,
hour: 8,
minute: 49,
second: 0
)
let date = Calendar(identifier: .gregorian).date(from: dateComponents)!
let payload = Payload(message: "hello world", date: date)

let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601

let json = try encoder.encode(payload)

var didCallParse = false
func wrappedParse(_ decoder: any Decoder) throws -> Date {
didCallParse = true
return try parseFromDecoder(decoder)
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom(wrappedParse(_:))
let decoded = try decoder.decode(Payload.self, from: json)

XCTAssertTrue(didCallParse)
XCTAssertEqual(decoded.message, "hello world")
XCTAssertEqual(decoded.date, date)
}
}

let isoFormatter: ISO8601DateFormatter = {
Expand Down

0 comments on commit b8430c9

Please sign in to comment.