@@ -69,8 +69,36 @@ extension Number {
6969 )
7070 }
7171
72- self . val = try container. decode ( Double . self, forKey: . val)
73- self . unit = try container. decode ( String ? . self, forKey: . unit)
72+ if let val = try ? container. decode ( Double . self, forKey: . val) {
73+ self . val = val
74+ self . unit = try container. decode ( String ? . self, forKey: . unit)
75+ } else if let val = try ? container. decode ( String . self, forKey: . val) {
76+ self . unit = nil
77+ switch val {
78+ case " INF " :
79+ self . val = . infinity
80+ case " -INF " :
81+ self . val = - 1.0 * . infinity
82+ case " NaN " :
83+ self . val = . nan
84+ default :
85+ throw DecodingError . typeMismatch (
86+ Self . self,
87+ . init(
88+ codingPath: [ Self . CodingKeys. val] ,
89+ debugDescription: " String `val` must be either `INF`, `-INF`, or `NaN`, not \( val) "
90+ )
91+ )
92+ }
93+ } else {
94+ throw DecodingError . typeMismatch (
95+ Self . self,
96+ . init(
97+ codingPath: [ Self . CodingKeys. val] ,
98+ debugDescription: " Expected `val` to be either Double or String "
99+ )
100+ )
101+ }
74102 } else if let container = try ? decoder. singleValueContainer ( ) {
75103 self . val = try container. decode ( Double . self)
76104 self . unit = nil
@@ -89,8 +117,19 @@ extension Number {
89117 if unit != nil || val. isNaN || val. isInfinite {
90118 var container = encoder. container ( keyedBy: Self . CodingKeys)
91119 try container. encode ( Self . kindValue, forKey: . _kind)
92- try container. encode ( val, forKey: . val)
93- try container. encode ( unit, forKey: . unit)
120+
121+ if val. isNaN {
122+ try container. encode ( " NaN " , forKey: . val)
123+ } else if val. isInfinite {
124+ if val > 0 {
125+ try container. encode ( " INF " , forKey: . val)
126+ } else {
127+ try container. encode ( " -INF " , forKey: . val)
128+ }
129+ } else {
130+ try container. encode ( val, forKey: . val)
131+ try container. encode ( unit, forKey: . unit)
132+ }
94133 } else {
95134 var container = encoder. singleValueContainer ( )
96135 try container. encode ( val)
0 commit comments