@@ -102,28 +102,42 @@ extension Array where Element: FixedWidthInteger {
102102
103103extension BigInt : Codable {
104104 public init ( from decoder: Decoder ) throws {
105- var container = try decoder. unkeyedContainer ( )
105+ if let container = try ? decoder. singleValueContainer ( ) , let stringValue = try ? container. decode ( String . self) {
106+ if stringValue. hasPrefix ( " 0x " ) || stringValue. hasPrefix ( " 0X " ) {
107+ guard let bigUInt = BigUInt ( stringValue. dropFirst ( 2 ) , radix: 16 ) else {
108+ throw DecodingError . dataCorruptedError ( in: container, debugDescription: " Invalid hexadecimal BigInt string " )
109+ }
110+ self . init ( sign: . plus, magnitude: bigUInt)
111+ } else {
112+ guard let bigInt = BigInt ( stringValue) else {
113+ throw DecodingError . dataCorruptedError ( in: container, debugDescription: " Invalid decimal BigInt string " )
114+ }
115+ self = bigInt
116+ }
117+ } else {
118+ var container = try decoder. unkeyedContainer ( )
106119
107- // Decode sign
108- let sign : BigInt . Sign
109- switch try container. decode ( String . self) {
110- case " + " :
111- sign = . plus
112- case " - " :
113- sign = . minus
114- default :
115- throw DecodingError . dataCorrupted ( . init( codingPath: container. codingPath,
116- debugDescription: " Invalid big integer sign " ) )
117- }
120+ // Decode sign
121+ let sign : BigInt . Sign
122+ switch try container. decode ( String . self) {
123+ case " + " :
124+ sign = . plus
125+ case " - " :
126+ sign = . minus
127+ default :
128+ throw DecodingError . dataCorrupted ( . init( codingPath: container. codingPath,
129+ debugDescription: " Invalid big integer sign " ) )
130+ }
118131
119- // Decode magnitude
120- let words = try [ UInt] ( count: container. count? . advanced ( by: - 1 ) ) { ( ) -> UInt64 ? in
121- guard !container. isAtEnd else { return nil }
122- return try container. decode ( UInt64 . self)
123- }
124- let magnitude = BigUInt ( words: words)
132+ // Decode magnitude
133+ let words = try [ UInt] ( count: container. count? . advanced ( by: - 1 ) ) { ( ) -> UInt64 ? in
134+ guard !container. isAtEnd else { return nil }
135+ return try container. decode ( UInt64 . self)
136+ }
137+ let magnitude = BigUInt ( words: words)
125138
126- self . init ( sign: sign, magnitude: magnitude)
139+ self . init ( sign: sign, magnitude: magnitude)
140+ }
127141 }
128142
129143 public func encode( to encoder: Encoder ) throws {
0 commit comments