this repo has no description
at main 64 lines 2.0 kB view raw
1// 2// NonConformingFloatEncodingStrategy.swift 3// URLQueryItemCoder 4// 5// Created by Kyle Hughes on 3/17/23. 6// 7 8/// The strategy to use for non-conforming floating-point values (IEEE 754 infinity and NaN). 9public enum NonConformingFloatEncodingStrategy { 10 /// Encode the values using the given representation strings. 11 case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) 12 13 /// Throw upon encountering non-conforming values. This is the default strategy. 14 case `throw` 15 16 // MARK: Public Static Interface 17 18 /// The default encoding strategy. 19 /// 20 /// Equals `.throw`. 21 public static let `default`: Self = .throw 22 23 // MARK: Internal Instance Interface 24 25 internal func encode<F>( 26 _ float: F, 27 at codingPath: [any CodingKey], 28 using configuration: EncodingStrategies 29 ) throws -> EncodingPrimitiveValue where F: CustomStringConvertible & FloatingPoint { 30 guard !float.isNaN, !float.isInfinite else { 31 switch self { 32 case let .convertToString(posInf, negInf, nan): 33 return .string( 34 { 35 switch float { 36 case .infinity: 37 return posInf 38 case -.infinity: 39 return negInf 40 default: 41 return nan 42 } 43 }() 44 ) 45 case .throw: 46 throw EncodingError.invalidValue( 47 float, 48 EncodingError.Context( 49 codingPath: codingPath, 50 debugDescription: "Unable to encode \(F.self).\(float) directly." 51 ) 52 ) 53 } 54 } 55 56 var string = float.description 57 58 if string.hasSuffix(".0") { 59 string.removeLast(2) 60 } 61 62 return .string(string) 63 } 64}