Skip to content

Commit e6bc18a

Browse files
coenttbclaude
andcommitted
Add RFC 5322 implementation and tests
🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent f6d01dd commit e6bc18a

File tree

3 files changed

+431
-0
lines changed

3 files changed

+431
-0
lines changed
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
//
2+
// File.swift
3+
// swift-web
4+
//
5+
// Created by Coen ten Thije Boonkkamp on 26/12/2024.
6+
//
7+
8+
import Foundation
9+
10+
extension RFC_5322 {
11+
public enum Date {}
12+
}
13+
14+
extension RFC_5322.Date {
15+
// MARK: - RFC 5322 Constants
16+
/// Valid year range as specified by RFC 5322 (1900 or later)
17+
private static let validYearRange = 1900...9999
18+
19+
/// Month abbreviations as specified by RFC 5322 section 3.3
20+
/// These are protocol-mandated values and must not be localized
21+
public static let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
22+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
23+
24+
/// Day abbreviations as specified by RFC 5322 section 3.3
25+
/// These are protocol-mandated values and must not be localized
26+
public static let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
27+
28+
// MARK: - Date Formatter
29+
public static let formatter: DateFormatter = {
30+
let formatter = DateFormatter()
31+
formatter.locale = Locale(identifier: "en_US_POSIX")
32+
// Allow both with and without seconds
33+
formatter.defaultDate = nil
34+
formatter.dateFormat = "EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z"
35+
if #available(macOS 13, *) {
36+
formatter.timeZone = .gmt
37+
} else {
38+
formatter.timeZone = TimeZone(secondsFromGMT: 0)
39+
}
40+
return formatter
41+
}()
42+
43+
// Secondary formatter for when seconds are omitted
44+
private static let shortFormatter: DateFormatter = {
45+
let formatter = DateFormatter()
46+
formatter.locale = Locale(identifier: "en_US_POSIX")
47+
formatter.defaultDate = nil
48+
formatter.dateFormat = "EEE', 'dd' 'MMM' 'yyyy' 'HH:mm' 'Z"
49+
if #available(macOS 13, *) {
50+
formatter.timeZone = .gmt
51+
} else {
52+
formatter.timeZone = TimeZone(secondsFromGMT: 0)
53+
}
54+
return formatter
55+
}()
56+
57+
/// Format a `Date` into RFC5322-compliant string
58+
public static func string(from date: Foundation.Date) -> String {
59+
formatter.string(from: date)
60+
}
61+
62+
/// Parse an RFC5322-compliant string into a `Foundation.Date`
63+
public static func date(from string: String) throws -> Foundation.Date {
64+
// Try parsing with seconds first
65+
if let date = formatter.date(from: string) {
66+
if isValidDate(string, date: date) {
67+
return date
68+
}
69+
}
70+
71+
// Try parsing without seconds
72+
if let date = shortFormatter.date(from: string) {
73+
if isValidDate(string, date: date) {
74+
return date
75+
}
76+
}
77+
78+
throw DateError.invalidDate(string)
79+
}
80+
81+
// MARK: - Validation
82+
private static func isValidDate(_ dateString: String, date: Foundation.Date) -> Bool {
83+
let components = dateString.components(separatedBy: " ")
84+
guard components.count >= 6 else { return false }
85+
86+
// Validate day of week if present
87+
if let dayOfWeek = components.first?.replacingOccurrences(of: ",", with: "") {
88+
if !Self.days.contains(dayOfWeek) {
89+
return false
90+
}
91+
92+
// Verify day matches the date
93+
let calendar = Calendar(identifier: .gregorian)
94+
let weekday = calendar.component(.weekday, from: date)
95+
let expectedDay = Self.days[(weekday + 5) % 7]
96+
if dayOfWeek != expectedDay {
97+
return false
98+
}
99+
}
100+
101+
// Validate month
102+
guard let monthStr = components.dropFirst(2).first,
103+
Self.months.contains(monthStr) else {
104+
return false
105+
}
106+
107+
// Validate year
108+
guard let yearStr = components.dropFirst(3).first,
109+
let year = Int(yearStr),
110+
validYearRange.contains(year) else {
111+
return false
112+
}
113+
114+
// Validate time format
115+
let timeComponents = components[4].split(separator: ":")
116+
guard timeComponents.count >= 2,
117+
timeComponents.count <= 3,
118+
let hour = Int(timeComponents[0]),
119+
let minute = Int(timeComponents[1]),
120+
hour >= 0 && hour <= 23,
121+
minute >= 0 && minute <= 59 else {
122+
return false
123+
}
124+
125+
if timeComponents.count == 3 {
126+
guard let second = Int(timeComponents[2]),
127+
second >= 0 && second <= 60 else { // Allow for leap second
128+
return false
129+
}
130+
}
131+
132+
// Validate timezone
133+
let zone = components.last ?? ""
134+
guard zone.count == 5,
135+
zone.hasPrefix("+") || zone.hasPrefix("-"),
136+
let offset = Int(zone.dropFirst()),
137+
offset <= 9959 else {
138+
return false
139+
}
140+
141+
return true
142+
}
143+
144+
// MARK: - Error Type
145+
public enum DateError: Error {
146+
case invalidDate(String)
147+
}
148+
}
149+
150+
@available(macOS 12.0, *)
151+
extension FormatStyle where Self == Foundation.Date.FormatStyle {
152+
public static var rfc5322: RFC5322DateStyle {
153+
RFC5322DateStyle()
154+
}
155+
}
156+
157+
@available(macOS 12.0, *)
158+
public struct RFC5322DateStyle: FormatStyle {
159+
public typealias FormatInput = Foundation.Date
160+
public typealias FormatOutput = String
161+
162+
public func format(_ value: Foundation.Date) -> String {
163+
RFC_5322.Date.string(from: value)
164+
}
165+
}

0 commit comments

Comments
 (0)