Procházet zdrojové kódy

Keep existing errors and move only new ones to SwiftProtobufError

Gus Cairo před 1 rokem
rodič
revize
330beeccd4
35 změnil soubory, kde provedl 304 přidání a 1070 odebrání
  1. 5 5
      Sources/SwiftProtobuf/AnyMessageStorage.swift
  2. 0 1
      Sources/SwiftProtobuf/AnyUnpackError.swift
  3. 2 2
      Sources/SwiftProtobuf/AsyncMessageSequence.swift
  4. 37 37
      Sources/SwiftProtobuf/BinaryDecoder.swift
  5. 0 1
      Sources/SwiftProtobuf/BinaryDecodingError.swift
  6. 6 7
      Sources/SwiftProtobuf/BinaryDelimited.swift
  7. 0 1
      Sources/SwiftProtobuf/BinaryEncodingError.swift
  8. 2 2
      Sources/SwiftProtobuf/Google_Protobuf_Any+Extensions.swift
  9. 9 9
      Sources/SwiftProtobuf/Google_Protobuf_Duration+Extensions.swift
  10. 2 2
      Sources/SwiftProtobuf/Google_Protobuf_FieldMask+Extensions.swift
  11. 16 16
      Sources/SwiftProtobuf/Google_Protobuf_Timestamp+Extensions.swift
  12. 3 3
      Sources/SwiftProtobuf/Google_Protobuf_Value+Extensions.swift
  13. 16 16
      Sources/SwiftProtobuf/JSONDecoder.swift
  14. 0 1
      Sources/SwiftProtobuf/JSONDecodingError.swift
  15. 0 1
      Sources/SwiftProtobuf/JSONEncodingError.swift
  16. 4 4
      Sources/SwiftProtobuf/JSONEncodingVisitor.swift
  17. 80 80
      Sources/SwiftProtobuf/JSONScanner.swift
  18. 2 2
      Sources/SwiftProtobuf/Message+BinaryAdditions.swift
  19. 5 5
      Sources/SwiftProtobuf/Message+JSONAdditions.swift
  20. 3 3
      Sources/SwiftProtobuf/Message+JSONArrayAdditions.swift
  21. 1 1
      Sources/SwiftProtobuf/Message+TextFormatAdditions.swift
  22. 0 761
      Sources/SwiftProtobuf/SwiftProtobufError.swift
  23. 24 24
      Sources/SwiftProtobuf/TextFormatDecoder.swift
  24. 0 1
      Sources/SwiftProtobuf/TextFormatDecodingError.swift
  25. 44 44
      Sources/SwiftProtobuf/TextFormatScanner.swift
  26. 3 3
      Tests/SwiftProtobufTests/Test_AsyncMessageSequence.swift
  27. 1 1
      Tests/SwiftProtobufTests/Test_BinaryDecodingOptions.swift
  28. 1 1
      Tests/SwiftProtobufTests/Test_BinaryDelimited.swift
  29. 5 6
      Tests/SwiftProtobufTests/Test_JSONDecodingOptions.swift
  30. 12 9
      Tests/SwiftProtobufTests/Test_JSON_Conformance.swift
  31. 4 4
      Tests/SwiftProtobufTests/Test_Required.swift
  32. 1 1
      Tests/SwiftProtobufTests/Test_Struct.swift
  33. 1 1
      Tests/SwiftProtobufTests/Test_TextFormatDecodingOptions.swift
  34. 14 14
      Tests/SwiftProtobufTests/Test_TextFormat_Unknown.swift
  35. 1 1
      Tests/SwiftProtobufTests/Test_Wrappers.swift

+ 5 - 5
Sources/SwiftProtobuf/AnyMessageStorage.swift

@@ -76,7 +76,7 @@ fileprivate func unpack(contentJSON: [UInt8],
         }
         if !options.ignoreUnknownFields {
           // The only thing within a WKT should be "value".
-          throw SwiftProtobufError.AnyUnpack.malformedWellKnownTypeJSON()
+          throw AnyUnpackError.malformedWellKnownTypeJSON
         }
         let _ = try scanner.skip()
         try scanner.skipRequiredComma()
@@ -84,7 +84,7 @@ fileprivate func unpack(contentJSON: [UInt8],
       if !options.ignoreUnknownFields && !scanner.complete {
         // If that wasn't the end, then there was another key, and WKTs should
         // only have the one when not skipping unknowns.
-        throw SwiftProtobufError.AnyUnpack.malformedWellKnownTypeJSON()
+        throw AnyUnpackError.malformedWellKnownTypeJSON
       }
     }
   }
@@ -174,7 +174,7 @@ internal class AnyMessageStorage {
     options: BinaryDecodingOptions
   ) throws {
     guard isA(M.self) else {
-      throw SwiftProtobufError.AnyUnpack.typeMismatch()
+      throw AnyUnpackError.typeMismatch
     }
 
     switch state {
@@ -243,7 +243,7 @@ extension AnyMessageStorage {
     _typeURL = url
     guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: url) else {
       // The type wasn't registered, can't parse it.
-      throw SwiftProtobufError.TextFormatDecoding.malformedText()
+      throw TextFormatDecodingError.malformedText
     }
     let terminator = try decoder.scanner.skipObjectStart()
     var subDecoder = try TextFormatDecoder(messageType: messageType, scanner: decoder.scanner, terminator: terminator)
@@ -259,7 +259,7 @@ extension AnyMessageStorage {
     decoder.scanner = subDecoder.scanner
     if try decoder.nextFieldNumber() != nil {
       // Verbose any can never have additional keys.
-      throw SwiftProtobufError.TextFormatDecoding.malformedText()
+      throw TextFormatDecodingError.malformedText
     }
   }
 

+ 0 - 1
Sources/SwiftProtobuf/AnyUnpackError.swift

@@ -21,7 +21,6 @@
 /// message.  At this time, any error can occur that might have occurred from a
 /// regular decoding operation.  There are also other errors that can occur due
 /// to problems with the `Any` value's structure.
-@available(*, deprecated, message: "This error type has been deprecated and won't be thrown anymore; it has been replaced by `SwiftProtobufError`.")
 public enum AnyUnpackError: Error {
   /// The `type_url` field in the `Google_Protobuf_Any` message did not match
   /// the message type provided to the `unpack()` method.

+ 2 - 2
Sources/SwiftProtobuf/AsyncMessageSequence.swift

@@ -131,7 +131,7 @@ public struct AsyncMessageSequence<
       if (shift > 0) {
         // The stream has ended inside a varint.
         iterator = nil
-          throw SwiftProtobufError.BinaryStreamDecoding.truncated()
+          throw BinaryDelimited.Error.truncated
       }
       return nil // End of stream reached.
     }
@@ -153,7 +153,7 @@ public struct AsyncMessageSequence<
           guard let byte = try await iterator?.next() else {
             // The iterator hit the end, but the chunk wasn't filled, so the full
             // payload wasn't read.
-            throw SwiftProtobufError.BinaryStreamDecoding.truncated()
+            throw BinaryDelimited.Error.truncated
           }
           chunk[consumedBytes] = byte
           consumedBytes += 1

+ 37 - 37
Sources/SwiftProtobuf/BinaryDecoder.swift

@@ -80,7 +80,7 @@ internal struct BinaryDecoder: Decoder {
     private mutating func incrementRecursionDepth() throws {
         recursionBudget -= 1
         if recursionBudget < 0 {
-            throw SwiftProtobufError.BinaryDecoding.messageDepthLimit()
+            throw BinaryDecodingError.messageDepthLimit
         }
     }
 
@@ -139,7 +139,7 @@ internal struct BinaryDecoder: Decoder {
         if let wireFormat = WireFormat(rawValue: c0 & 7) {
             fieldWireFormat = wireFormat
         } else {
-            throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+            throw BinaryDecodingError.malformedProtobuf
         }
         if (c0 & 0x80) == 0 {
             p += 1
@@ -148,7 +148,7 @@ internal struct BinaryDecoder: Decoder {
         } else {
             fieldNumber = Int(c0 & 0x7f) >> 3
             if available < 2 {
-                throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                throw BinaryDecodingError.malformedProtobuf
             }
             let c1 = start[1]
             if (c1 & 0x80) == 0 {
@@ -158,7 +158,7 @@ internal struct BinaryDecoder: Decoder {
             } else {
                 fieldNumber |= Int(c1 & 0x7f) << 4
                 if available < 3 {
-                    throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                    throw BinaryDecodingError.malformedProtobuf
                 }
                 let c2 = start[2]
                 fieldNumber |= Int(c2 & 0x7f) << 11
@@ -167,7 +167,7 @@ internal struct BinaryDecoder: Decoder {
                     available -= 3
                 } else {
                     if available < 4 {
-                        throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                        throw BinaryDecodingError.malformedProtobuf
                     }
                     let c3 = start[3]
                     fieldNumber |= Int(c3 & 0x7f) << 18
@@ -176,11 +176,11 @@ internal struct BinaryDecoder: Decoder {
                         available -= 4
                     } else {
                         if available < 5 {
-                            throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                            throw BinaryDecodingError.malformedProtobuf
                         }
                         let c4 = start[4]
                         if c4 > 15 {
-                            throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                            throw BinaryDecodingError.malformedProtobuf
                         }
                         fieldNumber |= Int(c4 & 0x7f) << 25
                         p += 5
@@ -200,12 +200,12 @@ internal struct BinaryDecoder: Decoder {
                 } else {
                     // .endGroup when not in a group or for a different
                     // group is an invalid binary.
-                    throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                    throw BinaryDecodingError.malformedProtobuf
                 }
             }
             return fieldNumber
         }
-        throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+        throw BinaryDecodingError.malformedProtobuf
     }
 
     internal mutating func decodeSingularFloatField(value: inout Float) throws {
@@ -236,7 +236,7 @@ internal struct BinaryDecoder: Decoder {
                 let itemSize = UInt64(MemoryLayout<Float>.size)
                 let itemCount = bodyBytes / itemSize
                 if bodyBytes % itemSize != 0 || bodyBytes > available {
-                    throw SwiftProtobufError.BinaryDecoding.truncated()
+                    throw BinaryDecodingError.truncated
                 }
                 value.reserveCapacity(value.count + Int(truncatingIfNeeded: itemCount))
                 for _ in 1...itemCount {
@@ -277,7 +277,7 @@ internal struct BinaryDecoder: Decoder {
                 let itemSize = UInt64(MemoryLayout<Double>.size)
                 let itemCount = bodyBytes / itemSize
                 if bodyBytes % itemSize != 0 || bodyBytes > available {
-                    throw SwiftProtobufError.BinaryDecoding.truncated()
+                    throw BinaryDecodingError.truncated
                 }
                 value.reserveCapacity(value.count + Int(truncatingIfNeeded: itemCount))
                 for _ in 1...itemCount {
@@ -721,7 +721,7 @@ internal struct BinaryDecoder: Decoder {
             value = s
             consumed = true
         } else {
-            throw SwiftProtobufError.BinaryDecoding.invalidUTF8()
+            throw BinaryDecodingError.invalidUTF8
         }
     }
 
@@ -735,7 +735,7 @@ internal struct BinaryDecoder: Decoder {
             value = s
             consumed = true
         } else {
-            throw SwiftProtobufError.BinaryDecoding.invalidUTF8()
+            throw BinaryDecodingError.invalidUTF8
         }
     }
 
@@ -748,7 +748,7 @@ internal struct BinaryDecoder: Decoder {
                 value.append(s)
                 consumed = true
             } else {
-                throw SwiftProtobufError.BinaryDecoding.invalidUTF8()
+                throw BinaryDecodingError.invalidUTF8
             }
         default:
             return
@@ -890,7 +890,7 @@ internal struct BinaryDecoder: Decoder {
       try message.decodeMessage(decoder: &self)
       decrementRecursionDepth()
       guard complete else {
-          throw SwiftProtobufError.BinaryDecoding.trailingGarbage()
+          throw BinaryDecodingError.trailingGarbage
       }
       if let unknownData = unknownData {
         message.unknownFields.append(protobufData: unknownData)
@@ -935,7 +935,7 @@ internal struct BinaryDecoder: Decoder {
         subDecoder.unknownData = nil
         try group.decodeMessage(decoder: &subDecoder)
         guard subDecoder.fieldNumber == fieldNumber && subDecoder.fieldWireFormat == .endGroup else {
-            throw SwiftProtobufError.BinaryDecoding.truncated()
+            throw BinaryDecodingError.truncated
         }
         if let groupUnknowns = subDecoder.unknownData {
             group.unknownFields.append(protobufData: groupUnknowns)
@@ -958,7 +958,7 @@ internal struct BinaryDecoder: Decoder {
         var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self)
         while let tag = try subdecoder.getTag() {
             if tag.wireFormat == .endGroup {
-                throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                throw BinaryDecodingError.malformedProtobuf
             }
             let fieldNumber = tag.fieldNumber
             switch fieldNumber {
@@ -971,7 +971,7 @@ internal struct BinaryDecoder: Decoder {
             }
         }
         if !subdecoder.complete {
-            throw SwiftProtobufError.BinaryDecoding.trailingGarbage()
+            throw BinaryDecodingError.trailingGarbage
         }
         // A map<> definition can't provide a default value for the keys/values,
         // so it is safe to use the proto3 default to get the right
@@ -993,7 +993,7 @@ internal struct BinaryDecoder: Decoder {
         var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self)
         while let tag = try subdecoder.getTag() {
             if tag.wireFormat == .endGroup {
-                throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                throw BinaryDecodingError.malformedProtobuf
             }
             let fieldNumber = tag.fieldNumber
             switch fieldNumber {
@@ -1014,7 +1014,7 @@ internal struct BinaryDecoder: Decoder {
             }
         }
         if !subdecoder.complete {
-            throw SwiftProtobufError.BinaryDecoding.trailingGarbage()
+            throw BinaryDecodingError.trailingGarbage
         }
         // A map<> definition can't provide a default value for the keys, so it
         // is safe to use the proto3 default to get the right integer/string/bytes.
@@ -1033,7 +1033,7 @@ internal struct BinaryDecoder: Decoder {
         var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self)
         while let tag = try subdecoder.getTag() {
             if tag.wireFormat == .endGroup {
-                throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                throw BinaryDecodingError.malformedProtobuf
             }
             let fieldNumber = tag.fieldNumber
             switch fieldNumber {
@@ -1046,7 +1046,7 @@ internal struct BinaryDecoder: Decoder {
             }
         }
         if !subdecoder.complete {
-            throw SwiftProtobufError.BinaryDecoding.trailingGarbage()
+            throw BinaryDecodingError.trailingGarbage
         }
         // A map<> definition can't provide a default value for the keys, so it
         // is safe to use the proto3 default to get the right integer/string/bytes.
@@ -1090,7 +1090,7 @@ internal struct BinaryDecoder: Decoder {
                 // the bytes were consumed, then there should have been a
                 // field that consumed them (existing or created). This
                 // specific error result is to allow this to be more detectable.
-                throw SwiftProtobufError.BinaryDecoding.internalExtensionError()
+                throw BinaryDecodingError.internalExtensionError
             }
         }
     }
@@ -1125,7 +1125,7 @@ internal struct BinaryDecoder: Decoder {
               break
 
             case .malformed:
-                throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                throw BinaryDecodingError.malformedProtobuf
             }
 
             assert(recursionBudget == subDecoder.recursionBudget)
@@ -1256,7 +1256,7 @@ internal struct BinaryDecoder: Decoder {
             let _ = try decodeVarint()
         case .fixed64:
             if available < 8 {
-                throw SwiftProtobufError.BinaryDecoding.truncated()
+                throw BinaryDecodingError.truncated
             }
             p += 8
             available -= 8
@@ -1266,7 +1266,7 @@ internal struct BinaryDecoder: Decoder {
                 p += Int(n)
                 available -= Int(n)
             } else {
-                throw SwiftProtobufError.BinaryDecoding.truncated()
+                throw BinaryDecodingError.truncated
             }
         case .startGroup:
             try incrementRecursionDepth()
@@ -1279,20 +1279,20 @@ internal struct BinaryDecoder: Decoder {
                         } else {
                             // .endGroup for a something other than the current
                             // group is an invalid binary.
-                            throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                            throw BinaryDecodingError.malformedProtobuf
                         }
                     } else {
                         try skipOver(tag: innerTag)
                     }
                 } else {
-                    throw SwiftProtobufError.BinaryDecoding.truncated()
+                    throw BinaryDecodingError.truncated
                 }
             }
         case .endGroup:
-            throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+            throw BinaryDecodingError.truncated
         case .fixed32:
             if available < 4 {
-                throw SwiftProtobufError.BinaryDecoding.truncated()
+                throw BinaryDecodingError.truncated
             }
             p += 4
             available -= 4
@@ -1314,7 +1314,7 @@ internal struct BinaryDecoder: Decoder {
             available += p - fieldStartP
             p = fieldStartP
             guard let tag = try getTagWithoutUpdatingFieldStart() else {
-                throw SwiftProtobufError.BinaryDecoding.truncated()
+                throw BinaryDecodingError.truncated
             }
             try skipOver(tag: tag)
             fieldEndP = p
@@ -1324,7 +1324,7 @@ internal struct BinaryDecoder: Decoder {
     /// Private: Parse the next raw varint from the input.
     private mutating func decodeVarint() throws -> UInt64 {
         if available < 1 {
-            throw SwiftProtobufError.BinaryDecoding.truncated()
+            throw BinaryDecodingError.truncated
         }
         var start = p
         var length = available
@@ -1340,7 +1340,7 @@ internal struct BinaryDecoder: Decoder {
         var shift = UInt64(7)
         while true {
             if length < 1 || shift > 63 {
-                throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                throw BinaryDecodingError.malformedProtobuf
             }
             c = start.load(fromByteOffset: 0, as: UInt8.self)
             start += 1
@@ -1373,13 +1373,13 @@ internal struct BinaryDecoder: Decoder {
         let t = try decodeVarint()
         if t < UInt64(UInt32.max) {
             guard let tag = FieldTag(rawValue: UInt32(truncatingIfNeeded: t)) else {
-                throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+                throw BinaryDecodingError.malformedProtobuf
             }
             fieldWireFormat = tag.wireFormat
             fieldNumber = tag.fieldNumber
             return tag
         } else {
-            throw SwiftProtobufError.BinaryDecoding.malformedProtobuf()
+            throw BinaryDecodingError.malformedProtobuf
         }
     }
 
@@ -1394,7 +1394,7 @@ internal struct BinaryDecoder: Decoder {
     private mutating func decodeLittleEndianInteger<T: FixedWidthInteger>() throws -> T {
         let size = MemoryLayout<T>.size
         assert(size == 4 || size == 8)
-        guard available >= size else {throw SwiftProtobufError.BinaryDecoding.truncated()}
+        guard available >= size else {throw BinaryDecodingError.truncated}
         defer { consume(length: size) }
         return T(littleEndian: p.loadUnaligned(as: T.self))
     }
@@ -1428,7 +1428,7 @@ internal struct BinaryDecoder: Decoder {
         }
 
         guard length <= UInt64(available) else {
-            throw SwiftProtobufError.BinaryDecoding.truncated()
+            throw BinaryDecodingError.truncated
         }
 
         count = Int(length)

+ 0 - 1
Sources/SwiftProtobuf/BinaryDecodingError.swift

@@ -13,7 +13,6 @@
 // -----------------------------------------------------------------------------
 
 /// Describes errors that can occur when decoding a message from binary format.
-@available(*, deprecated, message: "This error type has been deprecated and won't be thrown anymore; it has been replaced by `SwiftProtobufError`.")
 public enum BinaryDecodingError: Error {
   /// Extraneous data remained after decoding should have been complete.
   case trailingGarbage

+ 6 - 7
Sources/SwiftProtobuf/BinaryDelimited.swift

@@ -19,7 +19,6 @@ import Foundation
 /// Helper methods for reading/writing messages with a length prefix.
 public enum BinaryDelimited {
   /// Additional errors for delimited message handing.
-  @available(*, deprecated, message: "This error type has been deprecated and won't be thrown anymore; it has been replaced by `SwiftProtobufError`.")
   public enum Error: Swift.Error {
     /// If a read/write to the stream fails, but the stream's `streamError` is nil,
     /// this error will be throw instead since the stream didn't provide anything
@@ -79,9 +78,9 @@ public enum BinaryDelimited {
         if let streamError = stream.streamError {
           throw streamError
         }
-        throw SwiftProtobufError.BinaryStreamDecoding.unknownStreamError()
+        throw BinaryDelimited.Error.unknownStreamError
       }
-      throw SwiftProtobufError.BinaryStreamDecoding.truncated()
+      throw BinaryDelimited.Error.truncated
     }
   }
 
@@ -186,11 +185,11 @@ public enum BinaryDelimited {
         if let streamError = stream.streamError {
           throw streamError
         }
-        throw SwiftProtobufError.BinaryStreamDecoding.unknownStreamError()
+        throw BinaryDelimited.Error.unknownStreamError
       }
       if bytesRead == 0 {
         // Hit the end of the stream
-        throw SwiftProtobufError.BinaryStreamDecoding.truncated()
+        throw BinaryDelimited.Error.truncated
       }
       if bytesRead < chunk.count {
         data += chunk[0..<bytesRead]
@@ -230,7 +229,7 @@ internal func decodeVarint(_ stream: InputStream) throws -> UInt64 {
       if let streamError = stream.streamError {
         throw streamError
       }
-      throw SwiftProtobufError.BinaryStreamDecoding.unknownStreamError()
+      throw BinaryDelimited.Error.unknownStreamError
     }
   }
 
@@ -241,7 +240,7 @@ internal func decodeVarint(_ stream: InputStream) throws -> UInt64 {
       if shift == 0 {
         throw SwiftProtobufError.BinaryStreamDecoding.noBytesAvailable()
       }
-      throw SwiftProtobufError.BinaryStreamDecoding.truncated()
+      throw BinaryDelimited.Error.truncated
     }
     value |= UInt64(c & 0x7f) << shift
     if c & 0x80 == 0 {

+ 0 - 1
Sources/SwiftProtobuf/BinaryEncodingError.swift

@@ -13,7 +13,6 @@
 // -----------------------------------------------------------------------------
 
 /// Describes errors that can occur when decoding a message from binary format.
-@available(*, deprecated, message: "This error type has been deprecated and won't be thrown anymore; it has been replaced by `SwiftProtobufError`.")
 public enum BinaryEncodingError: Error, Hashable {
   /// An unexpected failure when deserializing a `Google_Protobuf_Any`.
   case anyTranscodeFailure

+ 2 - 2
Sources/SwiftProtobuf/Google_Protobuf_Any+Extensions.swift

@@ -43,7 +43,7 @@ extension Google_Protobuf_Any {
     typePrefix: String = defaultAnyTypeURLPrefix
   ) throws {
     if !partial && !message.isInitialized {
-      throw SwiftProtobufError.BinaryEncoding.missingRequiredFields()
+      throw BinaryEncodingError.missingRequiredFields
     }
     self.init()
     typeURL = buildTypeURL(forMessage:message, typePrefix: typePrefix)
@@ -78,7 +78,7 @@ extension Google_Protobuf_Any {
               extensions: extensions)
             try decodeTextFormat(decoder: &textDecoder)
             if !textDecoder.complete {
-              throw SwiftProtobufError.TextFormatDecoding.trailingGarbage()
+              throw TextFormatDecodingError.trailingGarbage
             }
           }
         }

+ 9 - 9
Sources/SwiftProtobuf/Google_Protobuf_Duration+Extensions.swift

@@ -32,7 +32,7 @@ private func parseDuration(text: String) throws -> (Int64, Int32) {
     case "-":
       // Only accept '-' as very first character
       if total > 0 {
-        throw SwiftProtobufError.JSONDecoding.malformedDuration()
+        throw JSONDecodingError.malformedDuration
       }
       digits.append(c)
       isNegative = true
@@ -41,14 +41,14 @@ private func parseDuration(text: String) throws -> (Int64, Int32) {
       digitCount += 1
     case ".":
       if let _ = seconds {
-        throw SwiftProtobufError.JSONDecoding.malformedDuration()
+        throw JSONDecodingError.malformedDuration
       }
       let digitString = String(digits)
       if let s = Int64(digitString),
          s >= minDurationSeconds && s <= maxDurationSeconds {
         seconds = s
       } else {
-        throw SwiftProtobufError.JSONDecoding.malformedDuration()
+        throw JSONDecodingError.malformedDuration
       }
       digits.removeAll()
       digitCount = 0
@@ -71,7 +71,7 @@ private func parseDuration(text: String) throws -> (Int64, Int32) {
             nanos = rawNanos
           }
         } else {
-          throw SwiftProtobufError.JSONDecoding.malformedDuration()
+          throw JSONDecodingError.malformedDuration
         }
       } else {
         // No fraction, we just have an integral number of seconds
@@ -80,20 +80,20 @@ private func parseDuration(text: String) throws -> (Int64, Int32) {
            s >= minDurationSeconds && s <= maxDurationSeconds {
           seconds = s
         } else {
-          throw SwiftProtobufError.JSONDecoding.malformedDuration()
+          throw JSONDecodingError.malformedDuration
         }
       }
       // Fail if there are characters after 's'
       if chars.next() != nil {
-        throw SwiftProtobufError.JSONDecoding.malformedDuration()
+        throw JSONDecodingError.malformedDuration
       }
       return (seconds!, nanos)
     default:
-      throw SwiftProtobufError.JSONDecoding.malformedDuration()
+      throw JSONDecodingError.malformedDuration
     }
     total += 1
   }
-  throw SwiftProtobufError.JSONDecoding.malformedDuration()
+  throw JSONDecodingError.malformedDuration
 }
 
 private func formatDuration(seconds: Int64, nanos: Int32) -> String? {
@@ -130,7 +130,7 @@ extension Google_Protobuf_Duration: _CustomJSONCodable {
     if let formatted = formatDuration(seconds: seconds, nanos: nanos) {
       return "\"\(formatted)\""
     } else {
-      throw SwiftProtobufError.JSONEncoding.durationRange()
+      throw JSONEncodingError.durationRange
     }
   }
 }

+ 2 - 2
Sources/SwiftProtobuf/Google_Protobuf_FieldMask+Extensions.swift

@@ -166,7 +166,7 @@ extension Google_Protobuf_FieldMask: _CustomJSONCodable {
     if let names = parseJSONFieldNames(names: s) {
       paths = names
     } else {
-      throw SwiftProtobufError.JSONDecoding.malformedFieldMask()
+      throw JSONDecodingError.malformedFieldMask
     }
   }
 
@@ -178,7 +178,7 @@ extension Google_Protobuf_FieldMask: _CustomJSONCodable {
       if let jsonPath = ProtoToJSON(name: p) {
         jsonPaths.append(jsonPath)
       } else {
-        throw SwiftProtobufError.JSONEncoding.fieldMaskConversion()
+        throw JSONEncodingError.fieldMaskConversion
       }
     }
     return "\"" + jsonPaths.joined(separator: ",") + "\""

+ 16 - 16
Sources/SwiftProtobuf/Google_Protobuf_Timestamp+Extensions.swift

@@ -29,7 +29,7 @@ private func parseTimestamp(s: String) throws -> (Int64, Int32) {
   // Convert to an array of integer character values
   let value = s.utf8.map{Int($0)}
   if value.count < 20 {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
   // Since the format is fixed-layout, we can just decode
   // directly as follows.
@@ -44,7 +44,7 @@ private func parseTimestamp(s: String) throws -> (Int64, Int32) {
 
   func fromAscii2(_ digit0: Int, _ digit1: Int) throws -> Int {
     if digit0 < zero || digit0 > nine || digit1 < zero || digit1 > nine {
-      throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+      throw JSONDecodingError.malformedTimestamp
     }
     return digit0 * 10 + digit1 - 528
   }
@@ -59,7 +59,7 @@ private func parseTimestamp(s: String) throws -> (Int64, Int32) {
       || digit1 < zero || digit1 > nine
       || digit2 < zero || digit2 > nine
       || digit3 < zero || digit3 > nine) {
-      throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+      throw JSONDecodingError.malformedTimestamp
     }
     return digit0 * 1000 + digit1 * 100 + digit2 * 10 + digit3 - 53328
   }
@@ -67,37 +67,37 @@ private func parseTimestamp(s: String) throws -> (Int64, Int32) {
   // Year: 4 digits followed by '-'
   let year = try fromAscii4(value[0], value[1], value[2], value[3])
   if value[4] != dash || year < Int(1) || year > Int(9999) {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
 
   // Month: 2 digits followed by '-'
   let month = try fromAscii2(value[5], value[6])
   if value[7] != dash || month < Int(1) || month > Int(12) {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
 
   // Day: 2 digits followed by 'T'
   let mday = try fromAscii2(value[8], value[9])
   if value[10] != letterT || mday < Int(1) || mday > Int(31) {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
 
   // Hour: 2 digits followed by ':'
   let hour = try fromAscii2(value[11], value[12])
   if value[13] != colon || hour > Int(23) {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
 
   // Minute: 2 digits followed by ':'
   let minute = try fromAscii2(value[14], value[15])
   if value[16] != colon || minute > Int(59) {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
 
   // Second: 2 digits (following char is checked below)
   let second = try fromAscii2(value[17], value[18])
   if second > Int(61) {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
 
   // timegm() is almost entirely useless.  It's nonexistent on
@@ -149,15 +149,15 @@ private func parseTimestamp(s: String) throws -> (Int64, Int32) {
   var seconds: Int64 = 0
   // "Z" or "+" or "-" starts Timezone offset
   if pos >= value.count {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   } else if value[pos] == plus || value[pos] == dash {
     if pos + 6 > value.count {
-      throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+      throw JSONDecodingError.malformedTimestamp
     }
     let hourOffset = try fromAscii2(value[pos + 1], value[pos + 2])
     let minuteOffset = try fromAscii2(value[pos + 4], value[pos + 5])
     if hourOffset > Int(13) || minuteOffset > Int(59) || value[pos + 3] != colon {
-      throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+      throw JSONDecodingError.malformedTimestamp
     }
     var adjusted: Int64 = t
     if value[pos] == plus {
@@ -168,7 +168,7 @@ private func parseTimestamp(s: String) throws -> (Int64, Int32) {
       adjusted += Int64(minuteOffset) * Int64(60)
     }
     if adjusted < minTimestampSeconds || adjusted > maxTimestampSeconds {
-      throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+      throw JSONDecodingError.malformedTimestamp
     }
     seconds = adjusted
     pos += 6
@@ -176,10 +176,10 @@ private func parseTimestamp(s: String) throws -> (Int64, Int32) {
     seconds = t
     pos += 1
   } else {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
   if pos != value.count {
-    throw SwiftProtobufError.JSONDecoding.malformedTimestamp()
+    throw JSONDecodingError.malformedTimestamp
   }
   return (seconds, nanos)
 }
@@ -223,7 +223,7 @@ extension Google_Protobuf_Timestamp: _CustomJSONCodable {
     if let formatted = formatTimestamp(seconds: seconds, nanos: nanos) {
       return "\"\(formatted)\""
     } else {
-      throw SwiftProtobufError.JSONEncoding.timestampRange()
+      throw JSONEncodingError.timestampRange
     }
   }
 }

+ 3 - 3
Sources/SwiftProtobuf/Google_Protobuf_Value+Extensions.swift

@@ -80,7 +80,7 @@ extension Google_Protobuf_Value: _CustomJSONCodable {
     switch c {
     case "n":
       if !decoder.scanner.skipOptionalNull() {
-        throw SwiftProtobufError.JSONDecoding.failure()
+        throw JSONDecodingError.failure
       }
       kind = .nullValue(.nullValue)
     case "[":
@@ -154,14 +154,14 @@ extension Google_Protobuf_Value {
     case .nullValue?: encoder.putNullValue()
     case .numberValue(let v)?:
       guard v.isFinite else {
-        throw SwiftProtobufError.JSONEncoding.valueNumberNotFinite()
+        throw JSONEncodingError.valueNumberNotFinite
       }
       encoder.putDoubleValue(value: v)
     case .stringValue(let v)?: encoder.putStringValue(value: v)
     case .boolValue(let v)?: encoder.putNonQuotedBoolValue(value: v)
     case .structValue(let v)?: encoder.append(text: try v.jsonString(options: options))
     case .listValue(let v)?: encoder.append(text: try v.jsonString(options: options))
-    case nil: throw SwiftProtobufError.JSONEncoding.missingValue()
+    case nil: throw JSONEncodingError.missingValue
     }
   }
 }

+ 16 - 16
Sources/SwiftProtobuf/JSONDecoder.swift

@@ -26,7 +26,7 @@ internal struct JSONDecoder: Decoder {
   }
 
   mutating func handleConflictingOneOf() throws {
-    throw SwiftProtobufError.JSONDecoding.conflictingOneOf()
+    throw JSONDecodingError.conflictingOneOf
   }
 
   internal init(source: UnsafeRawBufferPointer, options: JSONDecodingOptions,
@@ -133,7 +133,7 @@ internal struct JSONDecoder: Decoder {
     }
     let n = try scanner.nextSInt()
     if n > Int64(Int32.max) || n < Int64(Int32.min) {
-      throw SwiftProtobufError.JSONDecoding.numberRange()
+      throw JSONDecodingError.numberRange
     }
     value = Int32(truncatingIfNeeded: n)
   }
@@ -145,7 +145,7 @@ internal struct JSONDecoder: Decoder {
     }
     let n = try scanner.nextSInt()
     if n > Int64(Int32.max) || n < Int64(Int32.min) {
-      throw SwiftProtobufError.JSONDecoding.numberRange()
+      throw JSONDecodingError.numberRange
     }
     value = Int32(truncatingIfNeeded: n)
   }
@@ -161,7 +161,7 @@ internal struct JSONDecoder: Decoder {
     while true {
       let n = try scanner.nextSInt()
       if n > Int64(Int32.max) || n < Int64(Int32.min) {
-        throw SwiftProtobufError.JSONDecoding.numberRange()
+        throw JSONDecodingError.numberRange
       }
       value.append(Int32(truncatingIfNeeded: n))
       if scanner.skipOptionalArrayEnd() {
@@ -212,7 +212,7 @@ internal struct JSONDecoder: Decoder {
     }
     let n = try scanner.nextUInt()
     if n > UInt64(UInt32.max) {
-      throw SwiftProtobufError.JSONDecoding.numberRange()
+      throw JSONDecodingError.numberRange
     }
     value = UInt32(truncatingIfNeeded: n)
   }
@@ -224,7 +224,7 @@ internal struct JSONDecoder: Decoder {
     }
     let n = try scanner.nextUInt()
     if n > UInt64(UInt32.max) {
-      throw SwiftProtobufError.JSONDecoding.numberRange()
+      throw JSONDecodingError.numberRange
     }
     value = UInt32(truncatingIfNeeded: n)
   }
@@ -240,7 +240,7 @@ internal struct JSONDecoder: Decoder {
     while true {
       let n = try scanner.nextUInt()
       if n > UInt64(UInt32.max) {
-        throw SwiftProtobufError.JSONDecoding.numberRange()
+        throw JSONDecodingError.numberRange
       }
       value.append(UInt32(truncatingIfNeeded: n))
       if scanner.skipOptionalArrayEnd() {
@@ -514,7 +514,7 @@ internal struct JSONDecoder: Decoder {
           let e = try customDecodable.decodedFromJSONNull() as! E
           value.append(e)
         } else {
-          throw SwiftProtobufError.JSONDecoding.illegalNull()
+          throw JSONDecodingError.illegalNull
         }
       } else {
         if let e: E = try scanner.nextEnumValue() {
@@ -530,7 +530,7 @@ internal struct JSONDecoder: Decoder {
 
   internal mutating func decodeFullObject<M: Message>(message: inout M) throws {
     guard let nameProviding = (M.self as? any _ProtoNameProviding.Type) else {
-      throw SwiftProtobufError.JSONDecoding.missingFieldNames()
+      throw JSONDecodingError.missingFieldNames
     }
     fieldNameMap = nameProviding._protobuf_nameMap
     if let m = message as? (any _CustomJSONCodable) {
@@ -587,7 +587,7 @@ internal struct JSONDecoder: Decoder {
           }
         }
         if !appended {
-          throw SwiftProtobufError.JSONDecoding.illegalNull()
+          throw JSONDecodingError.illegalNull
         }
       } else {
         var message = M()
@@ -628,7 +628,7 @@ internal struct JSONDecoder: Decoder {
       // map keys must always be quoted strings.
       let c = try scanner.peekOneCharacter()
       if c != "\"" {
-        throw SwiftProtobufError.JSONDecoding.unquotedMapKey()
+        throw JSONDecodingError.unquotedMapKey
       }
       isMapKey = true
       var keyField: KeyType.BaseType?
@@ -640,7 +640,7 @@ internal struct JSONDecoder: Decoder {
       if let keyField = keyField, let valueField = valueField {
         value[keyField] = valueField
       } else {
-        throw SwiftProtobufError.JSONDecoding.malformedMap()
+        throw JSONDecodingError.malformedMap
       }
       if scanner.skipOptionalObjectEnd() {
         return
@@ -665,13 +665,13 @@ internal struct JSONDecoder: Decoder {
       // map keys must always be quoted strings.
       let c = try scanner.peekOneCharacter()
       if c != "\"" {
-        throw SwiftProtobufError.JSONDecoding.unquotedMapKey()
+        throw JSONDecodingError.unquotedMapKey
       }
       isMapKey = true
       var keyFieldOpt: KeyType.BaseType?
       try KeyType.decodeSingular(value: &keyFieldOpt, from: &self)
       guard let keyField = keyFieldOpt else {
-        throw SwiftProtobufError.JSONDecoding.malformedMap()
+        throw JSONDecodingError.malformedMap
       }
       isMapKey = false
       try scanner.skipRequiredColon()
@@ -707,7 +707,7 @@ internal struct JSONDecoder: Decoder {
       // map keys must always be quoted strings.
       let c = try scanner.peekOneCharacter()
       if c != "\"" {
-        throw SwiftProtobufError.JSONDecoding.unquotedMapKey()
+        throw JSONDecodingError.unquotedMapKey
       }
       isMapKey = true
       var keyField: KeyType.BaseType?
@@ -719,7 +719,7 @@ internal struct JSONDecoder: Decoder {
       if let keyField = keyField, let valueField = valueField {
         value[keyField] = valueField
       } else {
-        throw SwiftProtobufError.JSONDecoding.malformedMap()
+        throw JSONDecodingError.malformedMap
       }
       if scanner.skipOptionalObjectEnd() {
         return

+ 0 - 1
Sources/SwiftProtobuf/JSONDecodingError.swift

@@ -12,7 +12,6 @@
 ///
 // -----------------------------------------------------------------------------
 
-@available(*, deprecated, message: "This error type has been deprecated and won't be thrown anymore; it has been replaced by `SwiftProtobufError`.")
 public enum JSONDecodingError: Error {
     /// Something was wrong
     case failure

+ 0 - 1
Sources/SwiftProtobuf/JSONEncodingError.swift

@@ -12,7 +12,6 @@
 ///
 // -----------------------------------------------------------------------------
 
-@available(*, deprecated, message: "This error type has been deprecated and won't be thrown anymore; it has been replaced by `SwiftProtobufError`.")
 public enum JSONEncodingError: Error, Hashable {
     /// Any fields that were decoded from binary format cannot be
     /// re-encoded into JSON unless the object they hold is a

+ 4 - 4
Sources/SwiftProtobuf/JSONEncodingVisitor.swift

@@ -38,7 +38,7 @@ internal struct JSONEncodingVisitor: Visitor {
     if let nameProviding = type as? any _ProtoNameProviding.Type {
       self.nameMap = nameProviding._protobuf_nameMap
     } else {
-      throw SwiftProtobufError.JSONEncoding.missingFieldNames()
+      throw JSONEncodingError.missingFieldNames
     }
     self.options = options
   }
@@ -186,7 +186,7 @@ internal struct JSONEncodingVisitor: Visitor {
       self.nameMap = oldNameMap
       self.extensions = oldExtensions
     } else {
-      throw SwiftProtobufError.JSONEncoding.missingFieldNames()
+      throw JSONEncodingError.missingFieldNames
     }
   }
 
@@ -345,7 +345,7 @@ internal struct JSONEncodingVisitor: Visitor {
       self.nameMap = oldNameMap
       self.extensions = oldExtensions
     } else {
-      throw SwiftProtobufError.JSONEncoding.missingFieldNames()
+      throw JSONEncodingError.missingFieldNames
     }
     encoder.endArray()
   }
@@ -421,7 +421,7 @@ internal struct JSONEncodingVisitor: Visitor {
     } else if let name = extensions?[number]?.protobufExtension.fieldName {
         encoder.startExtensionField(name: name)
     } else {
-      throw SwiftProtobufError.JSONEncoding.missingFieldNames()
+      throw JSONEncodingError.missingFieldNames
     }
   }
 }

+ 80 - 80
Sources/SwiftProtobuf/JSONScanner.swift

@@ -122,7 +122,7 @@ private func parseBytes(
 ) throws -> Data {
     let c = source[index]
     if c != asciiDoubleQuote {
-      throw SwiftProtobufError.JSONDecoding.malformedString()
+      throw JSONDecodingError.malformedString
     }
     source.formIndex(after: &index)
 
@@ -142,7 +142,7 @@ private func parseBytes(
         if digit == asciiBackslash {
             source.formIndex(after: &index)
             if index == end {
-              throw SwiftProtobufError.JSONDecoding.malformedString()
+              throw JSONDecodingError.malformedString
             }
             let escaped = source[index]
             switch escaped {
@@ -150,12 +150,12 @@ private func parseBytes(
                 // TODO: Parse hex escapes such as \u0041.  Note that
                 // such escapes are going to be extremely rare, so
                 // there's little point in optimizing for them.
-              throw SwiftProtobufError.JSONDecoding.malformedString()
+              throw JSONDecodingError.malformedString
             case asciiForwardSlash:
                 digit = escaped
             default:
                 // Reject \b \f \n \r \t \" or \\ and all illegal escapes
-              throw SwiftProtobufError.JSONDecoding.malformedString()
+              throw JSONDecodingError.malformedString
             }
         }
 
@@ -173,11 +173,11 @@ private func parseBytes(
 
     // We reached the end without seeing the close quote
     if index == end {
-      throw SwiftProtobufError.JSONDecoding.malformedString()
+      throw JSONDecodingError.malformedString
     }
     // Reject mixed encodings.
     if sawSection4Characters && sawSection5Characters {
-      throw SwiftProtobufError.JSONDecoding.malformedString()
+      throw JSONDecodingError.malformedString
     }
 
     // Allocate a Data object of exactly the right size
@@ -211,7 +211,7 @@ private func parseBytes(
                     default:
                         // Note: Invalid backslash escapes were caught
                         // above; we should never get here.
-                        throw SwiftProtobufError.JSONDecoding.malformedString()
+                        throw JSONDecodingError.malformedString
                     }
                 case asciiSpace:
                     source.formIndex(after: &index)
@@ -226,12 +226,12 @@ private func parseBytes(
                         case 61:
                             padding += 1
                         default: // Only '=' and whitespace permitted
-                            throw SwiftProtobufError.JSONDecoding.malformedString()
+                            throw JSONDecodingError.malformedString
                         }
                         source.formIndex(after: &index)
                     }
                 default:
-                    throw SwiftProtobufError.JSONDecoding.malformedString()
+                    throw JSONDecodingError.malformedString
                 }
             }
             n <<= 6
@@ -266,7 +266,7 @@ private func parseBytes(
         default:
             break
         }
-        throw SwiftProtobufError.JSONDecoding.malformedString()
+        throw JSONDecodingError.malformedString
       }
     }
     source.formIndex(after: &index)
@@ -412,7 +412,7 @@ internal struct JSONScanner {
   internal mutating func incrementRecursionDepth() throws {
     recursionBudget -= 1
     if recursionBudget < 0 {
-      throw SwiftProtobufError.JSONDecoding.messageDepthLimit()
+      throw JSONDecodingError.messageDepthLimit
     }
   }
 
@@ -449,7 +449,7 @@ internal struct JSONScanner {
   internal mutating func peekOneCharacter() throws -> Character {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     return Character(UnicodeScalar(UInt32(currentByte))!)
   }
@@ -487,7 +487,7 @@ internal struct JSONScanner {
     end: UnsafeRawBufferPointer.Index
   ) throws -> UInt64? {
     if index == end {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let start = index
     let c = source[index]
@@ -499,7 +499,7 @@ internal struct JSONScanner {
         switch after {
         case asciiZero...asciiNine: // 0...9
           // leading '0' forbidden unless it is the only digit
-          throw SwiftProtobufError.JSONDecoding.leadingZero()
+          throw JSONDecodingError.leadingZero
         case asciiPeriod, asciiLowerE, asciiUpperE: // . e
           // Slow path: JSON numbers can be written in floating-point notation
           index = start
@@ -510,7 +510,7 @@ internal struct JSONScanner {
               return u
             }
           }
-          throw SwiftProtobufError.JSONDecoding.malformedNumber()
+          throw JSONDecodingError.malformedNumber
         case asciiBackslash:
           return nil
         default:
@@ -526,7 +526,7 @@ internal struct JSONScanner {
         case asciiZero...asciiNine: // 0...9
           let val = UInt64(digit - asciiZero)
           if n > UInt64.max / 10 || n * 10 > UInt64.max - val {
-            throw SwiftProtobufError.JSONDecoding.numberRange()
+            throw JSONDecodingError.numberRange
           }
           source.formIndex(after: &index)
           n = n * 10 + val
@@ -540,7 +540,7 @@ internal struct JSONScanner {
               return u
             }
           }
-          throw SwiftProtobufError.JSONDecoding.malformedNumber()
+          throw JSONDecodingError.malformedNumber
         case asciiBackslash:
           return nil
         default:
@@ -551,7 +551,7 @@ internal struct JSONScanner {
     case asciiBackslash:
       return nil
     default:
-      throw SwiftProtobufError.JSONDecoding.malformedNumber()
+      throw JSONDecodingError.malformedNumber
     }
   }
 
@@ -572,25 +572,25 @@ internal struct JSONScanner {
     end: UnsafeRawBufferPointer.Index
   ) throws -> Int64? {
     if index == end {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let c = source[index]
     if c == asciiMinus { // -
       source.formIndex(after: &index)
       if index == end {
-        throw SwiftProtobufError.JSONDecoding.truncated()
+        throw JSONDecodingError.truncated
       }
       // character after '-' must be digit
       let digit = source[index]
       if digit < asciiZero || digit > asciiNine {
-        throw SwiftProtobufError.JSONDecoding.malformedNumber()
+        throw JSONDecodingError.malformedNumber
       }
       if let n = try parseBareUInt64(source: source, index: &index, end: end) {
         let limit: UInt64 = 0x8000000000000000 // -Int64.min
         if n >= limit {
           if n > limit {
             // Too large negative number
-            throw SwiftProtobufError.JSONDecoding.numberRange()
+            throw JSONDecodingError.numberRange
           } else {
             return Int64.min // Special case for Int64.min
           }
@@ -601,7 +601,7 @@ internal struct JSONScanner {
       }
     } else if let n = try parseBareUInt64(source: source, index: &index, end: end) {
       if n > UInt64(bitPattern: Int64.max) {
-        throw SwiftProtobufError.JSONDecoding.numberRange()
+        throw JSONDecodingError.numberRange
       }
       return Int64(bitPattern: n)
     } else {
@@ -628,7 +628,7 @@ internal struct JSONScanner {
     // RFC 7159 defines the grammar for JSON numbers as:
     // number = [ minus ] int [ frac ] [ exp ]
     if index == end {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let start = index
     var c = source[index]
@@ -641,7 +641,7 @@ internal struct JSONScanner {
       source.formIndex(after: &index)
       if index == end {
         index = start
-        throw SwiftProtobufError.JSONDecoding.truncated()
+        throw JSONDecodingError.truncated
       }
       c = source[index]
       if c == asciiBackslash {
@@ -671,7 +671,7 @@ internal struct JSONScanner {
         return nil
       }
       if c >= asciiZero && c <= asciiNine {
-        throw SwiftProtobufError.JSONDecoding.leadingZero()
+          throw JSONDecodingError.leadingZero
       }
     case asciiOne...asciiNine:
       while c >= asciiZero && c <= asciiNine {
@@ -680,7 +680,7 @@ internal struct JSONScanner {
           if let d = numberParser.utf8ToDouble(bytes: source, start: start, end: index) {
             return d
           } else {
-            throw SwiftProtobufError.JSONDecoding.invalidUTF8()
+            throw JSONDecodingError.invalidUTF8
           }
         }
         c = source[index]
@@ -690,7 +690,7 @@ internal struct JSONScanner {
       }
     default:
       // Integer part cannot be empty
-      throw SwiftProtobufError.JSONDecoding.malformedNumber()
+      throw JSONDecodingError.malformedNumber
     }
 
     // frac = decimal-point 1*DIGIT
@@ -698,7 +698,7 @@ internal struct JSONScanner {
       source.formIndex(after: &index)
       if index == end {
         // decimal point must have a following digit
-        throw SwiftProtobufError.JSONDecoding.truncated()
+        throw JSONDecodingError.truncated
       }
       c = source[index]
       switch c {
@@ -709,7 +709,7 @@ internal struct JSONScanner {
             if let d = numberParser.utf8ToDouble(bytes: source, start: start, end: index) {
               return d
             } else {
-              throw SwiftProtobufError.JSONDecoding.invalidUTF8()
+              throw JSONDecodingError.invalidUTF8
             }
           }
           c = source[index]
@@ -721,7 +721,7 @@ internal struct JSONScanner {
         return nil
       default:
         // decimal point must be followed by at least one digit
-        throw SwiftProtobufError.JSONDecoding.malformedNumber()
+        throw JSONDecodingError.malformedNumber
       }
     }
 
@@ -730,7 +730,7 @@ internal struct JSONScanner {
       source.formIndex(after: &index)
       if index == end {
         // "e" must be followed by +,-, or digit
-        throw SwiftProtobufError.JSONDecoding.truncated()
+        throw JSONDecodingError.truncated
       }
       c = source[index]
       if c == asciiBackslash {
@@ -740,7 +740,7 @@ internal struct JSONScanner {
         source.formIndex(after: &index)
         if index == end {
           // must be at least one digit in exponent
-          throw SwiftProtobufError.JSONDecoding.truncated()
+          throw JSONDecodingError.truncated
         }
         c = source[index]
         if c == asciiBackslash {
@@ -755,7 +755,7 @@ internal struct JSONScanner {
             if let d = numberParser.utf8ToDouble(bytes: source, start: start, end: index) {
               return d
             } else {
-              throw SwiftProtobufError.JSONDecoding.invalidUTF8()
+              throw JSONDecodingError.invalidUTF8
             }
           }
           c = source[index]
@@ -765,13 +765,13 @@ internal struct JSONScanner {
         }
       default:
         // must be at least one digit in exponent
-        throw SwiftProtobufError.JSONDecoding.malformedNumber()
+        throw JSONDecodingError.malformedNumber
       }
     }
     if let d = numberParser.utf8ToDouble(bytes: source, start: start, end: index) {
       return d
     } else {
-      throw SwiftProtobufError.JSONDecoding.invalidUTF8()
+      throw JSONDecodingError.invalidUTF8
     }
   }
 
@@ -822,7 +822,7 @@ internal struct JSONScanner {
   internal mutating func nextUInt() throws -> UInt64 {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let c = currentByte
     if c == asciiDoubleQuote {
@@ -832,10 +832,10 @@ internal struct JSONScanner {
                                      index: &index,
                                      end: source.endIndex) {
         guard hasMoreContent else {
-          throw SwiftProtobufError.JSONDecoding.truncated()
+          throw JSONDecodingError.truncated
         }
         if currentByte != asciiDoubleQuote {
-          throw SwiftProtobufError.JSONDecoding.malformedNumber()
+          throw JSONDecodingError.malformedNumber
         }
         advance()
         return u
@@ -870,7 +870,7 @@ internal struct JSONScanner {
                                           end: source.endIndex) {
       return u
     }
-    throw SwiftProtobufError.JSONDecoding.malformedNumber()
+    throw JSONDecodingError.malformedNumber
   }
 
   /// Parse a signed integer, quoted or not, including handling
@@ -882,7 +882,7 @@ internal struct JSONScanner {
   internal mutating func nextSInt() throws -> Int64 {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let c = currentByte
     if c == asciiDoubleQuote {
@@ -892,10 +892,10 @@ internal struct JSONScanner {
                                      index: &index,
                                      end: source.endIndex) {
         guard hasMoreContent else {
-          throw SwiftProtobufError.JSONDecoding.truncated()
+          throw JSONDecodingError.truncated
         }
         if currentByte != asciiDoubleQuote {
-          throw SwiftProtobufError.JSONDecoding.malformedNumber()
+          throw JSONDecodingError.malformedNumber
         }
         advance()
         return s
@@ -930,7 +930,7 @@ internal struct JSONScanner {
                                           end: source.endIndex) {
       return s
     }
-    throw SwiftProtobufError.JSONDecoding.malformedNumber()
+    throw JSONDecodingError.malformedNumber
   }
 
   /// Parse the next Float value, regardless of whether it
@@ -939,7 +939,7 @@ internal struct JSONScanner {
   internal mutating func nextFloat() throws -> Float {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let c = currentByte
     if c == asciiDoubleQuote { // "
@@ -949,10 +949,10 @@ internal struct JSONScanner {
                                      index: &index,
                                      end: source.endIndex) {
         guard hasMoreContent else {
-          throw SwiftProtobufError.JSONDecoding.truncated()
+          throw JSONDecodingError.truncated
         }
         if currentByte != asciiDoubleQuote {
-          throw SwiftProtobufError.JSONDecoding.malformedNumber()
+          throw JSONDecodingError.malformedNumber
         }
         advance()
         return Float(d)
@@ -1002,7 +1002,7 @@ internal struct JSONScanner {
         }
       }
     }
-    throw SwiftProtobufError.JSONDecoding.malformedNumber()
+    throw JSONDecodingError.malformedNumber
   }
 
   /// Parse the next Double value, regardless of whether it
@@ -1011,7 +1011,7 @@ internal struct JSONScanner {
   internal mutating func nextDouble() throws -> Double {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let c = currentByte
     if c == asciiDoubleQuote { // "
@@ -1021,10 +1021,10 @@ internal struct JSONScanner {
                                      index: &index,
                                      end: source.endIndex) {
         guard hasMoreContent else {
-          throw SwiftProtobufError.JSONDecoding.truncated()
+          throw JSONDecodingError.truncated
         }
         if currentByte != asciiDoubleQuote {
-          throw SwiftProtobufError.JSONDecoding.malformedNumber()
+          throw JSONDecodingError.malformedNumber
         }
         advance()
         return d
@@ -1070,7 +1070,7 @@ internal struct JSONScanner {
         return d
       }
     }
-    throw SwiftProtobufError.JSONDecoding.malformedNumber()
+    throw JSONDecodingError.malformedNumber
   }
 
   /// Return the contents of the following quoted string,
@@ -1078,16 +1078,16 @@ internal struct JSONScanner {
   internal mutating func nextQuotedString() throws -> String {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let c = currentByte
     if c != asciiDoubleQuote {
-      throw SwiftProtobufError.JSONDecoding.malformedString()
+      throw JSONDecodingError.malformedString
     }
     if let s = parseOptionalQuotedString() {
       return s
     } else {
-      throw SwiftProtobufError.JSONDecoding.malformedString()
+      throw JSONDecodingError.malformedString
     }
   }
 
@@ -1121,7 +1121,7 @@ internal struct JSONScanner {
   internal mutating func nextBytesValue() throws -> Data {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     return try parseBytes(source: source, index: &index, end: source.endIndex)
   }
@@ -1169,7 +1169,7 @@ internal struct JSONScanner {
   internal mutating func nextBool() throws -> Bool {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let c = currentByte
     switch c {
@@ -1188,7 +1188,7 @@ internal struct JSONScanner {
     default:
       break
     }
-    throw SwiftProtobufError.JSONDecoding.malformedBool()
+    throw JSONDecodingError.malformedBool
   }
 
   /// Return the following Bool "true" or "false", including
@@ -1197,10 +1197,10 @@ internal struct JSONScanner {
   internal mutating func nextQuotedBool() throws -> Bool {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     if currentByte != asciiDoubleQuote {
-      throw SwiftProtobufError.JSONDecoding.unquotedMapKey()
+      throw JSONDecodingError.unquotedMapKey
     }
     if let s = parseOptionalQuotedString() {
       switch s {
@@ -1209,7 +1209,7 @@ internal struct JSONScanner {
       default: break
       }
     }
-    throw SwiftProtobufError.JSONDecoding.malformedBool()
+      throw JSONDecodingError.malformedBool
   }
 
   /// Returns pointer/count spanning the UTF8 bytes of the next regular
@@ -1219,7 +1219,7 @@ internal struct JSONScanner {
     skipWhitespace()
     let stringStart = index
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     if currentByte != asciiDoubleQuote {
       return nil
@@ -1234,7 +1234,7 @@ internal struct JSONScanner {
       advance()
     }
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let buff = UnsafeRawBufferPointer(
       start: source.baseAddress! + nameStart,
@@ -1265,7 +1265,7 @@ internal struct JSONScanner {
         if let s = utf8ToString(bytes: key.baseAddress!, count: key.count) {
           fieldName = s
         } else {
-          throw SwiftProtobufError.JSONDecoding.invalidUTF8()
+          throw JSONDecodingError.invalidUTF8
         }
       } else {
         // Slow path:  We parsed a String; lookups from String are slower.
@@ -1285,7 +1285,7 @@ internal struct JSONScanner {
         }
       }
       if !options.ignoreUnknownFields {
-        throw SwiftProtobufError.JSONDecoding.unknownField(fieldName)
+        throw JSONDecodingError.unknownField(fieldName)
       }
       // Unknown field, skip it and try to parse the next field name
       try skipValue()
@@ -1304,12 +1304,12 @@ internal struct JSONScanner {
       if options.ignoreUnknownFields {
         return nil
       } else {
-        throw SwiftProtobufError.JSONDecoding.unrecognizedEnumValue()
+        throw JSONDecodingError.unrecognizedEnumValue
       }
     }
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     if currentByte == asciiDoubleQuote {
       if let name = try nextOptionalKey() {
@@ -1334,7 +1334,7 @@ internal struct JSONScanner {
           return try throwOrIgnore()
         }
       } else {
-        throw SwiftProtobufError.JSONDecoding.numberRange()
+        throw JSONDecodingError.numberRange
       }
     }
   }
@@ -1343,14 +1343,14 @@ internal struct JSONScanner {
   private mutating func skipRequiredCharacter(_ required: UInt8) throws {
     skipWhitespace()
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     let next = currentByte
     if next == required {
       advance()
       return
     }
-    throw SwiftProtobufError.JSONDecoding.failure()
+    throw JSONDecodingError.failure
   }
 
   /// Skip "{", throw if that's not the next character
@@ -1419,7 +1419,7 @@ internal struct JSONScanner {
     if let s = utf8ToString(bytes: source, start: start, end: index) {
       return s
     } else {
-      throw SwiftProtobufError.JSONDecoding.invalidUTF8()
+      throw JSONDecodingError.invalidUTF8
     }
   }
 
@@ -1437,7 +1437,7 @@ internal struct JSONScanner {
             arrayDepth += 1
         }
         guard hasMoreContent else {
-          throw SwiftProtobufError.JSONDecoding.truncated()
+          throw JSONDecodingError.truncated
         }
         switch currentByte {
         case asciiDoubleQuote: // " begins a string
@@ -1446,7 +1446,7 @@ internal struct JSONScanner {
             try skipObject()
         case asciiCloseSquareBracket: // ] ends an empty array
             if arrayDepth == 0 {
-              throw SwiftProtobufError.JSONDecoding.failure()
+              throw JSONDecodingError.failure
             }
             // We also close out [[]] or [[[]]] here
             while arrayDepth > 0 && skipOptionalArrayEnd() {
@@ -1456,19 +1456,19 @@ internal struct JSONScanner {
             if !skipOptionalKeyword(bytes: [
                 asciiLowerN, asciiLowerU, asciiLowerL, asciiLowerL
             ]) {
-              throw SwiftProtobufError.JSONDecoding.truncated()
+              throw JSONDecodingError.truncated
             }
         case asciiLowerF: // f must be false
             if !skipOptionalKeyword(bytes: [
                 asciiLowerF, asciiLowerA, asciiLowerL, asciiLowerS, asciiLowerE
             ]) {
-              throw SwiftProtobufError.JSONDecoding.truncated()
+              throw JSONDecodingError.truncated
             }
         case asciiLowerT: // t must be true
             if !skipOptionalKeyword(bytes: [
                 asciiLowerT, asciiLowerR, asciiLowerU, asciiLowerE
             ]) {
-              throw SwiftProtobufError.JSONDecoding.truncated()
+              throw JSONDecodingError.truncated
             }
         default: // everything else is a number token
             _ = try nextDouble()
@@ -1516,10 +1516,10 @@ internal struct JSONScanner {
   // schema mismatches or other issues.
   private mutating func skipString() throws {
     guard hasMoreContent else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     if currentByte != asciiDoubleQuote {
-      throw SwiftProtobufError.JSONDecoding.malformedString()
+      throw JSONDecodingError.malformedString
     }
     advance()
     while hasMoreContent {
@@ -1531,13 +1531,13 @@ internal struct JSONScanner {
       case asciiBackslash:
         advance()
         guard hasMoreContent else {
-          throw SwiftProtobufError.JSONDecoding.truncated()
+          throw JSONDecodingError.truncated
         }
         advance()
       default:
         advance()
       }
     }
-    throw SwiftProtobufError.JSONDecoding.truncated()
+    throw JSONDecodingError.truncated
   }
 }

+ 2 - 2
Sources/SwiftProtobuf/Message+BinaryAdditions.swift

@@ -34,7 +34,7 @@ extension Message {
     options: BinaryEncodingOptions = BinaryEncodingOptions()
   ) throws -> Bytes {
     if !partial && !isInitialized {
-      throw SwiftProtobufError.BinaryEncoding.missingRequiredFields()
+      throw BinaryEncodingError.missingRequiredFields
     }
 
     // Note that this assumes `options` will not change the required size.
@@ -149,7 +149,7 @@ extension Message {
       try decoder.decodeFullMessage(message: &self)
     }
     if !partial && !isInitialized {
-      throw SwiftProtobufError.BinaryDecoding.missingRequiredFields()
+      throw BinaryDecodingError.missingRequiredFields
     }
   }
 }

+ 5 - 5
Sources/SwiftProtobuf/Message+JSONAdditions.swift

@@ -84,12 +84,12 @@ extension Message {
     options: JSONDecodingOptions = JSONDecodingOptions()
   ) throws {
     if jsonString.isEmpty {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     if let data = jsonString.data(using: String.Encoding.utf8) {
       try self.init(jsonUTF8Bytes: data, extensions: extensions, options: options)
     } else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
   }
   
@@ -126,7 +126,7 @@ extension Message {
     try jsonUTF8Bytes.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
       // Empty input is valid for binary, but not for JSON.
       guard body.count > 0 else {
-        throw SwiftProtobufError.JSONDecoding.truncated()
+        throw JSONDecodingError.truncated
       }
       var decoder = JSONDecoder(source: body, options: options,
                                 messageType: Self.self, extensions: extensions)
@@ -135,13 +135,13 @@ extension Message {
            let message = try customCodable.decodedFromJSONNull() {
           self = message as! Self
         } else {
-          throw SwiftProtobufError.JSONDecoding.illegalNull()
+          throw JSONDecodingError.illegalNull
         }
       } else {
         try decoder.decodeFullObject(message: &self)
       }
       if !decoder.scanner.complete {
-        throw SwiftProtobufError.JSONDecoding.trailingGarbage()
+        throw JSONDecodingError.trailingGarbage
       }
     }
   }

+ 3 - 3
Sources/SwiftProtobuf/Message+JSONArrayAdditions.swift

@@ -87,12 +87,12 @@ extension Message {
     options: JSONDecodingOptions = JSONDecodingOptions()
   ) throws -> [Self] {
     if jsonString.isEmpty {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
     if let data = jsonString.data(using: String.Encoding.utf8) {
       return try array(fromJSONUTF8Bytes: data, extensions: extensions, options: options)
     } else {
-      throw SwiftProtobufError.JSONDecoding.truncated()
+      throw JSONDecodingError.truncated
     }
   }
 
@@ -135,7 +135,7 @@ extension Message {
           messageType: Self.self, extensions: extensions)
         try decoder.decodeRepeatedMessageField(value: &array)
         if !decoder.scanner.complete {
-          throw SwiftProtobufError.JSONDecoding.trailingGarbage()
+          throw JSONDecodingError.trailingGarbage
         }
       }
 

+ 1 - 1
Sources/SwiftProtobuf/Message+TextFormatAdditions.swift

@@ -81,7 +81,7 @@ extension Message {
                                                 extensions: extensions)
             try decodeMessage(decoder: &decoder)
             if !decoder.complete {
-              throw SwiftProtobufError.TextFormatDecoding.trailingGarbage()
+              throw TextFormatDecodingError.trailingGarbage
             }
           }
         }

+ 0 - 761
Sources/SwiftProtobuf/SwiftProtobufError.swift

@@ -281,26 +281,6 @@ extension SwiftProtobufError: CustomDebugStringConvertible {
 extension SwiftProtobufError {
     /// Errors arising from encoding protobufs into binary data.
     public enum BinaryEncoding {
-        /// The definition of the message or one of its nested messages has required
-        /// fields but the message being encoded did not include values for them. You
-        /// must pass `partial: true` during encoding if you wish to explicitly ignore
-        /// missing required fields.
-        public static func missingRequiredFields(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryEncodingError,
-                message: """
-                The definition of the message or one of its nested messages has required fields, \
-                but the message being encoded did not include values for them. \
-                Decode with `partial: true` if you wish to explicitly ignore missing required fields.
-            """,
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
         /// Messages are limited to a maximum of 2GB in encoded size.
         public static func tooLarge(
             function: String = #function,
@@ -333,53 +313,10 @@ extension SwiftProtobufError {
             location: SourceLocation(function: function, file: file, line: line)
           )
         }
-        
-        /// When writing a binary-delimited message into a stream, this error will be thrown if less than
-        /// the expected number of bytes were written.
-        public static func truncated(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryEncodingError,
-                message: """
-                    Less than the expected number of bytes were written when writing \
-                    a binary-delimited message into an output stream.
-                """,
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
     }
 
     /// Errors arising from binary decoding of data into protobufs.
     public enum BinaryDecoding {
-        /// The end of the data was reached before it was expected.
-        public static func truncated(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryDecodingError,
-                message: "The end of the data was reached before it was expected.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        // Extraneous data remained after decoding should have been complete.
-        public static func trailingGarbage(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryDecodingError,
-                message: "Extraneous data remained after decoding should have been complete.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
         /// Message is too large. Bytes and Strings have a max size of 2GB.
         public static func tooLarge(
             function: String = #function,
@@ -392,117 +329,11 @@ extension SwiftProtobufError {
                 location: SourceLocation(function: function, file: file, line: line)
             )
         }
-        
-        /// A string field was not encoded as valid UTF-8.
-        public static func invalidUTF8(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryDecodingError,
-                message: "A string field was not encoded as valid UTF-8.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// The binary data was malformed in some way, such as an invalid wire format or field tag.
-        public static func malformedProtobuf(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryDecodingError,
-                message: """
-                    The binary data was malformed in some way, such as an \
-                    invalid wire format or field tag.
-                """,
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// The definition of the message or one of its nested messages has required
-        /// fields but the binary data did not include values for them. You must pass
-        /// `partial: true` during decoding if you wish to explicitly ignore missing
-        /// required fields.
-        public static func missingRequiredFields(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryDecodingError,
-                message: """
-                    The definition of the message or one of its nested messages has required fields, \
-                    but the binary data did not include values for them. \
-                    Decode with `partial: true` if you wish to explicitly ignore missing required fields.
-                """,
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// An internal error happened while decoding.  If this is ever encountered,
-        /// please file an issue with SwiftProtobuf with as much details as possible
-        /// for what happened (proto definitions, bytes being decoded (if possible)).
-        public static func internalExtensionError(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryDecodingError,
-                message: "An internal error hapenned while decoding. Please file an issue with SwiftProtobuf.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-
-        /// Reached the nesting limit for messages within messages while decoding.
-        public static func messageDepthLimit(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .binaryDecodingError,
-                message: "Reached the nesting limit for messages within messages while decoding.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
     }
     
     /// Errors arising from decoding streams of binary messages. These errors have to do with the framing
     /// of the messages in the stream, or the stream as a whole.
     public enum BinaryStreamDecoding {
-      /// If a read/write to the stream fails, but the stream's `streamError` is nil,
-      /// this error will be thrown instead since the stream didn't provide anything
-      /// more specific. A common cause for this can be failing to open the stream
-      /// before trying to read/write to it.
-      public static func unknownStreamError(
-        function: String = #function,
-        file: String = #fileID,
-        line: Int = #line
-      ) -> SwiftProtobufError {
-        SwiftProtobufError(
-          code: .binaryStreamDecodingError,
-          message: "Unknown error when reading/writing binary-delimited message into stream.",
-          location: .init(function: function, file: file, line: line)
-        )
-      }
-      
-      /// While reading/writing to the stream, less than the expected bytes was read/written.
-      public static func truncated(
-          function: String = #function,
-          file: String = #fileID,
-          line: Int = #line
-      ) -> SwiftProtobufError {
-          SwiftProtobufError(
-              code: .binaryStreamDecodingError,
-              message: "The end of the data was reached before it was expected.",
-              location: SourceLocation(function: function, file: file, line: line)
-          )
-      }
-      
       /// Message is too large. Bytes and Strings have a max size of 2GB.
       public static func tooLarge(
           function: String = #function,
@@ -558,95 +389,6 @@ extension SwiftProtobufError {
     
     /// Errors arising from encoding protobufs into JSON.
     public enum JSONEncoding {
-        /// Timestamp values can only be JSON encoded if they hold a value
-        /// between 0001-01-01Z00:00:00 and 9999-12-31Z23:59:59.
-        public static func timestampRange(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonEncodingError,
-                message: """
-                    Timestamp values can only be JSON encoded if they hold a value \
-                    between 0001-01-01Z00:00:00 and 9999-12-31Z23:59:59.
-                """,
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Duration values can only be JSON encoded if they hold a value
-        /// less than +/- 100 years.
-        public static func durationRange(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonEncodingError,
-                message: "Duration values can only be JSON encoded if they hold a value less than +/- 100 years.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Field masks get edited when converting between JSON and protobuf.
-        public static func fieldMaskConversion(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonEncodingError,
-                message: "Field masks get edited when converting between JSON and protobuf.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Field names were not compiled into the binary.
-        public static func missingFieldNames(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonEncodingError,
-                message: "Field names were not compiled into the binary.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Instances of `Google_Protobuf_Value` can only be encoded if they have a
-        /// valid `kind` (that is, they represent a null value, number, boolean,
-        /// string, struct, or list).
-        public static func missingValue(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonEncodingError,
-                message: "Instances of `Google_Protobuf_Value` can only be encoded if they have a valid `kind`.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// `Google_Protobuf_Value` cannot encode double values for infinity or nan,
-        /// because they would be parsed as a string.
-        public static func valueNumberNotFinite(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonEncodingError,
-                message: """
-                    `Google_Protobuf_Value` cannot encode double values for \
-                    infinity or nan, because they would be parsed as a string.
-                """,
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
         /// Any fields that were decoded from binary format cannot be re-encoded into JSON unless the
         /// object they hold is a well-known type or a type registered via `Google_Protobuf_Any.register()`.
         public static func anyTypeURLNotRegistered(
@@ -666,507 +408,4 @@ extension SwiftProtobufError {
             )
         }
     }
-    
-    /// Errors arising from JSON decoding of data into protobufs.
-    public enum JSONDecoding {
-        /// Something went wrong.
-        public static func failure(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "Something went wrong.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-
-        /// A number could not be parsed.
-        public static func malformedNumber(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A number could not be parsed.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Numeric value was out of range or was not an integer value when expected.
-        public static func numberRange(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "Numeric value was out of range or was not an integer value when expected.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A map could not be parsed.
-        public static func malformedMap(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A map could not be parsed.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A bool could not be parsed.
-        public static func malformedBool(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A bool could not be parsed.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// We expected a quoted string, or a quoted string has a malformed backslash sequence.
-        public static func malformedString(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "Expected a quoted string, or encountered a quoted string with a malformed backslash sequence.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// We encountered malformed UTF8.
-        public static func invalidUTF8(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "Encountered malformed UTF8.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// The message does not have fieldName information.
-        public static func missingFieldNames(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "The message does not have fieldName information.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// The data type does not match the schema description.
-        public static func schemaMismatch(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "The data type does not match the schema description.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A value (text or numeric) for an enum was not found on the enum.
-        public static func unrecognizedEnumValue(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A value (text or numeric) for an enum was not found on the enum.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A 'null' token appeared in an illegal location.
-        /// For example, Protobuf JSON does not allow 'null' tokens to appear in lists.
-        public static func illegalNull(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A 'null' token appeared in an illegal location.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A map key was not quoted.
-        public static func unquotedMapKey(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A map key was not quoted.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// JSON RFC 7519 does not allow numbers to have extra leading zeros.
-        public static func leadingZero(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "JSON RFC 7519 does not allow numbers to have extra leading zeros.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// We hit the end of the JSON string and expected something more.
-        public static func truncated(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "Reached end of JSON string but expected something more.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A JSON Duration could not be parsed.
-        public static func malformedDuration(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A JSON Duration could not be parsed.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A JSON Timestamp could not be parsed.
-        public static func malformedTimestamp(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A JSON Timestamp could not be parsed.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A FieldMask could not be parsed.
-        public static func malformedFieldMask(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "A FieldMask could not be parsed.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Extraneous data remained after decoding should have been complete.
-        public static func trailingGarbage(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError{
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "Extraneous data remained after decoding should have been complete.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// More than one value was specified for the same oneof field.
-        public static func conflictingOneOf(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError{
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "More than one value was specified for the same oneof field.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Reached the nesting limit for messages within messages while decoding.
-        public static func messageDepthLimit(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: "Reached the nesting limit for messages within messages while decoding.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Encountered an unknown field with the given name.
-        /// - Parameter name: The name of the unknown field.
-        /// - Note: When parsing JSON, you can instead instruct the library to ignore this via
-        /// `JSONDecodingOptions.ignoreUnknownFields`.
-        public static func unknownField(
-            _ name: String,
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .unknownField(name: name),
-                message: "Encountered an unknown field with name '\(name)'.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-    }
-    
-    /// Errors arising from text format decoding of data into protobufs.
-    public enum TextFormatDecoding {
-        /// Text data could not be parsed.
-        public static func malformedText(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "Text data could not be parsed",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A number could not be parsed.
-        public static func malformedNumber(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "A number could not be parsed.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Extraneous data remained after decoding should have been complete.
-        public static func trailingGarbage(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "Extraneous data remained after decoding should have been complete.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// The data stopped before we expected.
-        public static func truncated(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "The data stopped before we expected.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A string was not valid UTF8.
-        public static func invalidUTF8(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "A string was not valid UTF8.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// The data being parsed does not match the type specified in the proto file.
-        public static func schemaMismatch(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "The data being parsed does not match the type specified in the proto file.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Field names were not compiled into the binary.
-        public static func missingFieldNames(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "Field names were not compiled into the binary.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// A field identifier (name or number) was not found on the message.
-        public static func unknownField(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "A field identifier (name or number) was not found on the message.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// The enum value was not recognized.
-        public static func unrecognizedEnumValue(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "The enum value was not recognized.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Text format rejects conflicting values for the same oneof field.
-        public static func conflictingOneOf(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "Text format rejects conflicting values for the same oneof field.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// An internal error happened while decoding.  If this is ever encountered,
-        /// please file an issue with SwiftProtobuf with as much details as possible
-        /// for what happened (proto definitions, bytes being decoded (if possible)).
-        public static func internalExtensionError(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "An internal error happened while decoding: please file an issue with SwiftProtobuf.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-        
-        /// Reached the nesting limit for messages within messages while decoding.
-        public static func messageDepthLimit(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .textFormatDecodingError,
-                message: "Reached the nesting limit for messages within messages while decoding.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-    }
-    
-    /// Describes errors that can occur when unpacking a `Google_Protobuf_Any`
-    /// message.
-    ///
-    /// `Google_Protobuf_Any` messages can be decoded from protobuf binary, text
-    /// format, or JSON. The contents are not parsed immediately; the raw data is
-    /// held in the `Google_Protobuf_Any` message until you `unpack()` it into a
-    /// message.  At this time, any error can occur that might have occurred from a
-    /// regular decoding operation.  There are also other errors that can occur due
-    /// to problems with the `Any` value's structure.
-    public enum AnyUnpack {
-        /// The `type_url` field in the `Google_Protobuf_Any` message did not match
-        /// the message type provided to the `unpack()` method.
-        public static func typeMismatch(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .invalidArgument,
-                message: """
-                    The `type_url` field in the `Google_Protobuf_Any` message did not match
-                    the message type provided to the `unpack()` method.
-                """,
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-
-        /// Well-known types being decoded from JSON must have only two fields: the
-        /// `@type` field and a `value` field containing the specialized JSON coding
-        /// of the well-known type.
-        public static func malformedWellKnownTypeJSON(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .jsonDecodingError,
-                message: """
-                    Malformed JSON type: well-known types being decoded from JSON must have only two fields:
-                    the `@type` field and a `value` field containing the specialized JSON coding
-                    of the well-known type.
-                """,
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-
-        /// The `Google_Protobuf_Any` message was malformed in some other way not
-        /// covered by the other error cases.
-        public static func malformedAnyField(
-            function: String = #function,
-            file: String = #fileID,
-            line: Int = #line
-        ) -> SwiftProtobufError {
-            SwiftProtobufError(
-                code: .internalError,
-                message: "The `Google_Protobuf_Any` message was malformed.",
-                location: SourceLocation(function: function, file: file, line: line)
-            )
-        }
-    }
 }

+ 24 - 24
Sources/SwiftProtobuf/TextFormatDecoder.swift

@@ -46,7 +46,7 @@ internal struct TextFormatDecoder: Decoder {
     ) throws {
         scanner = TextFormatScanner(utf8Pointer: utf8Pointer, count: count, options: options, extensions: extensions)
         guard let nameProviding = (messageType as? any _ProtoNameProviding.Type) else {
-            throw SwiftProtobufError.TextFormatDecoding.missingFieldNames()
+            throw TextFormatDecodingError.missingFieldNames
         }
         fieldNameMap = nameProviding._protobuf_nameMap
         self.messageType = messageType
@@ -56,14 +56,14 @@ internal struct TextFormatDecoder: Decoder {
         self.scanner = scanner
         self.terminator = terminator
         guard let nameProviding = (messageType as? any _ProtoNameProviding.Type) else {
-            throw SwiftProtobufError.TextFormatDecoding.missingFieldNames()
+            throw TextFormatDecodingError.missingFieldNames
         }
         fieldNameMap = nameProviding._protobuf_nameMap
         self.messageType = messageType
     }
 
     mutating func handleConflictingOneOf() throws {
-        throw SwiftProtobufError.TextFormatDecoding.conflictingOneOf()
+        throw TextFormatDecodingError.conflictingOneOf
     }
 
     mutating func nextFieldNumber() throws -> Int? {
@@ -142,7 +142,7 @@ internal struct TextFormatDecoder: Decoder {
         try scanner.skipRequiredColon()
         let n = try scanner.nextSInt()
         if n > Int64(Int32.max) || n < Int64(Int32.min) {
-            throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+            throw TextFormatDecodingError.malformedNumber
         }
         value = Int32(truncatingIfNeeded: n)
     }
@@ -150,7 +150,7 @@ internal struct TextFormatDecoder: Decoder {
         try scanner.skipRequiredColon()
         let n = try scanner.nextSInt()
         if n > Int64(Int32.max) || n < Int64(Int32.min) {
-            throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+            throw TextFormatDecodingError.malformedNumber
         }
         value = Int32(truncatingIfNeeded: n)
     }
@@ -169,14 +169,14 @@ internal struct TextFormatDecoder: Decoder {
                 }
                 let n = try scanner.nextSInt()
                 if n > Int64(Int32.max) || n < Int64(Int32.min) {
-                    throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+                    throw TextFormatDecodingError.malformedNumber
                 }
                 value.append(Int32(truncatingIfNeeded: n))
             }
         } else {
             let n = try scanner.nextSInt()
             if n > Int64(Int32.max) || n < Int64(Int32.min) {
-                throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+                throw TextFormatDecodingError.malformedNumber
             }
             value.append(Int32(truncatingIfNeeded: n))
         }
@@ -214,7 +214,7 @@ internal struct TextFormatDecoder: Decoder {
         try scanner.skipRequiredColon()
         let n = try scanner.nextUInt()
         if n > UInt64(UInt32.max) {
-            throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+            throw TextFormatDecodingError.malformedNumber
         }
         value = UInt32(truncatingIfNeeded: n)
     }
@@ -222,7 +222,7 @@ internal struct TextFormatDecoder: Decoder {
         try scanner.skipRequiredColon()
         let n = try scanner.nextUInt()
         if n > UInt64(UInt32.max) {
-            throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+            throw TextFormatDecodingError.malformedNumber
         }
         value = UInt32(truncatingIfNeeded: n)
     }
@@ -241,14 +241,14 @@ internal struct TextFormatDecoder: Decoder {
                 }
                 let n = try scanner.nextUInt()
                 if n > UInt64(UInt32.max) {
-                    throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+                    throw TextFormatDecodingError.malformedNumber
                 }
                 value.append(UInt32(truncatingIfNeeded: n))
             }
         } else {
             let n = try scanner.nextUInt()
             if n > UInt64(UInt32.max) {
-                throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+                throw TextFormatDecodingError.malformedNumber
             }
             value.append(UInt32(truncatingIfNeeded: n))
         }
@@ -429,7 +429,7 @@ internal struct TextFormatDecoder: Decoder {
             if let b = E(rawUTF8: name) {
                 return b
             } else {
-                throw SwiftProtobufError.TextFormatDecoding.unrecognizedEnumValue()
+                throw TextFormatDecodingError.unrecognizedEnumValue
             }
         }
         let number = try scanner.nextSInt()
@@ -438,10 +438,10 @@ internal struct TextFormatDecoder: Decoder {
             if let e = E(rawValue: Int(n)) {
                 return e
             } else {
-                throw SwiftProtobufError.TextFormatDecoding.unrecognizedEnumValue()
+                throw TextFormatDecodingError.unrecognizedEnumValue
             }
         }
-        throw SwiftProtobufError.TextFormatDecoding.malformedText()
+        throw TextFormatDecodingError.malformedText
 
     }
 
@@ -560,7 +560,7 @@ internal struct TextFormatDecoder: Decoder {
                     value[keyField] = valueField
                     return
                 } else {
-                    throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                    throw TextFormatDecodingError.malformedText
                 }
             }
             if let key = try scanner.nextKey(allowExtensions: ignoreExtensionFields) {
@@ -575,12 +575,12 @@ internal struct TextFormatDecoder: Decoder {
                     } else if options.ignoreUnknownFields && !key.hasPrefix("[") {
                         try scanner.skipUnknownFieldValue()
                     } else {
-                        throw SwiftProtobufError.TextFormatDecoding.unknownField()
+                        throw TextFormatDecodingError.unknownField
                     }
                 }
                 scanner.skipOptionalSeparator()
             } else {
-                throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                throw TextFormatDecodingError.malformedText
             }
         }
     }
@@ -616,7 +616,7 @@ internal struct TextFormatDecoder: Decoder {
                     value[keyField] = valueField
                     return
                 } else {
-                    throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                    throw TextFormatDecodingError.malformedText
                 }
             }
             if let key = try scanner.nextKey(allowExtensions: ignoreExtensionFields) {
@@ -631,12 +631,12 @@ internal struct TextFormatDecoder: Decoder {
                     } else if options.ignoreUnknownFields && !key.hasPrefix("[") {
                         try scanner.skipUnknownFieldValue()
                     } else {
-                        throw SwiftProtobufError.TextFormatDecoding.unknownField()
+                        throw TextFormatDecodingError.unknownField
                     }
                 }
                 scanner.skipOptionalSeparator()
             } else {
-                throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                throw TextFormatDecodingError.malformedText
             }
         }
     }
@@ -672,7 +672,7 @@ internal struct TextFormatDecoder: Decoder {
                     value[keyField] = valueField
                     return
                 } else {
-                    throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                    throw TextFormatDecodingError.malformedText
                 }
             }
             if let key = try scanner.nextKey(allowExtensions: ignoreExtensionFields) {
@@ -687,12 +687,12 @@ internal struct TextFormatDecoder: Decoder {
                     } else if options.ignoreUnknownFields && !key.hasPrefix("[") {
                         try scanner.skipUnknownFieldValue()
                     } else {
-                        throw SwiftProtobufError.TextFormatDecoding.unknownField()
+                        throw TextFormatDecodingError.unknownField
                     }
                 }
                 scanner.skipOptionalSeparator()
             } else {
-                throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                throw TextFormatDecodingError.malformedText
             }
         }
     }
@@ -729,7 +729,7 @@ internal struct TextFormatDecoder: Decoder {
                     // Really things should never get here, for TextFormat, decoding
                     // the value should always work or throw an error.  This specific
                     // error result is to allow this to be more detectable.
-                    throw SwiftProtobufError.TextFormatDecoding.internalExtensionError()
+                    throw TextFormatDecodingError.internalExtensionError
                 }
             }
         }

+ 0 - 1
Sources/SwiftProtobuf/TextFormatDecodingError.swift

@@ -12,7 +12,6 @@
 ///
 // -----------------------------------------------------------------------------
 
-@available(*, deprecated, message: "This error type has been deprecated and won't be thrown anymore; it has been replaced by `SwiftProtobufError`.")
 public enum TextFormatDecodingError: Error {
     /// Text data could not be parsed
     case malformedText

+ 44 - 44
Sources/SwiftProtobuf/TextFormatScanner.swift

@@ -270,7 +270,7 @@ internal struct TextFormatScanner {
     private mutating func incrementRecursionDepth() throws {
         recursionBudget -= 1
         if recursionBudget < 0 {
-          throw SwiftProtobufError.TextFormatDecoding.messageDepthLimit()
+          throw TextFormatDecodingError.messageDepthLimit
         }
     }
 
@@ -355,7 +355,7 @@ internal struct TextFormatScanner {
         switch byte {
         case asciiNewLine, asciiCarriageReturn:
           // Can't have a newline in the middle of a bytes string.
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         case asciiBackslash: //  "\\"
           sawBackslash = true
           if p != end {
@@ -369,7 +369,7 @@ internal struct TextFormatScanner {
                   if p != end, p[0] >= asciiZero, p[0] <= asciiSeven {
                     if escaped > asciiThree {
                        // Out of range octal: three digits and first digit is greater than 3
-                      throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                      throw TextFormatDecodingError.malformedText
                     }
                     p += 1
                   }
@@ -378,14 +378,14 @@ internal struct TextFormatScanner {
               case asciiLowerU, asciiUpperU: // 'u' or 'U' unicode escape
                 let numDigits = (escaped == asciiLowerU) ? 4 : 8
                 guard (end - p) >= numDigits else {
-                  throw SwiftProtobufError.TextFormatDecoding.malformedText() // unicode escape must 4/8 digits
+                  throw TextFormatDecodingError.malformedText // unicode escape must 4/8 digits
                 }
                 var codePoint: UInt32 = 0
                 for i in 0..<numDigits {
                   if let digit = uint32FromHexDigit(p[i]) {
                     codePoint = (codePoint << 4) + digit
                   } else {
-                    throw SwiftProtobufError.TextFormatDecoding.malformedText() // wasn't a hex digit
+                    throw TextFormatDecodingError.malformedText // wasn't a hex digit
                   }
                 }
                 p += numDigits
@@ -398,7 +398,7 @@ internal struct TextFormatScanner {
                   count += 2
                 case 0xD800...0xDFFF:
                   // Surrogate pair (low or high), shouldn't get a unicode literal of those.
-                  throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                  throw TextFormatDecodingError.malformedText
                 case 0x800...0xffff:
                   // 3 byte encoding
                   count += 3
@@ -406,7 +406,7 @@ internal struct TextFormatScanner {
                   // 4 byte encoding
                   count += 4
                 default:
-                  throw SwiftProtobufError.TextFormatDecoding.malformedText() // Isn't a valid unicode character
+                  throw TextFormatDecodingError.malformedText // Isn't a valid unicode character
                 }
               case asciiLowerX: // 'x' hexadecimal escape
                 if p != end && fromHexDigit(p[0]) != nil {
@@ -415,7 +415,7 @@ internal struct TextFormatScanner {
                     p += 1
                   }
                 } else {
-                  throw SwiftProtobufError.TextFormatDecoding.malformedText() // Hex escape must have at least 1 digit
+                  throw TextFormatDecodingError.malformedText // Hex escape must have at least 1 digit
                 }
                 count += 1
               case asciiLowerA, // \a ("alert")
@@ -431,14 +431,14 @@ internal struct TextFormatScanner {
                    asciiBackslash: // \\
                 count += 1
               default:
-              throw SwiftProtobufError.TextFormatDecoding.malformedText() // Unrecognized escape
+              throw TextFormatDecodingError.malformedText // Unrecognized escape
             }
           }
         default:
           count += 1
         }
       }
-      throw SwiftProtobufError.TextFormatDecoding.malformedText()
+      throw TextFormatDecodingError.malformedText
     }
 
     /// Protobuf Text format uses C ASCII conventions for
@@ -592,7 +592,7 @@ internal struct TextFormatScanner {
 
     internal mutating func nextUInt() throws -> UInt64 {
         if p == end {
-          throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+          throw TextFormatDecodingError.malformedNumber
         }
         let c = p[0]
         p += 1
@@ -619,7 +619,7 @@ internal struct TextFormatScanner {
                         return n
                     }
                     if n > UInt64.max / 16 {
-                      throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+                      throw TextFormatDecodingError.malformedNumber
                     }
                     p += 1
                     n = n * 16 + val
@@ -636,7 +636,7 @@ internal struct TextFormatScanner {
                     }
                     let val = UInt64(digit - asciiZero)
                     if n > UInt64.max / 8 {
-                      throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+                      throw TextFormatDecodingError.malformedNumber
                     }
                     p += 1
                     n = n * 8 + val
@@ -654,7 +654,7 @@ internal struct TextFormatScanner {
                 }
                 let val = UInt64(digit - asciiZero)
                 if n > UInt64.max / 10 || n * 10 > UInt64.max - val {
-                  throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+                  throw TextFormatDecodingError.malformedNumber
                 }
                 p += 1
                 n = n * 10 + val
@@ -662,30 +662,30 @@ internal struct TextFormatScanner {
             skipWhitespace()
             return n
         }
-      throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+      throw TextFormatDecodingError.malformedNumber
     }
 
     internal mutating func nextSInt() throws -> Int64 {
         if p == end {
-          throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+          throw TextFormatDecodingError.malformedNumber
         }
         let c = p[0]
         if c == asciiMinus { // -
             p += 1
             if p == end {
-              throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+              throw TextFormatDecodingError.malformedNumber
             }
             // character after '-' must be digit
             let digit = p[0]
             if digit < asciiZero || digit > asciiNine {
-              throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+              throw TextFormatDecodingError.malformedNumber
             }
             let n = try nextUInt()
             let limit: UInt64 = 0x8000000000000000 // -Int64.min
             if n >= limit {
                 if n > limit {
                     // Too large negative number
-                  throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+                  throw TextFormatDecodingError.malformedNumber
                 } else {
                     return Int64.min // Special case for Int64.min
                 }
@@ -694,7 +694,7 @@ internal struct TextFormatScanner {
         } else {
             let n = try nextUInt()
             if n > UInt64(bitPattern: Int64.max) {
-              throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+              throw TextFormatDecodingError.malformedNumber
             }
             return Int64(bitPattern: n)
         }
@@ -704,17 +704,17 @@ internal struct TextFormatScanner {
         var result: String
         skipWhitespace()
         if p == end {
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
         let c = p[0]
         if c != asciiSingleQuote && c != asciiDoubleQuote {
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
         p += 1
         if let s = parseStringSegment(terminator: c) {
             result = s
         } else {
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
 
         while true {
@@ -729,7 +729,7 @@ internal struct TextFormatScanner {
             if let s = parseStringSegment(terminator: c) {
                 result.append(s)
             } else {
-              throw SwiftProtobufError.TextFormatDecoding.malformedText()
+              throw TextFormatDecodingError.malformedText
             }
         }
     }
@@ -744,11 +744,11 @@ internal struct TextFormatScanner {
         var result: Data
         skipWhitespace()
         if p == end {
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
         let c = p[0]
         if c != asciiSingleQuote && c != asciiDoubleQuote {
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
         p += 1
         var sawBackslash = false
@@ -947,7 +947,7 @@ internal struct TextFormatScanner {
         if let inf = skipOptionalInfinity() {
             return inf
         }
-      throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+      throw TextFormatDecodingError.malformedNumber
     }
 
     internal mutating func nextDouble() throws -> Double {
@@ -960,13 +960,13 @@ internal struct TextFormatScanner {
         if let inf = skipOptionalInfinity() {
             return Double(inf)
         }
-      throw SwiftProtobufError.TextFormatDecoding.malformedNumber()
+      throw TextFormatDecodingError.malformedNumber
     }
 
     internal mutating func nextBool() throws -> Bool {
         skipWhitespace()
         if p == end {
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
         let c = p[0]
         p += 1
@@ -989,7 +989,7 @@ internal struct TextFormatScanner {
             }
             result = true
         default:
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
         if p == end {
             return result
@@ -1008,14 +1008,14 @@ internal struct TextFormatScanner {
             skipWhitespace()
             return result
         default:
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
     }
 
     internal mutating func nextOptionalEnumName() throws -> UnsafeRawBufferPointer? {
         skipWhitespace()
         if p == end {
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
         switch p[0] {
         case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ:
@@ -1060,14 +1060,14 @@ internal struct TextFormatScanner {
         assert(p[0] == asciiOpenSquareBracket)
         p += 1
         if p == end {
-            throw SwiftProtobufError.TextFormatDecoding.malformedText()
+            throw TextFormatDecodingError.malformedText
         }
         let start = p
         switch p[0] {
         case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ:
             p += 1
         default:
-            throw SwiftProtobufError.TextFormatDecoding.malformedText()
+            throw TextFormatDecodingError.malformedText
         }
         loop: while p != end {
             switch p[0] {
@@ -1081,14 +1081,14 @@ internal struct TextFormatScanner {
             case asciiCloseSquareBracket: // ]
                 break loop
             default:
-                throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                throw TextFormatDecodingError.malformedText
             }
         }
         if p == end || p[0] != asciiCloseSquareBracket {
-            throw SwiftProtobufError.TextFormatDecoding.malformedText()
+            throw TextFormatDecodingError.malformedText
         }
         guard let extensionName = utf8ToString(bytes: start, count: p - start) else {
-            throw SwiftProtobufError.TextFormatDecoding.malformedText()
+            throw TextFormatDecodingError.malformedText
         }
         p += 1  // Skip ]
         skipWhitespace()
@@ -1107,7 +1107,7 @@ internal struct TextFormatScanner {
             if allowExtensions {
                 return "[\(try parseExtensionKey())]"
             }
-            throw SwiftProtobufError.TextFormatDecoding.unknownField()
+            throw TextFormatDecodingError.unknownField
         case asciiLowerA...asciiLowerZ,
              asciiUpperA...asciiUpperZ: // a...z, A...Z
             return parseIdentifier()
@@ -1130,7 +1130,7 @@ internal struct TextFormatScanner {
             // Safe, can't be invalid UTF-8 given the input.
             return s!
         default:
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
     }
 
@@ -1156,7 +1156,7 @@ internal struct TextFormatScanner {
                     return nil
                 } else {
                     // Never got the terminator.
-                    throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                    throw TextFormatDecodingError.malformedText
                 }
             }
             let c = p[0]
@@ -1350,12 +1350,12 @@ internal struct TextFormatScanner {
         let terminator = try skipObjectStart()
         while !skipOptionalObjectEnd(terminator) {
             if p == end {
-                throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                throw TextFormatDecodingError.malformedText
             }
             if let _ = try nextKey(allowExtensions: true) {
                 // Got a valid field name or extension name ("[ext.name]")
             } else {
-                throw SwiftProtobufError.TextFormatDecoding.malformedText()
+                throw TextFormatDecodingError.malformedText
             }
             try skipUnknownFieldValue()
             skipOptionalSeparator()
@@ -1368,7 +1368,7 @@ internal struct TextFormatScanner {
             p += 1
             skipWhitespace()
         } else {
-          throw SwiftProtobufError.TextFormatDecoding.malformedText()
+          throw TextFormatDecodingError.malformedText
         }
     }
 
@@ -1436,6 +1436,6 @@ internal struct TextFormatScanner {
                 break
             }
         }
-      throw SwiftProtobufError.TextFormatDecoding.malformedText()
+      throw TextFormatDecodingError.malformedText
     }
 }

+ 3 - 3
Tests/SwiftProtobufTests/Test_AsyncMessageSequence.swift

@@ -126,7 +126,7 @@ final class Test_AsyncMessageSequence: XCTestCase {
         XCTFail("Shouldn't have returned a value for an empty stream.")
       }
     } catch {
-      if self.isSwiftProtobufErrorEqual(error as! SwiftProtobufError, .BinaryStreamDecoding.truncated()) {
+      if error as! BinaryDelimited.Error == .truncated {
         truncatedThrown = true
       }
     }
@@ -157,7 +157,7 @@ final class Test_AsyncMessageSequence: XCTestCase {
         XCTFail("Shouldn't have returned a value for an empty stream.")
       }
     } catch {
-      if self.isSwiftProtobufErrorEqual(error as! SwiftProtobufError, .BinaryStreamDecoding.truncated()) {
+      if error as! BinaryDelimited.Error == .truncated {
         truncatedThrown = true
       }
     }
@@ -189,7 +189,7 @@ final class Test_AsyncMessageSequence: XCTestCase {
       }
       XCTAssertEqual(count, 1, "One message should be deserialized")
     } catch {
-      if self.isSwiftProtobufErrorEqual(error as! SwiftProtobufError, .BinaryStreamDecoding.truncated()) {
+      if error as! BinaryDelimited.Error == .truncated {
         truncatedThrown = true
       }
     }

+ 1 - 1
Tests/SwiftProtobufTests/Test_BinaryDecodingOptions.swift

@@ -113,7 +113,7 @@ final class Test_BinaryDecodingOptions: XCTestCase {
                     if !expectSuccess {
                         XCTFail("Should not have succeed, pass: \(i), limit: \(limit)")
                     }
-                } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .BinaryDecoding.messageDepthLimit()) {
+                } catch BinaryDecodingError.messageDepthLimit {
                     if expectSuccess {
                         XCTFail("Decode failed because of limit, but should *NOT* have, pass: \(i), limit: \(limit)")
                     } else {

+ 1 - 1
Tests/SwiftProtobufTests/Test_BinaryDelimited.swift

@@ -47,7 +47,7 @@ final class Test_BinaryDelimited: XCTestCase {
   func assertParsing(failsWithTruncatedStream istream: InputStream) {
     XCTAssertThrowsError(try BinaryDelimited.parse(messageType: SwiftProtoTesting_TestAllTypes.self,
                                                    from: istream)) { error in
-      XCTAssertTrue(self.isSwiftProtobufErrorEqual(error as! SwiftProtobufError, .BinaryStreamDecoding.truncated()))
+      XCTAssertEqual(error as? BinaryDelimited.Error, BinaryDelimited.Error.truncated)
     }
   }
 

+ 5 - 6
Tests/SwiftProtobufTests/Test_JSONDecodingOptions.swift

@@ -46,7 +46,7 @@ final class Test_JSONDecodingOptions: XCTestCase {
                     if !expectSuccess {
                         XCTFail("Should not have succeed, pass: \(i), limit: \(limit)")
                     }
-                } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .JSONDecoding.messageDepthLimit()) {
+                } catch JSONDecodingError.messageDepthLimit {
                     if expectSuccess {
                         XCTFail("Decode failed because of limit, but should *NOT* have, pass: \(i), limit: \(limit)")
                     } else {
@@ -136,9 +136,8 @@ final class Test_JSONDecodingOptions: XCTestCase {
             do {
                 let _ = try SwiftProtoTesting_TestEmptyMessage(jsonString: jsonInput)
                 XCTFail("Input \(i): Should not have gotten here! Input: \(jsonInput)")
-            } catch let error as SwiftProtobufError {
-                XCTAssertEqual(error.code, .unknownField(name: "unknown"))
-                XCTAssertEqual(error.message, "Encountered an unknown field with name 'unknown'.")
+            } catch JSONDecodingError.unknownField(let field) {
+                XCTAssertEqual(field, "unknown", "Input \(i): got field \(field)")
             } catch let e {
                 XCTFail("Input \(i): Error \(e) decoding into an empty message \(jsonInput)")
             }
@@ -149,8 +148,8 @@ final class Test_JSONDecodingOptions: XCTestCase {
                                                               options:options)
                 XCTAssertTrue(isValidJSON,
                               "Input \(i): Should not have been able to parse: \(jsonInput)")
-            } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .JSONDecoding.unknownField("unknown")) {
-                XCTFail("Input \(i): should not have gotten unknown field, input \(jsonInput)")
+            } catch JSONDecodingError.unknownField(let field) {
+                XCTFail("Input \(i): should not have gotten unknown field \(field), input \(jsonInput)")
             } catch let e {
                 XCTAssertFalse(isValidJSON,
                                "Input \(i): Error \(e): Should have been able to parse: \(jsonInput)")

+ 12 - 9
Tests/SwiftProtobufTests/Test_JSON_Conformance.swift

@@ -283,23 +283,26 @@ final class Test_JSON_Conformance: XCTestCase {
 
   func testValue_DoubleNonFinite() {
     XCTAssertThrowsError(try Google_Protobuf_Value(numberValue: .nan).jsonString()) {
-        XCTAssertTrue(
-            self.isSwiftProtobufErrorEqual($0 as! SwiftProtobufError, .JSONEncoding.valueNumberNotFinite()),
-            "Wrong error? - \($0)"
+        XCTAssertEqual(
+            $0 as? JSONEncodingError,
+           JSONEncodingError.valueNumberNotFinite,
+           "Wrong error? - \($0)"
         )
     }
 
     XCTAssertThrowsError(try Google_Protobuf_Value(numberValue: .infinity).jsonString()) {
-        XCTAssertTrue(
-            self.isSwiftProtobufErrorEqual($0 as! SwiftProtobufError, .JSONEncoding.valueNumberNotFinite()),
-            "Wrong error? - \($0)"
+        XCTAssertEqual(
+            $0 as? JSONEncodingError,
+           JSONEncodingError.valueNumberNotFinite,
+           "Wrong error? - \($0)"
         )
     }
 
     XCTAssertThrowsError(try Google_Protobuf_Value(numberValue: -.infinity).jsonString()) {
-        XCTAssertTrue(
-            self.isSwiftProtobufErrorEqual($0 as! SwiftProtobufError, .JSONEncoding.valueNumberNotFinite()),
-            "Wrong error? - \($0)"
+        XCTAssertEqual(
+            $0 as? JSONEncodingError,
+           JSONEncodingError.valueNumberNotFinite,
+           "Wrong error? - \($0)"
         )
     }
   }

+ 4 - 4
Tests/SwiftProtobufTests/Test_Required.swift

@@ -157,7 +157,7 @@ final class Test_Required: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(serializedBytes: bytes)
             XCTFail("Swift decode should have failed: \(bytes)", file: file, line: line)
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .BinaryDecoding.missingRequiredFields()) {
+        } catch BinaryDecodingError.missingRequiredFields {
             // Correct error!
         } catch let e {
             XCTFail("Decoding \(bytes) got wrong error: \(e)", file: file, line: line)
@@ -254,7 +254,7 @@ final class Test_Required: XCTestCase, PBTestHelpers {
         do {
             let _: [UInt8] = try message.serializedBytes()
             XCTFail("Swift encode should have failed: \(message)", file: file, line: line)
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .BinaryEncoding.missingRequiredFields()) {
+        } catch BinaryEncodingError.missingRequiredFields {
             // Correct error!
             print("sdfdsf")
         } catch let e {
@@ -358,7 +358,7 @@ final class Test_SmallRequired: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(serializedBytes: bytes)
             XCTFail("Swift decode should have failed: \(bytes)", file: file, line: line)
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .BinaryDecoding.missingRequiredFields()) {
+        } catch BinaryDecodingError.missingRequiredFields {
             // Correct error!
         } catch let e {
             XCTFail("Decoding \(bytes) got wrong error: \(e)", file: file, line: line)
@@ -415,7 +415,7 @@ final class Test_SmallRequired: XCTestCase, PBTestHelpers {
         do {
             let _: [UInt8] = try message.serializedBytes()
             XCTFail("Swift encode should have failed: \(message)", file: file, line: line)
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .BinaryEncoding.missingRequiredFields()) {
+        } catch BinaryEncodingError.missingRequiredFields {
             // Correct error!
         } catch let e {
             XCTFail("Encoding got wrong error: \(e) for \(message)", file: file, line: line)

+ 1 - 1
Tests/SwiftProtobufTests/Test_Struct.swift

@@ -221,7 +221,7 @@ final class Test_JSON_Value: XCTestCase, PBTestHelpers {
         do {
             _ = try empty.jsonString()
             XCTFail("Encoding should have thrown .missingValue, but it succeeded")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .JSONEncoding.missingValue()) {
+        } catch JSONEncodingError.missingValue {
             // Nothing to do here; this is the expected error.
         } catch {
             XCTFail("Encoding should have thrown .missingValue, but instead it threw: \(error)")

+ 1 - 1
Tests/SwiftProtobufTests/Test_TextFormatDecodingOptions.swift

@@ -38,7 +38,7 @@ final class Test_TextFormatDecodingOptions: XCTestCase {
                 if !expectSuccess {
                     XCTFail("Should not have succeed, limit: \(limit)")
                 }
-            } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.messageDepthLimit()) {
+            } catch TextFormatDecodingError.messageDepthLimit {
                 if expectSuccess {
                     XCTFail("Decode failed because of limit, but should *NOT* have, limit: \(limit)")
                 } else {

+ 14 - 14
Tests/SwiftProtobufTests/Test_TextFormat_Unknown.swift

@@ -41,7 +41,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -61,7 +61,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -81,7 +81,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -102,7 +102,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -124,7 +124,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -144,7 +144,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -165,7 +165,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -186,7 +186,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -206,7 +206,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -248,7 +248,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -281,7 +281,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -301,7 +301,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -352,7 +352,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 
@@ -376,7 +376,7 @@ final class Test_TextFormat_Unknown: XCTestCase, PBTestHelpers {
         do {
             let _ = try MessageTestType(textFormatString: text)
             XCTFail("Shouldn't get here")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .TextFormatDecoding.unknownField()) {
+        } catch TextFormatDecodingError.unknownField {
             // This is what should have happened.
         }
 

+ 1 - 1
Tests/SwiftProtobufTests/Test_Wrappers.swift

@@ -25,7 +25,7 @@ final class Test_Wrappers: XCTestCase {
         do {
             _ = try type.init(jsonString: "null")
             XCTFail("Expected decode to throw .illegalNull, but it succeeded")
-        } catch let error as SwiftProtobufError where self.isSwiftProtobufErrorEqual(error, .JSONDecoding.illegalNull()) {
+        } catch JSONDecodingError.illegalNull {
             // Nothing to do; this is the expected error.
         } catch {
             XCTFail("Expected decode to throw .illegalNull, but instead it threw: \(error)")