Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NativeTimestampParser.swift

51 lines2.4 KB

1import Foundation
2​
3@MainActor
4enum NativeTimestampParser {
5 private static let fractionalStyle = Date.ISO8601FormatStyle(includingFractionalSeconds: true)
6 private static let wholeSecondStyle = Date.ISO8601FormatStyle()
7 private static let fractionalFormatter: ISO8601DateFormatter = {
8 let formatter = ISO8601DateFormatter()
9 formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
10 return formatter
11 }()
12 private static let wholeSecondFormatter = ISO8601DateFormatter()
13​
14 static func parse(_ value: String) -> Date? {
15 if isStandardServerTimestamp(value) {
16 let style = value.utf8.count == 24 ? fractionalStyle : wholeSecondStyle
17 if let parsed = try? style.parse(value) {
18 // Match the existing formatter's millisecond date values.
19 return Date(timeIntervalSince1970: (parsed.timeIntervalSince1970 * 1_000).rounded() / 1_000)
20 }
21 }
22 return fractionalFormatter.date(from: value) ?? wholeSecondFormatter.date(from: value)
23 }
24​
25 /// The modern parser accepts invalid clock values and keeps extra fractional
26 /// precision. Use it only for normal UTC server timestamps.
27 private static func isStandardServerTimestamp(_ value: String) -> Bool {
28 value.utf8.withContiguousStorageIfAvailable { bytes in
29 guard bytes.count == 20 || bytes.count == 24 else { return false }
30 for index in bytes.indices {
31 let byte = bytes[index]
32 switch index {
33 case 4, 7:
34 guard byte == UInt8(ascii: "-") else { return false }
35 case 10:
36 guard byte == UInt8(ascii: "T") else { return false }
37 case 13, 16:
38 guard byte == UInt8(ascii: ":") else { return false }
39 case 19:
40 guard byte == (bytes.count == 20 ? UInt8(ascii: "Z") : UInt8(ascii: ".")) else { return false }
41 case 23:
42 guard byte == UInt8(ascii: "Z") else { return false }
43 default:
44 guard (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(byte) else { return false }
45 }
46 }
47 let hour = (bytes[11] - UInt8(ascii: "0")) * 10 + bytes[12] - UInt8(ascii: "0")
48 return hour < 24 && bytes[14] <= UInt8(ascii: "5") && bytes[17] <= UInt8(ascii: "5")
49 } ?? false
50 }