@@ -25,14 +25,37 @@ public protocol DateTranscoder: Sendable {
25
25
}
26
26
27
27
/// A transcoder for dates encoded as an ISO-8601 string (in RFC 3339 format).
28
- public struct ISO8601DateTranscoder : DateTranscoder {
28
+ public struct ISO8601DateTranscoder : DateTranscoder , @unchecked Sendable {
29
+
30
+ /// The lock protecting the formatter.
31
+ private let lock : NSLock
32
+
33
+ /// The underlying date formatter.
34
+ private let locked_formatter : ISO8601DateFormatter
35
+
36
+ /// Creates a new transcoder with the provided options.
37
+ /// - Parameter options: Options to override the default ones. If you provide nil here, the default options
38
+ /// are used.
39
+ public init ( options: ISO8601DateFormatter . Options ? = nil ) {
40
+ let formatter = ISO8601DateFormatter ( )
41
+ if let options { formatter. formatOptions = options }
42
+ lock = NSLock ( )
43
+ lock. name = " com.apple.swift-openapi-generator.runtime.ISO8601DateTranscoder "
44
+ locked_formatter = formatter
45
+ }
29
46
30
47
/// Creates and returns an ISO 8601 formatted string representation of the specified date.
31
- public func encode( _ date: Date ) throws -> String { ISO8601DateFormatter ( ) . string ( from: date) }
48
+ public func encode( _ date: Date ) throws -> String {
49
+ lock. lock ( )
50
+ defer { lock. unlock ( ) }
51
+ return locked_formatter. string ( from: date)
52
+ }
32
53
33
54
/// Creates and returns a date object from the specified ISO 8601 formatted string representation.
34
55
public func decode( _ dateString: String ) throws -> Date {
35
- guard let date = ISO8601DateFormatter ( ) . date ( from: dateString) else {
56
+ lock. lock ( )
57
+ defer { lock. unlock ( ) }
58
+ guard let date = locked_formatter. date ( from: dateString) else {
36
59
throw DecodingError . dataCorrupted (
37
60
. init( codingPath: [ ] , debugDescription: " Expected date string to be ISO8601-formatted. " )
38
61
)
@@ -44,6 +67,11 @@ public struct ISO8601DateTranscoder: DateTranscoder {
44
67
extension DateTranscoder where Self == ISO8601DateTranscoder {
45
68
/// A transcoder that transcodes dates as ISO-8601–formatted string (in RFC 3339 format).
46
69
public static var iso8601 : Self { ISO8601DateTranscoder ( ) }
70
+
71
+ /// A transcoder that transcodes dates as ISO-8601–formatted string (in RFC 3339 format) with fractional seconds.
72
+ public static var iso8601WithFractionalSeconds : Self {
73
+ ISO8601DateTranscoder ( options: [ . withInternetDateTime, . withFractionalSeconds] )
74
+ }
47
75
}
48
76
49
77
extension JSONEncoder . DateEncodingStrategy {
0 commit comments