this repo has no description
at main 63 lines 2.1 kB view raw
1// 2// DataDecodingStrategy.swift 3// URLQueryItemCoder 4// 5// Created by Kyle Hughes on 4/8/23. 6// 7 8import Foundation 9 10/// The strategy to use for decoding `Data` values. 11public enum DataDecodingStrategy { 12 /// Decode the `Data` from a Base64-encoded string. 13 /// 14 /// This is the default strategy. 15 case base64 16 17 /// Decode the `Data` as a custom value decoded by the given closure. 18 case custom(@Sendable (Decoder) throws -> Data) 19 20 /// Defer to `Data` for decoding. 21 case deferredToData 22 23 // MARK: Public Static Interface 24 25 /// The default decoding strategy. 26 /// 27 /// Equals `.base64`. 28 public static let `default`: Self = .base64 29 30 // MARK: Internal Instance Interface 31 32 internal func decode<PrimitiveValue>(insideOf lowLevelDecoder: LowLevelDecoder<PrimitiveValue>) throws -> Data { 33 switch self { 34 case .base64: 35 switch lowLevelDecoder.container { 36 case .multiValue: 37 throw DecodingError.dataCorrupted( 38 DecodingError.Context( 39 codingPath: lowLevelDecoder.codingPath, 40 debugDescription: "Expected data to be encoded as a single value conatiner." 41 ) 42 ) 43 case let .singleValue(singleValueContainer): 44 let stringValue = try singleValueContainer.decode(String.self) 45 46 guard let data = Data(base64Encoded: stringValue) else { 47 throw DecodingError.dataCorrupted( 48 DecodingError.Context( 49 codingPath: singleValueContainer.codingPath, 50 debugDescription: "Data unable to be decoded from base64 string." 51 ) 52 ) 53 } 54 55 return data 56 } 57 case let .custom(closure): 58 return try closure(lowLevelDecoder) 59 case .deferredToData: 60 return try Data(from: lowLevelDecoder) 61 } 62 } 63}