Skip to content

Commit 0af3194

Browse files
jverkoeyaehlke
authored andcommitted
Add mimeName to String.Encoding.
This alternative to displayName is more suitable to the charset attribute because it emits IANA-compatible MIME types or throws an error if the String encoding has no equivalent MIME type. This is a purely additive change with no behavioral changes. Ideally the current uses of String.Encoding/displayName would be replaced with this new mimeName method in order to generate HTML attributes that are more correct. Related to #279
1 parent 32f5aea commit 0af3194

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Sources/String.swift

+46
Original file line numberDiff line numberDiff line change
@@ -215,4 +215,50 @@ extension String.Encoding {
215215
return self.description
216216
}
217217
}
218+
219+
/// Errors that are thrown when a ``String.Encoding`` fails to be represented as a MIME type.
220+
public enum EncodingMIMETypeError: Error, LocalizedError {
221+
/// There is no IANA equivalent of the provided string encoding.
222+
case noIANAEquivalent(String.Encoding)
223+
224+
/// Returns a human-readable representation of this error.
225+
public var errorDescription: String? {
226+
switch self {
227+
case .noIANAEquivalent(let encoding):
228+
return String("There is no IANA equivalent for \(encoding)")
229+
}
230+
}
231+
}
232+
233+
/// Returns the encoding as an equivalent IANA MIME name.
234+
///
235+
/// - SeeAlso: https://www.iana.org/assignments/character-sets/character-sets.xhtml
236+
/// - Throws: EncodingMIMETypeError if there is no IANA-compatible MIME name.
237+
public func mimeName() throws -> String {
238+
switch self {
239+
case .ascii: return "US-ASCII"
240+
case .nextstep: throw EncodingMIMETypeError.noIANAEquivalent(self)
241+
case .japaneseEUC: return "EUC-JP"
242+
case .utf8: return "UTF-8"
243+
case .isoLatin1: return "csISOLatin1"
244+
case .symbol: throw EncodingMIMETypeError.noIANAEquivalent(self)
245+
case .nonLossyASCII: return "US-ASCII"
246+
case .shiftJIS: return "Shift_JIS"
247+
case .isoLatin2: return "csISOLatin2"
248+
case .windowsCP1251: return "windows-1251"
249+
case .windowsCP1252: return "windows-1252"
250+
case .windowsCP1253: return "windows-1253"
251+
case .windowsCP1254: return "windows-1254"
252+
case .windowsCP1250: return "windows-1250"
253+
case .iso2022JP: return "csISO2022JP"
254+
case .macOSRoman: throw EncodingMIMETypeError.noIANAEquivalent(self)
255+
case .utf16: return "UTF-16"
256+
case .utf16BigEndian: return "UTF-16BE"
257+
case .utf16LittleEndian: return "UTF-16LE"
258+
case .utf32: return "UTF-32"
259+
case .utf32BigEndian: return "UTF-32BE"
260+
case .utf32LittleEndian: return "UTF-32LE"
261+
default: throw EncodingMIMETypeError.noIANAEquivalent(self)
262+
}
263+
}
218264
}

0 commit comments

Comments
 (0)