this repo has no description
1//
2// DataEncodingStrategy.swift
3// URLQueryItemCoder
4//
5// Created by Kyle Hughes on 3/10/23.
6//
7
8import Foundation
9
10/// The strategy to use for encoding `Data` values.
11public enum DataEncodingStrategy {
12 /// Encoded the `Data` as a Base64-encoded string.
13 ///
14 /// This is the default strategy.
15 case base64
16
17 /// Encode the `Data` as a custom value encoded by the given closure.
18 ///
19 /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic
20 /// container in its place.
21 case custom(@Sendable (Data, Encoder) throws -> Void)
22
23 /// Defer to `Data` for choosing an encoding.
24 case deferredToData
25
26 // MARK: Public Static Interface
27
28 /// The default encoding strategy.
29 ///
30 /// Equals `.base64`.
31 public static let `default`: Self = .base64
32
33 // MARK: Internal Instance Interface
34
35 internal func encode(
36 _ data: Data,
37 at codingPath: [any CodingKey],
38 using configuration: EncodingStrategies
39 ) throws -> EncodingContainer {
40 switch self {
41 case .base64:
42 let container = EncodingContainer.SingleValue(codingPath: codingPath, configuration: configuration)
43
44 try container.encode(data.base64EncodedString())
45
46 return .singleValue(container)
47 case let .custom(closure):
48 let lowLevelEncoder = LowLevelEncoder(codingPath: codingPath, configuration: configuration)
49
50 try closure(data, lowLevelEncoder)
51
52 guard let container = lowLevelEncoder.container else {
53 preconditionFailure("Date was not encoded by low level encoder.")
54 }
55
56 return container
57 case .deferredToData:
58 return try .encodeByDeferringToType(data, at: codingPath, using: configuration)
59 }
60 }
61}