URLEncodedFormEncoder.swift 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. //
  2. // URLEncodedFormEncoder.swift
  3. //
  4. // Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// An object that encodes instances into URL-encoded query strings.
  26. ///
  27. /// `ArrayEncoding` can be used to configure how `Array` values are encoded. By default, the `.brackets` encoding is
  28. /// used, encoding array values with brackets for each value. e.g `array[]=1&array[]=2`.
  29. ///
  30. /// `BoolEncoding` can be used to configure how `Bool` values are encoded. By default, the `.numeric` encoding is used,
  31. /// encoding `true` as `1` and `false` as `0`.
  32. ///
  33. /// `DataEncoding` can be used to configure how `Data` values are encoded. By default, the `.deferredToData` encoding is
  34. /// used, which encodes `Data` values using their default `Encodable` implementation.
  35. ///
  36. /// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate`
  37. /// encoding is used, which encodes `Date`s using their default `Encodable` implementation.
  38. ///
  39. /// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used,
  40. /// which encodes the keys directly from the `Encodable` implementation.
  41. ///
  42. /// `KeyPathEncoding` can be used to configure how paths within nested objects are encoded. By default, the `.brackets`
  43. /// encoding is used, which encodes each sub-key in brackets. e.g. `parent[child][grandchild]=value`.
  44. ///
  45. /// `NilEncoding` can be used to configure how `nil` `Optional` values are encoded. By default, the `.dropKey` encoding
  46. /// is used, which drops `nil` key / value pairs from the output entirely.
  47. ///
  48. /// `SpaceEncoding` can be used to configure how spaces are encoded. By default, the `.percentEscaped` encoding is used,
  49. /// replacing spaces with `%20`.
  50. ///
  51. /// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project.
  52. public final class URLEncodedFormEncoder {
  53. /// Encoding to use for `Array` values.
  54. public enum ArrayEncoding {
  55. /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding.
  56. case brackets
  57. /// No brackets are appended to the key and the key is encoded as is.
  58. case noBrackets
  59. /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior.
  60. case indexInBrackets
  61. /// Provide a custom array key encoding with the given closure.
  62. case custom((_ key: String, _ index: Int) -> String)
  63. /// Encodes the key according to the encoding.
  64. ///
  65. /// - Parameters:
  66. /// - key: The `key` to encode.
  67. /// - index: When this enum instance is `.indexInBrackets`, the `index` to encode.
  68. ///
  69. /// - Returns: The encoded key.
  70. func encode(_ key: String, atIndex index: Int) -> String {
  71. switch self {
  72. case .brackets: return "\(key)[]"
  73. case .noBrackets: return key
  74. case .indexInBrackets: return "\(key)[\(index)]"
  75. case let .custom(encoding): return encoding(key, index)
  76. }
  77. }
  78. }
  79. /// Encoding to use for `Bool` values.
  80. public enum BoolEncoding {
  81. /// Encodes `true` as `1`, `false` as `0`.
  82. case numeric
  83. /// Encodes `true` as "true", `false` as "false". This is the default encoding.
  84. case literal
  85. /// Encodes the given `Bool` as a `String`.
  86. ///
  87. /// - Parameter value: The `Bool` to encode.
  88. ///
  89. /// - Returns: The encoded `String`.
  90. func encode(_ value: Bool) -> String {
  91. switch self {
  92. case .numeric: return value ? "1" : "0"
  93. case .literal: return value ? "true" : "false"
  94. }
  95. }
  96. }
  97. /// Encoding to use for `Data` values.
  98. public enum DataEncoding {
  99. /// Defers encoding to the `Data` type.
  100. case deferredToData
  101. /// Encodes `Data` as a Base64-encoded string. This is the default encoding.
  102. case base64
  103. /// Encode the `Data` as a custom value encoded by the given closure.
  104. case custom((Data) throws -> String)
  105. /// Encodes `Data` according to the encoding.
  106. ///
  107. /// - Parameter data: The `Data` to encode.
  108. ///
  109. /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its
  110. /// `Encodable` implementation.
  111. func encode(_ data: Data) throws -> String? {
  112. switch self {
  113. case .deferredToData: return nil
  114. case .base64: return data.base64EncodedString()
  115. case let .custom(encoding): return try encoding(data)
  116. }
  117. }
  118. }
  119. /// Encoding to use for `Date` values.
  120. public enum DateEncoding {
  121. /// ISO8601 and RFC3339 formatter.
  122. private static let iso8601Formatter: ISO8601DateFormatter = {
  123. let formatter = ISO8601DateFormatter()
  124. formatter.formatOptions = .withInternetDateTime
  125. return formatter
  126. }()
  127. /// Defers encoding to the `Date` type. This is the default encoding.
  128. case deferredToDate
  129. /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970.
  130. case secondsSince1970
  131. /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970.
  132. case millisecondsSince1970
  133. /// Encodes `Date`s according to the ISO8601 and RFC3339 standards.
  134. case iso8601
  135. /// Encodes `Date`s using the given `DateFormatter`.
  136. case formatted(DateFormatter)
  137. /// Encodes `Date`s using the given closure.
  138. case custom((Date) throws -> String)
  139. /// Encodes the date according to the encoding.
  140. ///
  141. /// - Parameter date: The `Date` to encode.
  142. ///
  143. /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its
  144. /// `Encodable` implementation.
  145. func encode(_ date: Date) throws -> String? {
  146. switch self {
  147. case .deferredToDate:
  148. return nil
  149. case .secondsSince1970:
  150. return String(date.timeIntervalSince1970)
  151. case .millisecondsSince1970:
  152. return String(date.timeIntervalSince1970 * 1000.0)
  153. case .iso8601:
  154. return DateEncoding.iso8601Formatter.string(from: date)
  155. case let .formatted(formatter):
  156. return formatter.string(from: date)
  157. case let .custom(closure):
  158. return try closure(date)
  159. }
  160. }
  161. }
  162. /// Encoding to use for keys.
  163. ///
  164. /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128)
  165. /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102).
  166. public enum KeyEncoding {
  167. /// Use the keys specified by each type. This is the default encoding.
  168. case useDefaultKeys
  169. /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key.
  170. ///
  171. /// Capital characters are determined by testing membership in
  172. /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters`
  173. /// (Unicode General Categories Lu and Lt).
  174. /// The conversion to lower case uses `Locale.system`, also known as
  175. /// the ICU "root" locale. This means the result is consistent
  176. /// regardless of the current user's locale and language preferences.
  177. ///
  178. /// Converting from camel case to snake case:
  179. /// 1. Splits words at the boundary of lower-case to upper-case
  180. /// 2. Inserts `_` between words
  181. /// 3. Lowercases the entire string
  182. /// 4. Preserves starting and ending `_`.
  183. ///
  184. /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.
  185. ///
  186. /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.
  187. case convertToSnakeCase
  188. /// Same as convertToSnakeCase, but using `-` instead of `_`.
  189. /// For example `oneTwoThree` becomes `one-two-three`.
  190. case convertToKebabCase
  191. /// Capitalize the first letter only.
  192. /// For example `oneTwoThree` becomes `OneTwoThree`.
  193. case capitalized
  194. /// Uppercase all letters.
  195. /// For example `oneTwoThree` becomes `ONETWOTHREE`.
  196. case uppercased
  197. /// Lowercase all letters.
  198. /// For example `oneTwoThree` becomes `onetwothree`.
  199. case lowercased
  200. /// A custom encoding using the provided closure.
  201. case custom((String) -> String)
  202. func encode(_ key: String) -> String {
  203. switch self {
  204. case .useDefaultKeys: return key
  205. case .convertToSnakeCase: return convertToSnakeCase(key)
  206. case .convertToKebabCase: return convertToKebabCase(key)
  207. case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst())
  208. case .uppercased: return key.uppercased()
  209. case .lowercased: return key.lowercased()
  210. case let .custom(encoding): return encoding(key)
  211. }
  212. }
  213. private func convertToSnakeCase(_ key: String) -> String {
  214. convert(key, usingSeparator: "_")
  215. }
  216. private func convertToKebabCase(_ key: String) -> String {
  217. convert(key, usingSeparator: "-")
  218. }
  219. private func convert(_ key: String, usingSeparator separator: String) -> String {
  220. guard !key.isEmpty else { return key }
  221. var words: [Range<String.Index>] = []
  222. // The general idea of this algorithm is to split words on
  223. // transition from lower to upper case, then on transition of >1
  224. // upper case characters to lowercase
  225. //
  226. // myProperty -> my_property
  227. // myURLProperty -> my_url_property
  228. //
  229. // It is assumed, per Swift naming conventions, that the first character of the key is lowercase.
  230. var wordStart = key.startIndex
  231. var searchRange = key.index(after: wordStart)..<key.endIndex
  232. // Find next uppercase character
  233. while let upperCaseRange = key.rangeOfCharacter(from: .uppercaseLetters, options: [], range: searchRange) {
  234. let untilUpperCase = wordStart..<upperCaseRange.lowerBound
  235. words.append(untilUpperCase)
  236. // Find next lowercase character
  237. searchRange = upperCaseRange.lowerBound..<searchRange.upperBound
  238. guard let lowerCaseRange = key.rangeOfCharacter(from: .lowercaseLetters, options: [], range: searchRange) else {
  239. // There are no more lower case letters. Just end here.
  240. wordStart = searchRange.lowerBound
  241. break
  242. }
  243. // Is the next lowercase letter more than 1 after the uppercase?
  244. // If so, we encountered a group of uppercase letters that we
  245. // should treat as its own word
  246. let nextCharacterAfterCapital = key.index(after: upperCaseRange.lowerBound)
  247. if lowerCaseRange.lowerBound == nextCharacterAfterCapital {
  248. // The next character after capital is a lower case character and therefore not a word boundary.
  249. // Continue searching for the next upper case for the boundary.
  250. wordStart = upperCaseRange.lowerBound
  251. } else {
  252. // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before
  253. // the lower case character.
  254. let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound)
  255. words.append(upperCaseRange.lowerBound..<beforeLowerIndex)
  256. // Next word starts at the capital before the lowercase we just found
  257. wordStart = beforeLowerIndex
  258. }
  259. searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
  260. }
  261. words.append(wordStart..<searchRange.upperBound)
  262. let result = words.map { range in
  263. key[range].lowercased()
  264. }.joined(separator: separator)
  265. return result
  266. }
  267. }
  268. /// Encoding to use for nested object and `Encodable` value key paths.
  269. ///
  270. /// ```
  271. /// ["parent" : ["child" : ["grandchild": "value"]]]
  272. /// ```
  273. ///
  274. /// This encoding affects how the `parent`, `child`, `grandchild` path is encoded. Brackets are used by default.
  275. /// e.g. `parent[child][grandchild]=value`.
  276. public struct KeyPathEncoding {
  277. /// Encodes key paths by wrapping each component in brackets. e.g. `parent[child][grandchild]`.
  278. public static let brackets = KeyPathEncoding { "[\($0)]" }
  279. /// Encodes key paths by separating each component with dots. e.g. `parent.child.grandchild`.
  280. public static let dots = KeyPathEncoding { ".\($0)" }
  281. private let encoding: (_ subkey: String) -> String
  282. /// Creates an instance with the encoding closure called for each sub-key in a key path.
  283. ///
  284. /// - Parameter encoding: Closure used to perform the encoding.
  285. public init(encoding: @escaping (_ subkey: String) -> String) {
  286. self.encoding = encoding
  287. }
  288. func encodeKeyPath(_ keyPath: String) -> String {
  289. encoding(keyPath)
  290. }
  291. }
  292. /// Encoding to use for `nil` values.
  293. public struct NilEncoding {
  294. /// Encodes `nil` by dropping the entire key / value pair.
  295. public static let dropKey = NilEncoding { nil }
  296. /// Encodes `nil` by dropping only the value. e.g. `value1=one&nilValue=&value2=two`.
  297. public static let dropValue = NilEncoding { "" }
  298. /// Encodes `nil` as `null`.
  299. public static let null = NilEncoding { "null" }
  300. private let encoding: () -> String?
  301. /// Creates an instance with the encoding closure called for `nil` values.
  302. ///
  303. /// - Parameter encoding: Closure used to perform the encoding.
  304. public init(encoding: @escaping () -> String?) {
  305. self.encoding = encoding
  306. }
  307. func encodeNil() -> String? {
  308. encoding()
  309. }
  310. }
  311. /// Encoding to use for spaces.
  312. public enum SpaceEncoding {
  313. /// Encodes spaces using percent escaping (`%20`).
  314. case percentEscaped
  315. /// Encodes spaces as `+`.
  316. case plusReplaced
  317. /// Encodes the string according to the encoding.
  318. ///
  319. /// - Parameter string: The `String` to encode.
  320. ///
  321. /// - Returns: The encoded `String`.
  322. func encode(_ string: String) -> String {
  323. switch self {
  324. case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20")
  325. case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+")
  326. }
  327. }
  328. }
  329. /// `URLEncodedFormEncoder` error.
  330. public enum Error: Swift.Error {
  331. /// An invalid root object was created by the encoder. Only keyed values are valid.
  332. case invalidRootObject(String)
  333. var localizedDescription: String {
  334. switch self {
  335. case let .invalidRootObject(object):
  336. return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead."
  337. }
  338. }
  339. }
  340. /// Whether or not to sort the encoded key value pairs.
  341. ///
  342. /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`,
  343. /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to
  344. /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order.
  345. public let alphabetizeKeyValuePairs: Bool
  346. /// The `ArrayEncoding` to use.
  347. public let arrayEncoding: ArrayEncoding
  348. /// The `BoolEncoding` to use.
  349. public let boolEncoding: BoolEncoding
  350. /// THe `DataEncoding` to use.
  351. public let dataEncoding: DataEncoding
  352. /// The `DateEncoding` to use.
  353. public let dateEncoding: DateEncoding
  354. /// The `KeyEncoding` to use.
  355. public let keyEncoding: KeyEncoding
  356. /// The `KeyPathEncoding` to use.
  357. public let keyPathEncoding: KeyPathEncoding
  358. /// The `NilEncoding` to use.
  359. public let nilEncoding: NilEncoding
  360. /// The `SpaceEncoding` to use.
  361. public let spaceEncoding: SpaceEncoding
  362. /// The `CharacterSet` of allowed (non-escaped) characters.
  363. public var allowedCharacters: CharacterSet
  364. /// Creates an instance from the supplied parameters.
  365. ///
  366. /// - Parameters:
  367. /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default.
  368. /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default.
  369. /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default.
  370. /// - dataEncoding: The `DataEncoding` to use. `.base64` by default.
  371. /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default.
  372. /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default.
  373. /// - nilEncoding: The `NilEncoding` to use. `.drop` by default.
  374. /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default.
  375. /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by
  376. /// default.
  377. public init(alphabetizeKeyValuePairs: Bool = true,
  378. arrayEncoding: ArrayEncoding = .brackets,
  379. boolEncoding: BoolEncoding = .numeric,
  380. dataEncoding: DataEncoding = .base64,
  381. dateEncoding: DateEncoding = .deferredToDate,
  382. keyEncoding: KeyEncoding = .useDefaultKeys,
  383. keyPathEncoding: KeyPathEncoding = .brackets,
  384. nilEncoding: NilEncoding = .dropKey,
  385. spaceEncoding: SpaceEncoding = .percentEscaped,
  386. allowedCharacters: CharacterSet = .afURLQueryAllowed) {
  387. self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs
  388. self.arrayEncoding = arrayEncoding
  389. self.boolEncoding = boolEncoding
  390. self.dataEncoding = dataEncoding
  391. self.dateEncoding = dateEncoding
  392. self.keyEncoding = keyEncoding
  393. self.keyPathEncoding = keyPathEncoding
  394. self.nilEncoding = nilEncoding
  395. self.spaceEncoding = spaceEncoding
  396. self.allowedCharacters = allowedCharacters
  397. }
  398. func encode(_ value: Encodable) throws -> URLEncodedFormComponent {
  399. let context = URLEncodedFormContext(.object([]))
  400. let encoder = _URLEncodedFormEncoder(context: context,
  401. boolEncoding: boolEncoding,
  402. dataEncoding: dataEncoding,
  403. dateEncoding: dateEncoding,
  404. nilEncoding: nilEncoding)
  405. try value.encode(to: encoder)
  406. return context.component
  407. }
  408. /// Encodes the `value` as a URL form encoded `String`.
  409. ///
  410. /// - Parameter value: The `Encodable` value.`
  411. ///
  412. /// - Returns: The encoded `String`.
  413. /// - Throws: An `Error` or `EncodingError` instance if encoding fails.
  414. public func encode(_ value: Encodable) throws -> String {
  415. let component: URLEncodedFormComponent = try encode(value)
  416. guard case let .object(object) = component else {
  417. throw Error.invalidRootObject("\(component)")
  418. }
  419. let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs,
  420. arrayEncoding: arrayEncoding,
  421. keyEncoding: keyEncoding,
  422. keyPathEncoding: keyPathEncoding,
  423. spaceEncoding: spaceEncoding,
  424. allowedCharacters: allowedCharacters)
  425. let query = serializer.serialize(object)
  426. return query
  427. }
  428. /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the
  429. /// `.utf8` data.
  430. ///
  431. /// - Parameter value: The `Encodable` value.
  432. ///
  433. /// - Returns: The encoded `Data`.
  434. ///
  435. /// - Throws: An `Error` or `EncodingError` instance if encoding fails.
  436. public func encode(_ value: Encodable) throws -> Data {
  437. let string: String = try encode(value)
  438. return Data(string.utf8)
  439. }
  440. }
  441. final class _URLEncodedFormEncoder {
  442. var codingPath: [CodingKey]
  443. // Returns an empty dictionary, as this encoder doesn't support userInfo.
  444. var userInfo: [CodingUserInfoKey: Any] { [:] }
  445. let context: URLEncodedFormContext
  446. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  447. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  448. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  449. private let nilEncoding: URLEncodedFormEncoder.NilEncoding
  450. init(context: URLEncodedFormContext,
  451. codingPath: [CodingKey] = [],
  452. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  453. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  454. dateEncoding: URLEncodedFormEncoder.DateEncoding,
  455. nilEncoding: URLEncodedFormEncoder.NilEncoding) {
  456. self.context = context
  457. self.codingPath = codingPath
  458. self.boolEncoding = boolEncoding
  459. self.dataEncoding = dataEncoding
  460. self.dateEncoding = dateEncoding
  461. self.nilEncoding = nilEncoding
  462. }
  463. }
  464. extension _URLEncodedFormEncoder: Encoder {
  465. func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
  466. let container = _URLEncodedFormEncoder.KeyedContainer<Key>(context: context,
  467. codingPath: codingPath,
  468. boolEncoding: boolEncoding,
  469. dataEncoding: dataEncoding,
  470. dateEncoding: dateEncoding,
  471. nilEncoding: nilEncoding)
  472. return KeyedEncodingContainer(container)
  473. }
  474. func unkeyedContainer() -> UnkeyedEncodingContainer {
  475. _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  476. codingPath: codingPath,
  477. boolEncoding: boolEncoding,
  478. dataEncoding: dataEncoding,
  479. dateEncoding: dateEncoding,
  480. nilEncoding: nilEncoding)
  481. }
  482. func singleValueContainer() -> SingleValueEncodingContainer {
  483. _URLEncodedFormEncoder.SingleValueContainer(context: context,
  484. codingPath: codingPath,
  485. boolEncoding: boolEncoding,
  486. dataEncoding: dataEncoding,
  487. dateEncoding: dateEncoding,
  488. nilEncoding: nilEncoding)
  489. }
  490. }
  491. final class URLEncodedFormContext {
  492. var component: URLEncodedFormComponent
  493. init(_ component: URLEncodedFormComponent) {
  494. self.component = component
  495. }
  496. }
  497. enum URLEncodedFormComponent {
  498. typealias Object = [(key: String, value: URLEncodedFormComponent)]
  499. case string(String)
  500. case array([URLEncodedFormComponent])
  501. case object(Object)
  502. /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible.
  503. var array: [URLEncodedFormComponent]? {
  504. switch self {
  505. case let .array(array): return array
  506. default: return nil
  507. }
  508. }
  509. /// Converts self to an `Object` or returns `nil` if not convertible.
  510. var object: Object? {
  511. switch self {
  512. case let .object(object): return object
  513. default: return nil
  514. }
  515. }
  516. /// Sets self to the supplied value at a given path.
  517. ///
  518. /// data.set(to: "hello", at: ["path", "to", "value"])
  519. ///
  520. /// - parameters:
  521. /// - value: Value of `Self` to set at the supplied path.
  522. /// - path: `CodingKey` path to update with the supplied value.
  523. public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) {
  524. set(&self, to: value, at: path)
  525. }
  526. /// Recursive backing method to `set(to:at:)`.
  527. private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) {
  528. guard !path.isEmpty else {
  529. context = value
  530. return
  531. }
  532. let end = path[0]
  533. var child: URLEncodedFormComponent
  534. switch path.count {
  535. case 1:
  536. child = value
  537. case 2...:
  538. if let index = end.intValue {
  539. let array = context.array ?? []
  540. if array.count > index {
  541. child = array[index]
  542. } else {
  543. child = .array([])
  544. }
  545. set(&child, to: value, at: Array(path[1...]))
  546. } else {
  547. child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init())
  548. set(&child, to: value, at: Array(path[1...]))
  549. }
  550. default: fatalError("Unreachable")
  551. }
  552. if let index = end.intValue {
  553. if var array = context.array {
  554. if array.count > index {
  555. array[index] = child
  556. } else {
  557. array.append(child)
  558. }
  559. context = .array(array)
  560. } else {
  561. context = .array([child])
  562. }
  563. } else {
  564. if var object = context.object {
  565. if let index = object.firstIndex(where: { $0.key == end.stringValue }) {
  566. object[index] = (key: end.stringValue, value: child)
  567. } else {
  568. object.append((key: end.stringValue, value: child))
  569. }
  570. context = .object(object)
  571. } else {
  572. context = .object([(key: end.stringValue, value: child)])
  573. }
  574. }
  575. }
  576. }
  577. struct AnyCodingKey: CodingKey, Hashable {
  578. let stringValue: String
  579. let intValue: Int?
  580. init?(stringValue: String) {
  581. self.stringValue = stringValue
  582. intValue = nil
  583. }
  584. init?(intValue: Int) {
  585. stringValue = "\(intValue)"
  586. self.intValue = intValue
  587. }
  588. init<Key>(_ base: Key) where Key: CodingKey {
  589. if let intValue = base.intValue {
  590. self.init(intValue: intValue)!
  591. } else {
  592. self.init(stringValue: base.stringValue)!
  593. }
  594. }
  595. }
  596. extension _URLEncodedFormEncoder {
  597. final class KeyedContainer<Key> where Key: CodingKey {
  598. var codingPath: [CodingKey]
  599. private let context: URLEncodedFormContext
  600. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  601. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  602. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  603. private let nilEncoding: URLEncodedFormEncoder.NilEncoding
  604. init(context: URLEncodedFormContext,
  605. codingPath: [CodingKey],
  606. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  607. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  608. dateEncoding: URLEncodedFormEncoder.DateEncoding,
  609. nilEncoding: URLEncodedFormEncoder.NilEncoding) {
  610. self.context = context
  611. self.codingPath = codingPath
  612. self.boolEncoding = boolEncoding
  613. self.dataEncoding = dataEncoding
  614. self.dateEncoding = dateEncoding
  615. self.nilEncoding = nilEncoding
  616. }
  617. private func nestedCodingPath(for key: CodingKey) -> [CodingKey] {
  618. codingPath + [key]
  619. }
  620. }
  621. }
  622. extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol {
  623. func encodeNil(forKey key: Key) throws {
  624. guard let nilValue = nilEncoding.encodeNil() else { return }
  625. try encode(nilValue, forKey: key)
  626. }
  627. func encodeIfPresent(_ value: Bool?, forKey key: Key) throws {
  628. try _encodeIfPresent(value, forKey: key)
  629. }
  630. func encodeIfPresent(_ value: String?, forKey key: Key) throws {
  631. try _encodeIfPresent(value, forKey: key)
  632. }
  633. func encodeIfPresent(_ value: Double?, forKey key: Key) throws {
  634. try _encodeIfPresent(value, forKey: key)
  635. }
  636. func encodeIfPresent(_ value: Float?, forKey key: Key) throws {
  637. try _encodeIfPresent(value, forKey: key)
  638. }
  639. func encodeIfPresent(_ value: Int?, forKey key: Key) throws {
  640. try _encodeIfPresent(value, forKey: key)
  641. }
  642. func encodeIfPresent(_ value: Int8?, forKey key: Key) throws {
  643. try _encodeIfPresent(value, forKey: key)
  644. }
  645. func encodeIfPresent(_ value: Int16?, forKey key: Key) throws {
  646. try _encodeIfPresent(value, forKey: key)
  647. }
  648. func encodeIfPresent(_ value: Int32?, forKey key: Key) throws {
  649. try _encodeIfPresent(value, forKey: key)
  650. }
  651. func encodeIfPresent(_ value: Int64?, forKey key: Key) throws {
  652. try _encodeIfPresent(value, forKey: key)
  653. }
  654. func encodeIfPresent(_ value: UInt?, forKey key: Key) throws {
  655. try _encodeIfPresent(value, forKey: key)
  656. }
  657. func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws {
  658. try _encodeIfPresent(value, forKey: key)
  659. }
  660. func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws {
  661. try _encodeIfPresent(value, forKey: key)
  662. }
  663. func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws {
  664. try _encodeIfPresent(value, forKey: key)
  665. }
  666. func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws {
  667. try _encodeIfPresent(value, forKey: key)
  668. }
  669. func encodeIfPresent<Value>(_ value: Value?, forKey key: Key) throws where Value: Encodable {
  670. try _encodeIfPresent(value, forKey: key)
  671. }
  672. func _encodeIfPresent<Value>(_ value: Value?, forKey key: Key) throws where Value: Encodable {
  673. if let value = value {
  674. try encode(value, forKey: key)
  675. } else {
  676. try encodeNil(forKey: key)
  677. }
  678. }
  679. func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable {
  680. var container = nestedSingleValueEncoder(for: key)
  681. try container.encode(value)
  682. }
  683. func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer {
  684. let container = _URLEncodedFormEncoder.SingleValueContainer(context: context,
  685. codingPath: nestedCodingPath(for: key),
  686. boolEncoding: boolEncoding,
  687. dataEncoding: dataEncoding,
  688. dateEncoding: dateEncoding,
  689. nilEncoding: nilEncoding)
  690. return container
  691. }
  692. func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
  693. let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  694. codingPath: nestedCodingPath(for: key),
  695. boolEncoding: boolEncoding,
  696. dataEncoding: dataEncoding,
  697. dateEncoding: dateEncoding,
  698. nilEncoding: nilEncoding)
  699. return container
  700. }
  701. func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
  702. let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
  703. codingPath: nestedCodingPath(for: key),
  704. boolEncoding: boolEncoding,
  705. dataEncoding: dataEncoding,
  706. dateEncoding: dateEncoding,
  707. nilEncoding: nilEncoding)
  708. return KeyedEncodingContainer(container)
  709. }
  710. func superEncoder() -> Encoder {
  711. _URLEncodedFormEncoder(context: context,
  712. codingPath: codingPath,
  713. boolEncoding: boolEncoding,
  714. dataEncoding: dataEncoding,
  715. dateEncoding: dateEncoding,
  716. nilEncoding: nilEncoding)
  717. }
  718. func superEncoder(forKey key: Key) -> Encoder {
  719. _URLEncodedFormEncoder(context: context,
  720. codingPath: nestedCodingPath(for: key),
  721. boolEncoding: boolEncoding,
  722. dataEncoding: dataEncoding,
  723. dateEncoding: dateEncoding,
  724. nilEncoding: nilEncoding)
  725. }
  726. }
  727. extension _URLEncodedFormEncoder {
  728. final class SingleValueContainer {
  729. var codingPath: [CodingKey]
  730. private var canEncodeNewValue = true
  731. private let context: URLEncodedFormContext
  732. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  733. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  734. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  735. private let nilEncoding: URLEncodedFormEncoder.NilEncoding
  736. init(context: URLEncodedFormContext,
  737. codingPath: [CodingKey],
  738. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  739. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  740. dateEncoding: URLEncodedFormEncoder.DateEncoding,
  741. nilEncoding: URLEncodedFormEncoder.NilEncoding) {
  742. self.context = context
  743. self.codingPath = codingPath
  744. self.boolEncoding = boolEncoding
  745. self.dataEncoding = dataEncoding
  746. self.dateEncoding = dateEncoding
  747. self.nilEncoding = nilEncoding
  748. }
  749. private func checkCanEncode(value: Any?) throws {
  750. guard canEncodeNewValue else {
  751. let context = EncodingError.Context(codingPath: codingPath,
  752. debugDescription: "Attempt to encode value through single value container when previously value already encoded.")
  753. throw EncodingError.invalidValue(value as Any, context)
  754. }
  755. }
  756. }
  757. }
  758. extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer {
  759. func encodeNil() throws {
  760. guard let nilValue = nilEncoding.encodeNil() else { return }
  761. try encode(nilValue)
  762. }
  763. func encode(_ value: Bool) throws {
  764. try encode(value, as: String(boolEncoding.encode(value)))
  765. }
  766. func encode(_ value: String) throws {
  767. try encode(value, as: value)
  768. }
  769. func encode(_ value: Double) throws {
  770. try encode(value, as: String(value))
  771. }
  772. func encode(_ value: Float) throws {
  773. try encode(value, as: String(value))
  774. }
  775. func encode(_ value: Int) throws {
  776. try encode(value, as: String(value))
  777. }
  778. func encode(_ value: Int8) throws {
  779. try encode(value, as: String(value))
  780. }
  781. func encode(_ value: Int16) throws {
  782. try encode(value, as: String(value))
  783. }
  784. func encode(_ value: Int32) throws {
  785. try encode(value, as: String(value))
  786. }
  787. func encode(_ value: Int64) throws {
  788. try encode(value, as: String(value))
  789. }
  790. func encode(_ value: UInt) throws {
  791. try encode(value, as: String(value))
  792. }
  793. func encode(_ value: UInt8) throws {
  794. try encode(value, as: String(value))
  795. }
  796. func encode(_ value: UInt16) throws {
  797. try encode(value, as: String(value))
  798. }
  799. func encode(_ value: UInt32) throws {
  800. try encode(value, as: String(value))
  801. }
  802. func encode(_ value: UInt64) throws {
  803. try encode(value, as: String(value))
  804. }
  805. private func encode<T>(_ value: T, as string: String) throws where T: Encodable {
  806. try checkCanEncode(value: value)
  807. defer { canEncodeNewValue = false }
  808. context.component.set(to: .string(string), at: codingPath)
  809. }
  810. func encode<T>(_ value: T) throws where T: Encodable {
  811. switch value {
  812. case let date as Date:
  813. guard let string = try dateEncoding.encode(date) else {
  814. try attemptToEncode(value)
  815. return
  816. }
  817. try encode(value, as: string)
  818. case let data as Data:
  819. guard let string = try dataEncoding.encode(data) else {
  820. try attemptToEncode(value)
  821. return
  822. }
  823. try encode(value, as: string)
  824. case let decimal as Decimal:
  825. // Decimal's `Encodable` implementation returns an object, not a single value, so override it.
  826. try encode(value, as: String(describing: decimal))
  827. default:
  828. try attemptToEncode(value)
  829. }
  830. }
  831. private func attemptToEncode<T>(_ value: T) throws where T: Encodable {
  832. try checkCanEncode(value: value)
  833. defer { canEncodeNewValue = false }
  834. let encoder = _URLEncodedFormEncoder(context: context,
  835. codingPath: codingPath,
  836. boolEncoding: boolEncoding,
  837. dataEncoding: dataEncoding,
  838. dateEncoding: dateEncoding,
  839. nilEncoding: nilEncoding)
  840. try value.encode(to: encoder)
  841. }
  842. }
  843. extension _URLEncodedFormEncoder {
  844. final class UnkeyedContainer {
  845. var codingPath: [CodingKey]
  846. var count = 0
  847. var nestedCodingPath: [CodingKey] {
  848. codingPath + [AnyCodingKey(intValue: count)!]
  849. }
  850. private let context: URLEncodedFormContext
  851. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  852. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  853. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  854. private let nilEncoding: URLEncodedFormEncoder.NilEncoding
  855. init(context: URLEncodedFormContext,
  856. codingPath: [CodingKey],
  857. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  858. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  859. dateEncoding: URLEncodedFormEncoder.DateEncoding,
  860. nilEncoding: URLEncodedFormEncoder.NilEncoding) {
  861. self.context = context
  862. self.codingPath = codingPath
  863. self.boolEncoding = boolEncoding
  864. self.dataEncoding = dataEncoding
  865. self.dateEncoding = dateEncoding
  866. self.nilEncoding = nilEncoding
  867. }
  868. }
  869. }
  870. extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer {
  871. func encodeNil() throws {
  872. guard let nilValue = nilEncoding.encodeNil() else { return }
  873. try encode(nilValue)
  874. }
  875. func encode<T>(_ value: T) throws where T: Encodable {
  876. var container = nestedSingleValueContainer()
  877. try container.encode(value)
  878. }
  879. func nestedSingleValueContainer() -> SingleValueEncodingContainer {
  880. defer { count += 1 }
  881. return _URLEncodedFormEncoder.SingleValueContainer(context: context,
  882. codingPath: nestedCodingPath,
  883. boolEncoding: boolEncoding,
  884. dataEncoding: dataEncoding,
  885. dateEncoding: dateEncoding,
  886. nilEncoding: nilEncoding)
  887. }
  888. func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
  889. defer { count += 1 }
  890. let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
  891. codingPath: nestedCodingPath,
  892. boolEncoding: boolEncoding,
  893. dataEncoding: dataEncoding,
  894. dateEncoding: dateEncoding,
  895. nilEncoding: nilEncoding)
  896. return KeyedEncodingContainer(container)
  897. }
  898. func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
  899. defer { count += 1 }
  900. return _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  901. codingPath: nestedCodingPath,
  902. boolEncoding: boolEncoding,
  903. dataEncoding: dataEncoding,
  904. dateEncoding: dateEncoding,
  905. nilEncoding: nilEncoding)
  906. }
  907. func superEncoder() -> Encoder {
  908. defer { count += 1 }
  909. return _URLEncodedFormEncoder(context: context,
  910. codingPath: codingPath,
  911. boolEncoding: boolEncoding,
  912. dataEncoding: dataEncoding,
  913. dateEncoding: dateEncoding,
  914. nilEncoding: nilEncoding)
  915. }
  916. }
  917. final class URLEncodedFormSerializer {
  918. private let alphabetizeKeyValuePairs: Bool
  919. private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding
  920. private let keyEncoding: URLEncodedFormEncoder.KeyEncoding
  921. private let keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding
  922. private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding
  923. private let allowedCharacters: CharacterSet
  924. init(alphabetizeKeyValuePairs: Bool,
  925. arrayEncoding: URLEncodedFormEncoder.ArrayEncoding,
  926. keyEncoding: URLEncodedFormEncoder.KeyEncoding,
  927. keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding,
  928. spaceEncoding: URLEncodedFormEncoder.SpaceEncoding,
  929. allowedCharacters: CharacterSet) {
  930. self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs
  931. self.arrayEncoding = arrayEncoding
  932. self.keyEncoding = keyEncoding
  933. self.keyPathEncoding = keyPathEncoding
  934. self.spaceEncoding = spaceEncoding
  935. self.allowedCharacters = allowedCharacters
  936. }
  937. func serialize(_ object: URLEncodedFormComponent.Object) -> String {
  938. var output: [String] = []
  939. for (key, component) in object {
  940. let value = serialize(component, forKey: key)
  941. output.append(value)
  942. }
  943. output = alphabetizeKeyValuePairs ? output.sorted() : output
  944. return output.joinedWithAmpersands()
  945. }
  946. func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String {
  947. switch component {
  948. case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))"
  949. case let .array(array): return serialize(array, forKey: key)
  950. case let .object(object): return serialize(object, forKey: key)
  951. }
  952. }
  953. func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String {
  954. var segments: [String] = object.map { subKey, value in
  955. let keyPath = keyPathEncoding.encodeKeyPath(subKey)
  956. return serialize(value, forKey: key + keyPath)
  957. }
  958. segments = alphabetizeKeyValuePairs ? segments.sorted() : segments
  959. return segments.joinedWithAmpersands()
  960. }
  961. func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String {
  962. var segments: [String] = array.enumerated().map { index, component in
  963. let keyPath = arrayEncoding.encode(key, atIndex: index)
  964. return serialize(component, forKey: keyPath)
  965. }
  966. segments = alphabetizeKeyValuePairs ? segments.sorted() : segments
  967. return segments.joinedWithAmpersands()
  968. }
  969. func escape(_ query: String) -> String {
  970. var allowedCharactersWithSpace = allowedCharacters
  971. allowedCharactersWithSpace.insert(charactersIn: " ")
  972. let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query
  973. let spaceEncodedQuery = spaceEncoding.encode(escapedQuery)
  974. return spaceEncodedQuery
  975. }
  976. }
  977. extension Array where Element == String {
  978. func joinedWithAmpersands() -> String {
  979. joined(separator: "&")
  980. }
  981. }
  982. extension CharacterSet {
  983. /// Creates a CharacterSet from RFC 3986 allowed characters.
  984. ///
  985. /// RFC 3986 states that the following characters are "reserved" characters.
  986. ///
  987. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  988. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  989. ///
  990. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  991. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  992. /// should be percent-escaped in the query string.
  993. public static let afURLQueryAllowed: CharacterSet = {
  994. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  995. let subDelimitersToEncode = "!$&'()*+,;="
  996. let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  997. return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
  998. }()
  999. }