|
| 1 | +//===--- Backtrace+Codable.swift ------------------------------*- swift -*-===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | +// |
| 13 | +// Defines the Codable conformance for Backtrace. |
| 14 | +// |
| 15 | +//===----------------------------------------------------------------------===// |
| 16 | + |
| 17 | +import Swift |
| 18 | + |
| 19 | +func stringFrom(sequence: some Sequence<UTF8.CodeUnit>) -> String? { |
| 20 | + if #available(macOS 15.0, *) { |
| 21 | + return String(validating: sequence, as: UTF8.self) |
| 22 | + } else { |
| 23 | + let bytes = Array(sequence) |
| 24 | + return String(decoding: bytes, as: UTF8.self) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +@available(macOS 15.0, *) |
| 29 | +extension Backtrace: Codable { |
| 30 | + |
| 31 | + enum CodingKeys: CodingKey { |
| 32 | + case architecture |
| 33 | + case backtrace |
| 34 | + case imageMap |
| 35 | + } |
| 36 | + |
| 37 | + public init(from decoder: any Decoder) throws { |
| 38 | + let values = try decoder.container(keyedBy: CodingKeys.self) |
| 39 | + self.architecture = try values.decode(String.self, forKey: .architecture) |
| 40 | + |
| 41 | + let backtraceB64 = try values.decode(String.self, forKey: .backtrace) |
| 42 | + self.representation = Array(Base64Decoder(source: backtraceB64.utf8)) |
| 43 | + |
| 44 | + if let imageMapB64 = try values.decodeIfPresent(String.self, |
| 45 | + forKey: .imageMap) { |
| 46 | + self.images = ImageMap(compactImageMapData: |
| 47 | + Base64Decoder(source: imageMapB64.utf8)) |
| 48 | + } else { |
| 49 | + self.images = nil |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public func encode(to encoder: any Encoder) throws { |
| 54 | + var values = encoder.container(keyedBy: CodingKeys.self) |
| 55 | + try values.encode(architecture, forKey: .architecture) |
| 56 | + |
| 57 | + let backtraceB64 = stringFrom(sequence: |
| 58 | + Base64Encoder(source: self.representation)) |
| 59 | + try values.encode(backtraceB64, forKey: .backtrace) |
| 60 | + |
| 61 | + if let imageMap = self.images { |
| 62 | + let encoder = CompactImageMapFormat.Encoder(imageMap) |
| 63 | + let imageMapB64 = stringFrom(sequence: |
| 64 | + Base64Encoder(source: encoder)) |
| 65 | + try values.encode(imageMapB64, forKey: .imageMap) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | +} |
0 commit comments