DataStreamRequest.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. //
  2. // DataStreamRequest.swift
  3. //
  4. // Copyright (c) 2014-2024 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. /// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
  26. public final class DataStreamRequest: Request {
  27. /// Closure type handling `DataStreamRequest.Stream` values.
  28. public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
  29. /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
  30. /// to stop the stream at any time.
  31. public struct Stream<Success, Failure: Error> {
  32. /// Latest `Event` from the stream.
  33. public let event: Event<Success, Failure>
  34. /// Token used to cancel the stream.
  35. public let token: CancellationToken
  36. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  37. public func cancel() {
  38. token.cancel()
  39. }
  40. }
  41. /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
  42. /// `Data` or the completion of the stream.
  43. public enum Event<Success, Failure: Error> {
  44. /// Output produced every time the instance receives additional `Data`. The associated value contains the
  45. /// `Result` of processing the incoming `Data`.
  46. case stream(Result<Success, Failure>)
  47. /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
  48. /// Associated `Completion` value contains the final state.
  49. case complete(Completion)
  50. }
  51. /// Value containing the state of a `DataStreamRequest` when the stream was completed.
  52. public struct Completion {
  53. /// Last `URLRequest` issued by the instance.
  54. public let request: URLRequest?
  55. /// Last `HTTPURLResponse` received by the instance.
  56. public let response: HTTPURLResponse?
  57. /// Last `URLSessionTaskMetrics` produced for the instance.
  58. public let metrics: URLSessionTaskMetrics?
  59. /// `AFError` produced for the instance, if any.
  60. public let error: AFError?
  61. }
  62. /// Type used to cancel an ongoing stream.
  63. public struct CancellationToken {
  64. weak var request: DataStreamRequest?
  65. init(_ request: DataStreamRequest) {
  66. self.request = request
  67. }
  68. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  69. public func cancel() {
  70. request?.cancel()
  71. }
  72. }
  73. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  74. public let convertible: URLRequestConvertible
  75. /// Whether or not the instance will be cancelled if stream parsing encounters an error.
  76. public let automaticallyCancelOnStreamError: Bool
  77. /// Internal mutable state specific to this type.
  78. struct StreamMutableState {
  79. /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
  80. var outputStream: OutputStream?
  81. /// Stream closures called as `Data` is received.
  82. var streams: [(_ data: Data) -> Void] = []
  83. /// Number of currently executing streams. Used to ensure completions are only fired after all streams are
  84. /// enqueued.
  85. var numberOfExecutingStreams = 0
  86. /// Completion calls enqueued while streams are still executing.
  87. var enqueuedCompletionEvents: [() -> Void] = []
  88. /// Handler for any `HTTPURLResponse`s received.
  89. var httpResponseHandler: (queue: DispatchQueue,
  90. handler: (_ response: HTTPURLResponse,
  91. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)?
  92. }
  93. let streamMutableState = Protected(StreamMutableState())
  94. /// Creates a `DataStreamRequest` using the provided parameters.
  95. ///
  96. /// - Parameters:
  97. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
  98. /// by default.
  99. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
  100. /// instance.
  101. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
  102. /// is thrown while serializing stream `Data`.
  103. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  104. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
  105. /// targets
  106. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  107. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  108. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  109. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by
  110. /// the `Request`.
  111. init(id: UUID = UUID(),
  112. convertible: URLRequestConvertible,
  113. automaticallyCancelOnStreamError: Bool,
  114. underlyingQueue: DispatchQueue,
  115. serializationQueue: DispatchQueue,
  116. eventMonitor: EventMonitor?,
  117. interceptor: RequestInterceptor?,
  118. delegate: RequestDelegate) {
  119. self.convertible = convertible
  120. self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
  121. super.init(id: id,
  122. underlyingQueue: underlyingQueue,
  123. serializationQueue: serializationQueue,
  124. eventMonitor: eventMonitor,
  125. interceptor: interceptor,
  126. delegate: delegate)
  127. }
  128. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  129. let copiedRequest = request
  130. return session.dataTask(with: copiedRequest)
  131. }
  132. override func finish(error: AFError? = nil) {
  133. streamMutableState.write { state in
  134. state.outputStream?.close()
  135. }
  136. super.finish(error: error)
  137. }
  138. func didReceive(data: Data) {
  139. streamMutableState.write { state in
  140. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  141. if let stream = state.outputStream {
  142. underlyingQueue.async {
  143. var bytes = Array(data)
  144. stream.write(&bytes, maxLength: bytes.count)
  145. }
  146. }
  147. #endif
  148. state.numberOfExecutingStreams += state.streams.count
  149. let localState = state
  150. underlyingQueue.async { localState.streams.forEach { $0(data) } }
  151. }
  152. }
  153. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  154. streamMutableState.read { dataMutableState in
  155. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  156. underlyingQueue.async { completionHandler(.allow) }
  157. return
  158. }
  159. httpResponseHandler.queue.async {
  160. httpResponseHandler.handler(response) { disposition in
  161. if disposition == .cancel {
  162. self.mutableState.write { mutableState in
  163. mutableState.state = .cancelled
  164. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  165. }
  166. }
  167. self.underlyingQueue.async {
  168. completionHandler(disposition.sessionDisposition)
  169. }
  170. }
  171. }
  172. }
  173. }
  174. /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
  175. ///
  176. /// - Parameter validation: `Validation` closure used to validate the request and response.
  177. ///
  178. /// - Returns: The `DataStreamRequest`.
  179. @discardableResult
  180. public func validate(_ validation: @escaping Validation) -> Self {
  181. let validator: () -> Void = { [unowned self] in
  182. guard error == nil, let response else { return }
  183. let result = validation(request, response)
  184. if case let .failure(error) = result {
  185. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  186. }
  187. eventMonitor?.request(self,
  188. didValidateRequest: request,
  189. response: response,
  190. withResult: result)
  191. }
  192. validators.write { $0.append(validator) }
  193. return self
  194. }
  195. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  196. /// Produces an `InputStream` that receives the `Data` received by the instance.
  197. ///
  198. /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
  199. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
  200. /// not the creating session has `startRequestsImmediately` set to `true`.
  201. ///
  202. /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
  203. ///
  204. /// - Returns: The `InputStream` bound to the internal `OutboundStream`.
  205. public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
  206. defer { resume() }
  207. var inputStream: InputStream?
  208. streamMutableState.write { state in
  209. Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
  210. inputStream: &inputStream,
  211. outputStream: &state.outputStream)
  212. state.outputStream?.open()
  213. }
  214. return inputStream
  215. }
  216. #endif
  217. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  218. /// handler to return a `ResponseDisposition` value.
  219. ///
  220. /// - Parameters:
  221. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  222. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  223. /// MUST be called, otherwise the request will never complete.
  224. ///
  225. /// - Returns: The instance.
  226. @_disfavoredOverload
  227. @discardableResult
  228. public func onHTTPResponse(
  229. on queue: DispatchQueue = .main,
  230. perform handler: @escaping (_ response: HTTPURLResponse,
  231. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void
  232. ) -> Self {
  233. streamMutableState.write { mutableState in
  234. mutableState.httpResponseHandler = (queue, handler)
  235. }
  236. return self
  237. }
  238. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  239. ///
  240. /// - Parameters:
  241. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  242. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  243. ///
  244. /// - Returns: The instance.
  245. @discardableResult
  246. public func onHTTPResponse(on queue: DispatchQueue = .main,
  247. perform handler: @escaping (HTTPURLResponse) -> Void) -> Self {
  248. onHTTPResponse(on: queue) { response, completionHandler in
  249. handler(response)
  250. completionHandler(.allow)
  251. }
  252. return self
  253. }
  254. func capturingError(from closure: () throws -> Void) {
  255. do {
  256. try closure()
  257. } catch {
  258. self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  259. cancel()
  260. }
  261. }
  262. func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
  263. stream: @escaping Handler<Success, Failure>) {
  264. appendResponseSerializer {
  265. self.underlyingQueue.async {
  266. self.responseSerializerDidComplete {
  267. self.streamMutableState.write { state in
  268. guard state.numberOfExecutingStreams == 0 else {
  269. state.enqueuedCompletionEvents.append {
  270. self.enqueueCompletion(on: queue, stream: stream)
  271. }
  272. return
  273. }
  274. self.enqueueCompletion(on: queue, stream: stream)
  275. }
  276. }
  277. }
  278. }
  279. }
  280. func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
  281. stream: @escaping Handler<Success, Failure>) {
  282. queue.async {
  283. do {
  284. let completion = Completion(request: self.request,
  285. response: self.response,
  286. metrics: self.metrics,
  287. error: self.error)
  288. try stream(.init(event: .complete(completion), token: .init(self)))
  289. } catch {
  290. // Ignore error, as errors on Completion can't be handled anyway.
  291. }
  292. }
  293. }
  294. // MARK: Response Serialization
  295. /// Adds a `StreamHandler` which performs no parsing on incoming `Data`.
  296. ///
  297. /// - Parameters:
  298. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  299. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  300. ///
  301. /// - Returns: The `DataStreamRequest`.
  302. @discardableResult
  303. public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler<Data, Never>) -> Self {
  304. let parser = { [unowned self] (data: Data) in
  305. queue.async {
  306. self.capturingError {
  307. try stream(.init(event: .stream(.success(data)), token: .init(self)))
  308. }
  309. self.updateAndCompleteIfPossible()
  310. }
  311. }
  312. streamMutableState.write { $0.streams.append(parser) }
  313. appendStreamCompletion(on: queue, stream: stream)
  314. return self
  315. }
  316. /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`.
  317. ///
  318. /// - Parameters:
  319. /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`.
  320. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  321. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  322. ///
  323. /// - Returns: The `DataStreamRequest`.
  324. @discardableResult
  325. public func responseStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
  326. on queue: DispatchQueue = .main,
  327. stream: @escaping Handler<Serializer.SerializedObject, AFError>) -> Self {
  328. let parser = { [unowned self] (data: Data) in
  329. serializationQueue.async {
  330. // Start work on serialization queue.
  331. let result = Result { try serializer.serialize(data) }
  332. .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) }
  333. // End work on serialization queue.
  334. self.underlyingQueue.async {
  335. self.eventMonitor?.request(self, didParseStream: result)
  336. if result.isFailure, self.automaticallyCancelOnStreamError {
  337. self.cancel()
  338. }
  339. queue.async {
  340. self.capturingError {
  341. try stream(.init(event: .stream(result), token: .init(self)))
  342. }
  343. self.updateAndCompleteIfPossible()
  344. }
  345. }
  346. }
  347. }
  348. streamMutableState.write { $0.streams.append(parser) }
  349. appendStreamCompletion(on: queue, stream: stream)
  350. return self
  351. }
  352. /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`.
  353. ///
  354. /// - Parameters:
  355. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  356. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  357. ///
  358. /// - Returns: The `DataStreamRequest`.
  359. @discardableResult
  360. public func responseStreamString(on queue: DispatchQueue = .main,
  361. stream: @escaping Handler<String, Never>) -> Self {
  362. let parser = { [unowned self] (data: Data) in
  363. serializationQueue.async {
  364. // Start work on serialization queue.
  365. let string = String(decoding: data, as: UTF8.self)
  366. // End work on serialization queue.
  367. self.underlyingQueue.async {
  368. self.eventMonitor?.request(self, didParseStream: .success(string))
  369. queue.async {
  370. self.capturingError {
  371. try stream(.init(event: .stream(.success(string)), token: .init(self)))
  372. }
  373. self.updateAndCompleteIfPossible()
  374. }
  375. }
  376. }
  377. }
  378. streamMutableState.write { $0.streams.append(parser) }
  379. appendStreamCompletion(on: queue, stream: stream)
  380. return self
  381. }
  382. private func updateAndCompleteIfPossible() {
  383. streamMutableState.write { state in
  384. state.numberOfExecutingStreams -= 1
  385. guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return }
  386. let completionEvents = state.enqueuedCompletionEvents
  387. self.underlyingQueue.async { completionEvents.forEach { $0() } }
  388. state.enqueuedCompletionEvents.removeAll()
  389. }
  390. }
  391. /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`.
  392. ///
  393. /// - Parameters:
  394. /// - type: `Decodable` type to parse incoming `Data` into.
  395. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  396. /// - decoder: `DataDecoder` used to decode the incoming `Data`.
  397. /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`.
  398. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  399. ///
  400. /// - Returns: The `DataStreamRequest`.
  401. @discardableResult
  402. public func responseStreamDecodable<T: Decodable>(of type: T.Type = T.self,
  403. on queue: DispatchQueue = .main,
  404. using decoder: DataDecoder = JSONDecoder(),
  405. preprocessor: DataPreprocessor = PassthroughPreprocessor(),
  406. stream: @escaping Handler<T, AFError>) -> Self {
  407. responseStream(using: DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: preprocessor),
  408. on: queue,
  409. stream: stream)
  410. }
  411. }
  412. extension DataStreamRequest.Stream {
  413. /// Incoming `Result` values from `Event.stream`.
  414. public var result: Result<Success, Failure>? {
  415. guard case let .stream(result) = event else { return nil }
  416. return result
  417. }
  418. /// `Success` value of the instance, if any.
  419. public var value: Success? {
  420. guard case let .success(value) = result else { return nil }
  421. return value
  422. }
  423. /// `Failure` value of the instance, if any.
  424. public var error: Failure? {
  425. guard case let .failure(error) = result else { return nil }
  426. return error
  427. }
  428. /// `Completion` value of the instance, if any.
  429. public var completion: DataStreamRequest.Completion? {
  430. guard case let .complete(completion) = event else { return nil }
  431. return completion
  432. }
  433. }
  434. // MARK: - Serialization
  435. /// A type which can serialize incoming `Data`.
  436. public protocol DataStreamSerializer {
  437. /// Type produced from the serialized `Data`.
  438. associatedtype SerializedObject
  439. /// Serializes incoming `Data` into a `SerializedObject` value.
  440. ///
  441. /// - Parameter data: `Data` to be serialized.
  442. ///
  443. /// - Throws: Any error produced during serialization.
  444. func serialize(_ data: Data) throws -> SerializedObject
  445. }
  446. /// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`.
  447. public struct DecodableStreamSerializer<T: Decodable>: DataStreamSerializer {
  448. /// `DataDecoder` used to decode incoming `Data`.
  449. public let decoder: DataDecoder
  450. /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`.
  451. public let dataPreprocessor: DataPreprocessor
  452. /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`.
  453. /// - Parameters:
  454. /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default.
  455. /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the
  456. /// `decoder`. `PassthroughPreprocessor()` by default.
  457. public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) {
  458. self.decoder = decoder
  459. self.dataPreprocessor = dataPreprocessor
  460. }
  461. public func serialize(_ data: Data) throws -> T {
  462. let processedData = try dataPreprocessor.preprocess(data)
  463. do {
  464. return try decoder.decode(T.self, from: processedData)
  465. } catch {
  466. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  467. }
  468. }
  469. }
  470. /// `DataStreamSerializer` which performs no serialization on incoming `Data`.
  471. public struct PassthroughStreamSerializer: DataStreamSerializer {
  472. /// Creates an instance.
  473. public init() {}
  474. public func serialize(_ data: Data) throws -> Data { data }
  475. }
  476. /// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values.
  477. public struct StringStreamSerializer: DataStreamSerializer {
  478. /// Creates an instance.
  479. public init() {}
  480. public func serialize(_ data: Data) throws -> String {
  481. String(decoding: data, as: UTF8.self)
  482. }
  483. }
  484. extension DataStreamSerializer {
  485. /// Creates a `DecodableStreamSerializer` instance with the provided `DataDecoder` and `DataPreprocessor`.
  486. ///
  487. /// - Parameters:
  488. /// - type: `Decodable` type to decode from stream data.
  489. /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default.
  490. /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the
  491. /// `decoder`. `PassthroughPreprocessor()` by default.
  492. public static func decodable<T: Decodable>(of type: T.Type,
  493. decoder: DataDecoder = JSONDecoder(),
  494. dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer<T> {
  495. DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: dataPreprocessor)
  496. }
  497. }
  498. extension DataStreamSerializer where Self == PassthroughStreamSerializer {
  499. /// Provides a `PassthroughStreamSerializer` instance.
  500. public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() }
  501. }
  502. extension DataStreamSerializer where Self == StringStreamSerializer {
  503. /// Provides a `StringStreamSerializer` instance.
  504. public static var string: StringStreamSerializer { StringStreamSerializer() }
  505. }