|
14 | 14 | * limitations under the License. |
15 | 15 | */ |
16 | 16 |
|
17 | | -import Foundation |
18 | 17 | import GRPCCore |
19 | 18 |
|
20 | | -struct JSONSerializer<Message: Encodable>: MessageSerializer { |
21 | | - private let encoder = JSONEncoder() |
| 19 | +import struct Foundation.Data |
| 20 | +import class Foundation.JSONDecoder |
| 21 | +import class Foundation.JSONEncoder |
22 | 22 |
|
23 | | - func serialize(_ message: Message) throws -> [UInt8] { |
24 | | - let data = try self.encoder.encode(message) |
25 | | - return Array(data) |
| 23 | +struct JSONSerializer<Message: Codable>: MessageSerializer { |
| 24 | + func serialize<Bytes: GRPCContiguousBytes>(_ message: Message) throws -> Bytes { |
| 25 | + do { |
| 26 | + let jsonEncoder = JSONEncoder() |
| 27 | + let data = try jsonEncoder.encode(message) |
| 28 | + return Bytes(data) |
| 29 | + } catch { |
| 30 | + throw RPCError(code: .internalError, message: "Can't serialize message to JSON. \(error)") |
| 31 | + } |
26 | 32 | } |
27 | 33 | } |
28 | 34 |
|
29 | | -struct JSONDeserializer<Message: Decodable>: MessageDeserializer { |
30 | | - private let decoder = JSONDecoder() |
31 | | - |
32 | | - func deserialize(_ serializedMessageBytes: [UInt8]) throws -> Message { |
33 | | - try self.decoder.decode(Message.self, from: Data(serializedMessageBytes)) |
| 35 | +struct JSONDeserializer<Message: Codable>: MessageDeserializer { |
| 36 | + func deserialize<Bytes: GRPCContiguousBytes>(_ serializedMessageBytes: Bytes) throws -> Message { |
| 37 | + do { |
| 38 | + let jsonDecoder = JSONDecoder() |
| 39 | + let data = serializedMessageBytes.withUnsafeBytes { Data($0) } |
| 40 | + return try jsonDecoder.decode(Message.self, from: data) |
| 41 | + } catch { |
| 42 | + throw RPCError(code: .internalError, message: "Can't deserialze message from JSON. \(error)") |
| 43 | + } |
34 | 44 | } |
35 | 45 | } |
0 commit comments